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 scanTargetTwice( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, + FenceIdentity fence, + long startedAt) { + Set first = scanOnce(cohort, fence, startedAt); + requireFenceAndTime(cohort, fence, startedAt); + Set second = scanOnce(cohort, fence, startedAt); + requireFenceAndTime(cohort, fence, startedAt); + if (!first.equals(second)) { + throw conflict("Target Redis inventory changed between complete fenced scans"); + } + return first; + } + + private Set scanOnce( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, + FenceIdentity fence, + long startedAt) { + Set scanned = + redis.execute( + (RedisCallback>) + connection -> scanConnection(connection, cohort, fence, startedAt)); + if (scanned == null) { + throw conflict("Target Redis cursor returned no complete namespace inventory"); + } + return scanned; + } + + private Set scanConnection( + RedisConnection connection, + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, + FenceIdentity fence, + long startedAt) { + requireFenceAndTime(cohort, fence, startedAt); + if (connection instanceof RedisClusterConnection) { + throw conflict( + "Target Redis cluster scan cannot prove complete cluster-wide namespace coverage"); + } + try { + CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology( + connection.serverCommands().info("cluster")); + } catch (RuntimeException unprovenTopology) { + throw conflict("Target Redis standalone topology could not be proven"); + } + + Set keys = new TreeSet<>(); + ScanOptions options = + ScanOptions.scanOptions().match(SCAN_PATTERN).count(limits.scanCount()).build(); + try (Cursor cursor = connection.scan(options)) { + if (cursor == null) { + throw conflict("Target Redis cursor was unavailable"); + } + int visited = 0; + int sinceFenceCheck = 0; + while (true) { + requireWithinTime(startedAt); + boolean hasNext = cursor.hasNext(); + requireWithinTime(startedAt); + if (!hasNext) { + break; + } + String key = decodeKey(cursor.next()); + if (!key.startsWith(TARGET_PREFIX)) { + throw conflict("Target Redis scan returned a key outside its pinned prefix"); + } + if (key.startsWith(ISSUER_GENERATION_PREFIX) && !isCanonicalIssuerProjectionKey(key)) { + throw conflict("Target Redis inventory contains a malformed issuer projection key"); + } + visited++; + if (visited > limits.maxVisitedKeys()) { + throw conflict("Target Redis cursor exceeded its duplicate-safe visit bound"); + } + // Redis SCAN may legitimately return the same key more than once. Deduplicate the + // structural inventory, but count every visit above so repeated output remains bounded. + keys.add(key); + if (keys.size() > limits.maxUniqueKeys()) { + throw conflict("Target Redis inventory exceeded its unique-key bound"); + } + if (++sinceFenceCheck >= limits.scanCount()) { + requireFenceAndTime(cohort, fence, startedAt); + sinceFenceCheck = 0; + } + } + if (cursor.getCursorId() != 0L) { + throw conflict("Target Redis cursor stopped before the terminal cursor identity"); + } + requireFenceAndTime(cohort, fence, startedAt); + return Set.copyOf(keys); + } catch (CanonicalGameplayBindingInventoryConflictException rejected) { + throw rejected; + } catch (RuntimeException incompleteCursor) { + throw conflict("Target Redis cursor failed before complete exhaustion"); + } + } + + private void requireStandaloneRedisTopology() { + try { + Boolean validated = + redis.execute( + (RedisCallback) + connection -> { + CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology( + connection.serverCommands().info("cluster")); + return Boolean.TRUE; + }); + if (!Boolean.TRUE.equals(validated)) { + throw conflict("Target Redis standalone topology could not be proven"); + } + } catch (CanonicalGameplayBindingInventoryConflictException rejected) { + throw rejected; + } catch (RuntimeException unavailableTopology) { + throw conflict("Target Redis standalone topology could not be proven"); + } + } + + private void requireNoNamespaceKeys(Set keys) { + if (keys.stream().anyMatch(key -> !isCanonicalIssuerProjectionKey(key))) { + throw conflict("Target Redis session or index family is retained or unknown"); + } + } + + private void requireFenceAndTime( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, + FenceIdentity expected, + long startedAt) { + requireWithinTime(startedAt); + requireSameIdentity(cohort, expected); + cohort.requireStillFenced(expected.storageIdentity()); + requireSameIdentity(cohort, expected); + requireWithinTime(startedAt); + } + + private static void requireSameIdentity( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, FenceIdentity expected) { + if (!expected.equals(FenceIdentity.capture(cohort))) { + throw conflict("Target Redis cohort identity or writer fence changed during reconciliation"); + } + } + + private void requireWithinTime(long startedAt) { + if (System.nanoTime() - startedAt >= limits.maxDuration().toNanos()) { + throw conflict("Target Redis inventory exceeded its time bound"); + } + } + + private static void requireEmptyCanonicalSnapshot( + CanonicalGameplayBindingInventorySnapshot snapshot) { + Objects.requireNonNull(snapshot, "canonicalSnapshot"); + // The real inventory revision is retained by the owner, but its numeric value is never used as + // a substitute for enumerating every canonical row and repair-obligation family. + if (!snapshot.bindings().isEmpty() + || !snapshot.transitions().isEmpty() + || !snapshot.reservations().isEmpty() + || !snapshot.accountIndexObligations().isEmpty() + || !snapshot.issuerIndexObligations().isEmpty() + || !snapshot.regionBridgeObligations().isEmpty()) { + throw conflict( + "Nonempty canonical gameplay inventory is unsupported by the fresh reconciler"); + } + } + + private static void requireEmptyLegacySnapshot( + CanonicalGameplayLegacyMigrationSourceSnapshot snapshot, String sourceName) { + Objects.requireNonNull(snapshot, sourceName); + if (!snapshot.enumeratedEveryKnownFamily() || !snapshot.entries().isEmpty()) { + throw conflict("Complete empty legacy source inventory is required before reconciliation"); + } + } + + private String decodeKey(byte[] serializedKey) { + if (serializedKey == null + || serializedKey.length == 0 + || serializedKey.length > limits.maxKeyBytes()) { + throw conflict("Target Redis key is empty or exceeds its byte bound"); + } + try { + String key = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(serializedKey)) + .toString(); + if (!key.equals(key.strip()) || key.chars().anyMatch(Character::isISOControl)) { + throw conflict("Target Redis key is not a canonical text key"); + } + return key; + } catch (CharacterCodingException malformedUtf8) { + throw conflict("Target Redis key is not valid UTF-8"); + } + } + + private static boolean isCanonicalIssuerProjectionKey(String key) { + if (!key.startsWith(ISSUER_GENERATION_PREFIX)) { + return false; + } + String issuerId = key.substring(ISSUER_GENERATION_PREFIX.length()); + if (!CANONICAL_UUID.matcher(issuerId).matches()) { + return false; + } + try { + UUID parsed = UUID.fromString(issuerId); + return !NIL_UUID.equals(parsed) && parsed.toString().equals(issuerId); + } catch (IllegalArgumentException malformedUuid) { + return false; + } + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + record ScanLimits( + int scanCount, int maxUniqueKeys, int maxVisitedKeys, int maxKeyBytes, Duration maxDuration) { + ScanLimits { + Objects.requireNonNull(maxDuration, "maxDuration"); + if (scanCount <= 0 + || maxUniqueKeys <= 0 + || maxVisitedKeys < maxUniqueKeys + || maxKeyBytes <= 0 + || maxDuration.isZero() + || maxDuration.isNegative()) { + throw new IllegalArgumentException( + "target Redis scan limits must be positive and coherent"); + } + } + } + + private record FenceIdentity( + UUID cohortId, + UUID legacyWriterFence, + CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity) { + private FenceIdentity { + Objects.requireNonNull(cohortId, "cohortId"); + Objects.requireNonNull(legacyWriterFence, "legacyWriterFence"); + Objects.requireNonNull(storageIdentity, "storageIdentity"); + if (NIL_UUID.equals(cohortId) || NIL_UUID.equals(legacyWriterFence)) { + throw conflict("Target Redis reconciler requires non-nil cohort and writer-fence ids"); + } + } + + private static FenceIdentity capture( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort) { + return new FenceIdentity( + cohort.cohortId(), cohort.legacyWriterFence(), cohort.storageIdentity()); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOperation.java new file mode 100644 index 0000000000..7198110ea8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOperation.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; + +/** Package-private owner state loaded only from Game Session's V33 operation row. */ +record CanonicalGameplayLegacyMigrationOperation( + UUID operationId, + UUID cohortId, + UUID legacyWriterFence, + CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity, + State state, + BigInteger sourceSnapshotRevision, + BigInteger canonicalSnapshotRevision, + BigInteger publicationInventoryRevision, + String sourceSnapshotDigest, + String canonicalSnapshotDigest, + String rebuildDigest, + BigInteger namespaceIndexReadbackRevision, + String namespaceIndexReadbackDigest, + String evidenceDigest, + String blockedReason) { + CanonicalGameplayLegacyMigrationOperation { + requireNonNil(operationId, "operationId"); + requireNonNil(cohortId, "cohortId"); + requireNonNil(legacyWriterFence, "legacyWriterFence"); + Objects.requireNonNull(storageIdentity, "storageIdentity"); + Objects.requireNonNull(state, "state"); + if (state == State.FENCED || (state == State.BLOCKED && sourceSnapshotRevision == null)) { + if (sourceSnapshotRevision != null + || canonicalSnapshotRevision != null + || publicationInventoryRevision != null + || sourceSnapshotDigest != null + || canonicalSnapshotDigest != null + || rebuildDigest != null + || namespaceIndexReadbackRevision != null + || namespaceIndexReadbackDigest != null + || evidenceDigest != null + || (state == State.FENCED && blockedReason != null) + || (state == State.BLOCKED && (blockedReason == null || blockedReason.isBlank()))) { + throw new IllegalArgumentException( + "Pre-snapshot operation cannot carry later-stage evidence"); + } + } else { + requirePositive(sourceSnapshotRevision, "sourceSnapshotRevision"); + requireNonNegative(canonicalSnapshotRevision, "canonicalSnapshotRevision"); + requireDigest(sourceSnapshotDigest, "sourceSnapshotDigest"); + requireDigest(canonicalSnapshotDigest, "canonicalSnapshotDigest"); + if (state == State.BLOCKED && (blockedReason == null || blockedReason.isBlank())) { + throw new IllegalArgumentException("BLOCKED operation must retain its reason"); + } + if (state == State.REBUILT || state == State.READBACK_VERIFIED || state == State.VERIFIED) { + requireDigest(rebuildDigest, "rebuildDigest"); + } + if (state == State.READBACK_VERIFIED || state == State.VERIFIED) { + requirePositive(namespaceIndexReadbackRevision, "namespaceIndexReadbackRevision"); + requireDigest(namespaceIndexReadbackDigest, "namespaceIndexReadbackDigest"); + } + if (state == State.VERIFIED) { + requirePositive(publicationInventoryRevision, "publicationInventoryRevision"); + requireDigest(evidenceDigest, "evidenceDigest"); + } + } + } + + enum State { + FENCED, + SNAPSHOTTED, + REBUILT, + READBACK_VERIFIED, + BLOCKED, + VERIFIED + } + + 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"); + } + } + + private static void requireNonNegative(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() < 0) { + throw new IllegalArgumentException(name + " must not be negative"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwner.java new file mode 100644 index 0000000000..24d700e286 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwner.java @@ -0,0 +1,185 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; +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.transaction.support.TransactionSynchronizationManager; + +/** + * Non-bean Game Session owner flow. There is intentionally no default cohort, legacy-source, or + * Redis-index adapter: without all three trusted implementations this package-private operation + * cannot be composed or invoked. The current Redis-index adapter supports only a fully inventoried + * empty cohort; it does not serialize or rebuild active gameplay session records. + */ +final class CanonicalGameplayLegacyMigrationOwner { + private final CanonicalGameplayLegacyMigrationRepository migration; + private final CanonicalGameplayBindingInventoryRepository inventory; + private final ProtectedCohortProvider cohortProvider; + private final CompleteLegacySource legacySource; + private final NamespaceIndexOwner namespaceIndex; + + CanonicalGameplayLegacyMigrationOwner( + CanonicalGameplayLegacyMigrationRepository migration, + CanonicalGameplayBindingInventoryRepository inventory, + ProtectedCohortProvider cohortProvider, + CompleteLegacySource legacySource, + NamespaceIndexOwner namespaceIndex) { + this.migration = Objects.requireNonNull(migration, "migration"); + this.inventory = Objects.requireNonNull(inventory, "inventory"); + this.cohortProvider = Objects.requireNonNull(cohortProvider, "cohortProvider"); + this.legacySource = Objects.requireNonNull(legacySource, "legacySource"); + this.namespaceIndex = Objects.requireNonNull(namespaceIndex, "namespaceIndex"); + } + + /** + * Replays one fenced cohort through durable snapshot, exact replacement, readback, and V31 + * publication. Admission remains fenced; this owner has no fence-release or activation method. + */ + CanonicalGameplayLegacyMigrationOperation migrate() { + requireNoAmbientTransaction(); + FencedCohort cohort = + Objects.requireNonNull( + cohortProvider.requireProtectedDisposableCohort(), + "protected disposable cohort provider returned no cohort"); + CanonicalGameplayLegacyMigrationStorageIdentity identity = + Objects.requireNonNull(cohort.storageIdentity(), "cohort storage identity"); + cohort.requireStillFenced(identity); + CanonicalGameplayLegacyMigrationOperation operation = + migration.begin(cohort.cohortId(), cohort.legacyWriterFence(), identity); + try { + cohort.requireStillFenced(identity); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED + || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED) { + return operation; + } + + CanonicalGameplayLegacyMigrationSourceSnapshot source; + CanonicalGameplayBindingInventorySnapshot canonical; + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.FENCED + || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.SNAPSHOTTED) { + cohort.requireStillFenced(identity); + source = + Objects.requireNonNull( + legacySource.captureEveryKnownFamily(cohort), + "legacy source adapter returned no complete structural inventory"); + cohort.requireStillFenced(identity); + } else { + // The exact sanitized pre-mutation source inventory is durable. Re-scanning after a + // successful replacement would compare against the intentionally removed old keys. + source = migration.readSourceSnapshot(operation.operationId()); + } + + cohort.requireStillFenced(identity); + canonical = inventory.readSnapshot(); + cohort.requireStillFenced(identity); + operation = migration.captureSnapshots(operation.operationId(), source, canonical); + cohort.requireStillFenced(identity); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED) { + return operation; + } + + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.SNAPSHOTTED) { + cohort.requireStillFenced(identity); + namespaceIndex.rebuildExact(cohort, source, canonical); + cohort.requireStillFenced(identity); + operation = migration.markRebuilt(operation.operationId()); + } + + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.REBUILT + || operation.state() + == CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + canonical = inventory.readSnapshot(); + cohort.requireStillFenced(identity); + CanonicalGameplayLegacyMigrationReadback readback = + Objects.requireNonNull( + namespaceIndex.readBackExact(cohort, canonical), + "namespace index owner returned no exact readback"); + cohort.requireStillFenced(identity); + operation = migration.recordReadback(operation.operationId(), canonical, readback); + } + + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED) { + return operation; + } + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + throw new IllegalStateException( + "Migration owner did not reach exact readback verification"); + } + cohort.requireStillFenced(identity); + return migration.publishVerified(operation.operationId(), cohort); + } catch (RuntimeException ambiguous) { + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.VERIFIED + && operation.state() != CanonicalGameplayLegacyMigrationOperation.State.BLOCKED) { + try { + migration.block(operation.operationId(), "OWNER_ADAPTER_AMBIGUOUS"); + } catch (RuntimeException persistFailure) { + ambiguous.addSuppressed(persistFailure); + } + } + throw new CanonicalGameplayBindingInventoryConflictException( + "Legacy migration remains fenced and unresolved; retain the same cohort and operation", + ambiguous); + } + } + + /** Existing authenticated factory must provide the actual cluster/storage identity and fence. */ + interface ProtectedCohortProvider { + FencedCohort requireProtectedDisposableCohort(); + } + + /** + * Live retained-fence handle. Implementations must re-observe the exact Kubernetes/PG/Redis + * identities and all-writer/admission exclusions on every call; no release operation is exposed. + */ + interface FencedCohort { + UUID cohortId(); + + UUID legacyWriterFence(); + + CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity(); + + void requireStillFenced(CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity); + } + + /** Reads every actual legacy key family, decodes only through the trusted GS serializer owner. */ + interface CompleteLegacySource { + CanonicalGameplayLegacyMigrationSourceSnapshot captureEveryKnownFamily(FencedCohort cohort); + } + + /** Exact namespace reconciliation and full Redis readback owner contract. */ + interface NamespaceIndexOwner { + /** + * The current owner admits only a completely enumerated empty legacy snapshot and a complete + * durable snapshot with no bindings, transitions, reservations, or repair obligations. Its + * fresh-cohort implementation proves the target session/index namespace is physically empty + * with bounded repeated scans and performs no writes. Only the separately owned canonical + * issuer-generation projection family is excluded from this namespace result and remains + * subject to its independent owner gate. Any retained session/index key, unknown key, nonempty + * legacy family, or nonempty canonical row remains blocked and untouched. This is not an + * active-row rebuild implementation. + */ + void rebuildExact( + FencedCohort cohort, + CanonicalGameplayLegacyMigrationSourceSnapshot legacySnapshot, + CanonicalGameplayBindingInventorySnapshot canonicalSnapshot); + + /** + * Independently re-inventories legacy families and all target Redis families under the same + * cohort fence. The current empty-only implementation returns empty rows only after complete + * repeated physical scans confirm no retained keys; counts or caller-provided digests are not + * accepted. + */ + CanonicalGameplayLegacyMigrationReadback readBackExact( + FencedCohort cohort, CanonicalGameplayBindingInventorySnapshot canonicalSnapshot); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new CanonicalGameplayBindingInventoryConflictException( + "Legacy migration owner refuses to join an ambient Spring transaction"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepository.java new file mode 100644 index 0000000000..65eff3f7b3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepository.java @@ -0,0 +1,950 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry; +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.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session-owned durable phases for legacy controller-index migration. Package-private and + * deliberately not a Spring bean or a public receipt writer. + */ +final class CanonicalGameplayLegacyMigrationRepository { + private static final String OPERATION = "game_session_canonical_legacy_migration_operation"; + private static final String SOURCE_ENTRY = + "game_session_canonical_legacy_migration_source_snapshot_entry"; + private static final String LEGACY_DISPOSITION = + "game_session_canonical_binding_legacy_disposition"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + + private static final String CANONICAL_SNAPSHOT_SQL = + "SELECT c.inventory_revision, jsonb_build_object(" + + "'bindingGenerations', COALESCE((SELECT jsonb_agg(to_jsonb(g)" + + " ORDER BY g.tenant_id, g.playable_state_namespace_id, g.character_id)" + + " FROM game_session_canonical_binding_generation g), '[]'::jsonb)," + + "'bindings', COALESCE((SELECT jsonb_agg(to_jsonb(i) ORDER BY encode(i.binding_ref, 'hex'))" + + " FROM game_session_canonical_gameplay_binding_inventory i), '[]'::jsonb)," + + "'transitions', COALESCE((SELECT jsonb_agg(to_jsonb(t) ORDER BY t.transition_id)" + + " FROM game_session_canonical_binding_transition t), '[]'::jsonb)," + + "'reservations', COALESCE((SELECT jsonb_agg(to_jsonb(r) ORDER BY r.reservation_id)" + + " FROM game_session_canonical_issuer_partition_reservation r), '[]'::jsonb)," + + "'accountObligations', COALESCE((SELECT jsonb_agg(to_jsonb(a)" + + " ORDER BY a.transition_id, a.obligation_ordinal)" + + " FROM game_session_canonical_binding_account_index_obligation a), '[]'::jsonb)," + + "'issuerObligations', COALESCE((SELECT jsonb_agg(to_jsonb(i)" + + " ORDER BY i.transition_id, i.binding_ref)" + + " FROM game_session_canonical_binding_issuer_index_obligation i), '[]'::jsonb)," + + "'regionObligations', COALESCE((SELECT jsonb_agg(to_jsonb(g) ORDER BY g.transition_id)" + + " FROM game_session_canonical_binding_region_bridge_obligation g), '[]'::jsonb))::text AS snapshot_json" + + " FROM " + + INVENTORY_CLOCK + + " c WHERE c.singleton_id = 1"; + private static final String HAS_FUTURE_REVISION_SQL = + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.inventory_revision > c.inventory_revision)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition t" + + " WHERE t.inventory_revision > c.inventory_revision)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.inventory_revision > c.inventory_revision)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation a" + + " WHERE a.inventory_revision > c.inventory_revision)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation i" + + " WHERE i.inventory_revision > c.inventory_revision)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation g" + + " WHERE g.inventory_revision > c.inventory_revision) AS has_future_revision" + + " FROM " + + INVENTORY_CLOCK + + " c WHERE c.singleton_id = 1"; + + private final DSLContext dsl; + private final CanonicalGameplayBindingInventoryRepository inventory; + + CanonicalGameplayLegacyMigrationRepository( + DSLContext dsl, CanonicalGameplayBindingInventoryRepository inventory) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.inventory = Objects.requireNonNull(inventory, "inventory"); + } + + /** Creates or resumes the one durable owner operation bound to this exact physical cohort. */ + CanonicalGameplayLegacyMigrationOperation begin( + UUID cohortId, + UUID legacyWriterFence, + CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity) { + requireNoAmbientTransaction(); + requireNonNil(cohortId, "cohortId"); + requireNonNil(legacyWriterFence, "legacyWriterFence"); + Objects.requireNonNull(storageIdentity, "storageIdentity"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE cohort_id = ? FOR UPDATE", cohortId); + if (existing != null) { + CanonicalGameplayLegacyMigrationOperation operation = toOperation(existing); + if (!operation.legacyWriterFence().equals(legacyWriterFence) + || !operation.storageIdentity().equals(storageIdentity)) { + throw conflict( + "The cohort is already bound to a different retained writer/storage fence"); + } + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + requirePublishedDispositionMatches(transaction, operation); + } + return operation; + } + + Record disposition = + transaction.fetchOne( + "SELECT disposition_state FROM " + + LEGACY_DISPOSITION + + " WHERE singleton_id = 1 FOR UPDATE"); + if (disposition == null + || !"REQUIRED".equals(disposition.get("disposition_state", String.class))) { + throw conflict( + "Legacy migration can start only while the V31 disposition remains REQUIRED"); + } + + UUID operationId = UUID.randomUUID(); + if (operationId.equals(new UUID(0L, 0L))) { + throw new IllegalStateException("UUID generator returned nil migration operation id"); + } + insertOperation(transaction, operationId, cohortId, legacyWriterFence, storageIdentity); + return readOperation(transaction, operationId, false); + }); + } + + CanonicalGameplayLegacyMigrationOperation read(UUID operationId) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + return dsl.transactionResult( + configuration -> readOperation(DSL.using(configuration), operationId, false)); + } + + /** Rehydrates only the persisted sanitized source snapshot for deterministic restart replay. */ + CanonicalGameplayLegacyMigrationSourceSnapshot readSourceSnapshot(UUID operationId) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + return dsl.transactionResult( + configuration -> loadSourceSnapshot(DSL.using(configuration), operationId)); + } + + /** + * Persists the complete typed repository snapshot and only credential-free legacy structure. Only + * a completely enumerated empty legacy source is eligible to proceed. Any retained row, unknown + * family, credential, or incomplete scan is durably BLOCKED rather than treated as empty. + */ + CanonicalGameplayLegacyMigrationOperation captureSnapshots( + UUID operationId, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + CanonicalGameplayBindingInventorySnapshot canonical) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(canonical, "canonical"); + CanonicalGameplayBindingInventorySnapshot actualCanonical = inventory.readSnapshot(); + if (!actualCanonical.equals(canonical)) { + return block(operationId, "CANONICAL_SNAPSHOT_NOT_FROM_OWNER_REPOSITORY"); + } + CanonicalGameplayLegacyMigrationOperation.State blockState = null; + String blockReason = null; + if (!source.enumeratedEveryKnownFamily()) { + blockState = CanonicalGameplayLegacyMigrationOperation.State.BLOCKED; + blockReason = "SOURCE_INVENTORY_INCOMPLETE"; + } else if (source.entries().stream() + .anyMatch( + entry -> + entry.disposition() + == CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition + .CREDENTIAL_BEARING)) { + blockState = CanonicalGameplayLegacyMigrationOperation.State.BLOCKED; + blockReason = "CREDENTIAL_BEARING_SOURCE"; + } else if (source.entries().stream() + .anyMatch( + entry -> + entry.disposition() + == CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN)) { + blockState = CanonicalGameplayLegacyMigrationOperation.State.BLOCKED; + blockReason = "UNKNOWN_SOURCE_RECORD"; + } else if (!source.everyEntryIsReconciled()) { + blockState = CanonicalGameplayLegacyMigrationOperation.State.BLOCKED; + blockReason = "UNMAPPABLE_SOURCE_RECORD"; + } + final CanonicalGameplayLegacyMigrationOperation.State finalBlockState = blockState; + final String finalBlockReason = blockReason; + String sourceDigest = digestSource(source); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record operationRow = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation current = toOperation(operationRow); + if (current.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED + || current.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED) { + return current; + } + SnapshotJson snapshotJson = readCanonicalSnapshot(transaction); + if (!snapshotJson.revision().equals(canonical.inventoryRevision())) { + return block(transaction, operationId, "CANONICAL_SNAPSHOT_CHANGED"); + } + String canonicalDigest = sha256(snapshotJson.json()); + if (current.state() != CanonicalGameplayLegacyMigrationOperation.State.FENCED) { + if (!Objects.equals(current.sourceSnapshotDigest(), sourceDigest) + || !Objects.equals( + current.canonicalSnapshotRevision(), canonical.inventoryRevision()) + || !Objects.equals(current.canonicalSnapshotDigest(), canonicalDigest)) { + return block(transaction, operationId, "SNAPSHOT_CHANGED_ON_REPLAY"); + } + return current; + } + + BigInteger sourceRevision = + readBigInteger( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT nextval('game_session_canonical_legacy_migration_source_revision_seq') AS revision"), + "legacy migration source revision sequence must exist"), + "revision"); + long ordinal = 0L; + List entries = + source.entries().stream() + .sorted( + Comparator.comparing( + CanonicalGameplayLegacyMigrationSourceSnapshot.Entry::sourceKeyDigest)) + .toList(); + for (CanonicalGameplayLegacyMigrationSourceSnapshot.Entry entry : entries) { + transaction.execute( + "INSERT INTO " + + SOURCE_ENTRY + + " (operation_id, row_ordinal, source_family, source_key_digest, disposition)" + + " VALUES (?, ?, ?, ?, ?)", + operationId, + ordinal++, + entry.family().name(), + entry.sourceKeyDigest(), + entry.disposition().name()); + } + + String nextState = finalBlockState == null ? "SNAPSHOTTED" : "BLOCKED"; + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = ?, source_snapshot_revision = ?, source_snapshot_digest = ?," + + " source_snapshot_entry_count = ?, canonical_snapshot_revision = ?," + + " source_snapshot_families = ?::jsonb, canonical_snapshot_digest = ?, canonical_snapshot = ?::jsonb," + + " blocked_reason = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'FENCED'", + nextState, + decimal(sourceRevision), + sourceDigest, + entries.size(), + decimal(canonical.inventoryRevision()), + familiesJson(source.scannedFamilies()), + canonicalDigest, + snapshotJson.json(), + finalBlockReason, + operationId), + "Migration operation changed while its snapshots were being staged"); + return readOperation(transaction, operationId, false); + }); + } + + /** + * Records completion of the idempotent exact-replacement request; readback is still mandatory. + */ + CanonicalGameplayLegacyMigrationOperation markRebuilt(UUID operationId) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record row = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED + || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED + || operation.state() + == CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + return operation; + } + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.REBUILT) { + return operation; + } + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.SNAPSHOTTED) { + throw conflict("Only a complete staged source and canonical snapshot may be rebuilt"); + } + requireStoredSnapshotsConsistent(transaction, operation); + String expectedProjectionDigest = + expectedActiveProjectionDigest(transaction, operationId); + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = 'REBUILT', rebuild_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'SNAPSHOTTED'", + expectedProjectionDigest, + operationId), + "Migration operation changed before exact index rebuild was retained"); + return readOperation(transaction, operationId, false); + }); + } + + /** + * Persists only an exact full readback. A mismatch is durable BLOCKED evidence; no caller digest + * or count is accepted, and canonical rows are re-read through the typed inventory owner. + */ + CanonicalGameplayLegacyMigrationOperation recordReadback( + UUID operationId, + CanonicalGameplayBindingInventorySnapshot canonical, + CanonicalGameplayLegacyMigrationReadback readback) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(canonical, "canonical"); + Objects.requireNonNull(readback, "readback"); + CanonicalGameplayBindingInventorySnapshot actualCanonical = inventory.readSnapshot(); + if (!actualCanonical.equals(canonical)) { + return block(operationId, "CANONICAL_READBACK_NOT_FROM_OWNER_REPOSITORY"); + } + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record row = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED + || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + return operation; + } + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.REBUILT + && operation.state() + != CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + throw conflict("Exact namespace readback is not available before rebuild"); + } + requireStoredSnapshotsConsistent(transaction, operation); + SnapshotJson snapshotJson = readCanonicalSnapshot(transaction); + if (!snapshotJson.revision().equals(canonical.inventoryRevision()) + || !snapshotJson.revision().equals(operation.canonicalSnapshotRevision()) + || !sha256(snapshotJson.json()).equals(operation.canonicalSnapshotDigest())) { + return block(transaction, operationId, "CANONICAL_SNAPSHOT_CHANGED_BEFORE_READBACK"); + } + + List expected = activeBindings(actualCanonical); + if (!sameRows(expected, readback.sessionRecords()) + || !sameRows(expected, readback.characterIndexRecords()) + || !readback.remainingLegacySourceKeyDigests().isEmpty() + || !readback.unexpectedNamespaceKeyDigests().isEmpty()) { + return block(transaction, operationId, "INDEX_READBACK_MISMATCH"); + } + + String readbackDigest = digestReadback(readback); + if (operation.state() + == CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + if (!operation.namespaceIndexReadbackDigest().equals(readbackDigest)) { + return block(transaction, operationId, "READBACK_CHANGED_ON_REPLAY"); + } + return operation; + } + BigInteger readbackRevision = + readBigInteger( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT nextval('game_session_canonical_legacy_migration_readback_revision_seq') AS revision"), + "legacy migration readback revision sequence must exist"), + "revision"); + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = 'READBACK_VERIFIED', namespace_index_readback_revision = ?," + + " namespace_index_readback_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'REBUILT'", + decimal(readbackRevision), + readbackDigest, + operationId), + "Migration operation changed before exact index readback was retained"); + return readOperation(transaction, operationId, false); + }); + } + + /** + * The sole V31 publisher. The cohort fence is revalidated inside the same DB transaction and V31 + * plus the owner operation commit atomically. A zero snapshot clock is advanced only here, after + * complete source/readback proof; the original zero snapshot revision remains recorded. + */ + CanonicalGameplayLegacyMigrationOperation publishVerified( + UUID operationId, CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(cohort, "cohort"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record row = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); + requireSameCohort(operation, cohort); + cohort.requireStillFenced(operation.storageIdentity()); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + requirePublishedDispositionMatches(transaction, operation); + return operation; + } + if (operation.state() + != CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + throw conflict("Only exact complete readback evidence may publish the V31 disposition"); + } + + Record clock = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"), + "canonical inventory clock row must exist"); + BigInteger currentRevision = readBigInteger(clock, "inventory_revision"); + requireStoredSourceSnapshotConsistent(transaction, operation); + requireStoredCanonicalSnapshotConsistent(transaction, operation); + if (!currentRevision.equals(operation.canonicalSnapshotRevision())) { + throw conflict("Canonical inventory revision changed while migration fences were held"); + } + SnapshotJson currentSnapshot = readCanonicalSnapshot(transaction); + if (!currentSnapshot.revision().equals(currentRevision) + || !sha256(currentSnapshot.json()).equals(operation.canonicalSnapshotDigest())) { + throw conflict("Canonical durable inventory changed after staged readback"); + } + + BigInteger publicationRevision = currentRevision; + if (publicationRevision.signum() == 0) { + publicationRevision = BigInteger.ONE; + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY_CLOCK + + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = 0", + decimal(publicationRevision)), + "Empty canonical snapshot could not acquire its owner publication revision"); + } + String evidenceDigest = digestEvidence(operation, publicationRevision); + requireOne( + transaction.execute( + "UPDATE " + + LEGACY_DISPOSITION + + " SET disposition_state = 'VERIFIED', cohort_id = ?, owner_operation_id = ?," + + " legacy_writer_fence = ?, source_snapshot_revision = ?," + + " canonical_inventory_revision = ?, namespace_index_readback_revision = ?," + + " evidence_digest = ? WHERE singleton_id = 1 AND disposition_state = 'REQUIRED'", + operation.cohortId(), + operation.operationId(), + operation.legacyWriterFence(), + decimal(operation.sourceSnapshotRevision()), + decimal(publicationRevision), + decimal(operation.namespaceIndexReadbackRevision()), + evidenceDigest), + "V31 disposition was already changed by a different migration owner"); + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = 'VERIFIED', publication_inventory_revision = ?," + + " evidence_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'READBACK_VERIFIED'", + decimal(publicationRevision), + evidenceDigest, + operationId), + "Migration operation changed before atomic V31 publication"); + cohort.requireStillFenced(operation.storageIdentity()); + CanonicalGameplayLegacyMigrationOperation published = + readOperation(transaction, operationId, false); + requirePublishedDispositionMatches(transaction, published); + return published; + }); + } + + CanonicalGameplayLegacyMigrationOperation block(UUID operationId, String reason) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + if (reason == null || !reason.matches("[A-Z0-9_]{1,48}")) { + throw new IllegalArgumentException("blocked migration reason must be a bounded code"); + } + return dsl.transactionResult( + configuration -> block(DSL.using(configuration), operationId, reason)); + } + + private CanonicalGameplayLegacyMigrationOperation block( + DSLContext transaction, UUID operationId, String reason) { + Record currentRow = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation current = toOperation(currentRow); + if (current.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + throw conflict("A VERIFIED migration operation cannot be rewritten as blocked"); + } + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = 'BLOCKED', blocked_reason = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state <> 'VERIFIED'", + reason, + operationId), + "Migration operation changed before its blocking evidence was retained"); + return readOperation(transaction, operationId, false); + } + + private static void insertOperation( + DSLContext transaction, + UUID operationId, + UUID cohortId, + UUID legacyWriterFence, + CanonicalGameplayLegacyMigrationStorageIdentity identity) { + requireOne( + transaction.execute( + "INSERT INTO " + + OPERATION + + " (operation_id, cohort_id, legacy_writer_fence, state," + + " kubernetes_cluster_uid, kubernetes_namespace_uid, producer_pod_uid," + + " producer_container_id, producer_node_uid, postgres_system_identifier," + + " postgres_database_oid, postgres_storage_uid, redis_run_id, redis_storage_uid," + + " storage_identity_digest)" + + " VALUES (?, ?, ?, 'FENCED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + cohortId, + legacyWriterFence, + identity.kubernetesClusterUid(), + identity.kubernetesNamespaceUid(), + identity.producerPodUid(), + identity.producerContainerId(), + identity.producerNodeUid(), + new BigDecimal(identity.postgresSystemIdentifier()), + identity.postgresDatabaseOid(), + identity.postgresStorageUid(), + identity.redisRunId(), + identity.redisStorageUid(), + identity.digest()), + "Migration operation could not bind its exact cohort, writer fence, and storage identity"); + } + + private static Record lockOperation(DSLContext transaction, UUID operationId) { + return Objects.requireNonNull( + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", operationId), + "legacy migration operation does not exist"); + } + + private static CanonicalGameplayLegacyMigrationOperation readOperation( + DSLContext transaction, UUID operationId, boolean forUpdate) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + + OPERATION + + " WHERE operation_id = ?" + + (forUpdate ? " FOR UPDATE" : ""), + operationId); + if (row == null) { + throw conflict("Legacy migration operation does not exist"); + } + return toOperation(row); + } + + private static CanonicalGameplayLegacyMigrationSourceSnapshot loadSourceSnapshot( + DSLContext transaction, UUID operationId) { + Record operation = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT source_snapshot_revision, source_snapshot_digest," + + " source_snapshot_entry_count, source_snapshot_families::text AS source_families" + + " FROM " + + OPERATION + + " WHERE operation_id = ?", + operationId), + "legacy migration operation does not exist"); + if (operation.get("source_snapshot_revision", BigDecimal.class) == null) { + throw conflict("Legacy source snapshot has not been staged"); + } + var families = parseFamilies(operation.get("source_families", String.class)); + List entries = + transaction + .fetch( + "SELECT source_family, source_key_digest, disposition" + + " FROM " + + SOURCE_ENTRY + + " WHERE operation_id = ? ORDER BY row_ordinal", + operationId) + .map( + row -> { + return new CanonicalGameplayLegacyMigrationSourceSnapshot.Entry( + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.valueOf( + row.get("source_family", String.class)), + row.get("source_key_digest", String.class), + CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.valueOf( + row.get("disposition", String.class))); + }); + Long storedEntryCount = operation.get("source_snapshot_entry_count", Long.class); + if (!Objects.equals(storedEntryCount, (long) entries.size())) { + throw conflict("Persisted legacy source inventory entry count is incomplete"); + } + CanonicalGameplayLegacyMigrationSourceSnapshot snapshot = + new CanonicalGameplayLegacyMigrationSourceSnapshot(families, entries); + if (!digestSource(snapshot).equals(operation.get("source_snapshot_digest", String.class))) { + throw conflict("Persisted sanitized legacy source snapshot digest is malformed"); + } + return snapshot; + } + + private static void requireStoredSnapshotsConsistent( + DSLContext transaction, CanonicalGameplayLegacyMigrationOperation operation) { + requireStoredSourceSnapshotConsistent(transaction, operation); + requireStoredCanonicalSnapshotConsistent(transaction, operation); + SnapshotJson currentSnapshot = readCanonicalSnapshot(transaction); + if (!currentSnapshot.revision().equals(operation.canonicalSnapshotRevision()) + || !sha256(currentSnapshot.json()).equals(operation.canonicalSnapshotDigest())) { + throw conflict("Canonical durable inventory changed after its complete snapshot was staged"); + } + } + + private static void requireStoredSourceSnapshotConsistent( + DSLContext transaction, CanonicalGameplayLegacyMigrationOperation operation) { + CanonicalGameplayLegacyMigrationSourceSnapshot source = + loadSourceSnapshot(transaction, operation.operationId()); + if (!digestSource(source).equals(operation.sourceSnapshotDigest())) { + throw conflict("Persisted sanitized legacy source inventory differs from its staged digest"); + } + } + + private static void requireStoredCanonicalSnapshotConsistent( + DSLContext transaction, CanonicalGameplayLegacyMigrationOperation operation) { + Record snapshotRow = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT canonical_snapshot::text AS canonical_snapshot_text FROM " + + OPERATION + + " WHERE operation_id = ?", + operation.operationId()), + "migration operation must retain its canonical snapshot"); + String snapshotText = snapshotRow.get("canonical_snapshot_text", String.class); + if (snapshotText == null || !sha256(snapshotText).equals(operation.canonicalSnapshotDigest())) { + throw conflict("Persisted canonical migration snapshot differs from its staged digest"); + } + } + + private static CanonicalGameplayLegacyMigrationOperation toOperation(Record row) { + BigDecimal systemId = row.get("postgres_system_identifier", BigDecimal.class); + CanonicalGameplayLegacyMigrationStorageIdentity identity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + row.get("kubernetes_cluster_uid", String.class), + row.get("kubernetes_namespace_uid", String.class), + row.get("producer_pod_uid", String.class), + row.get("producer_container_id", String.class), + row.get("producer_node_uid", String.class), + Objects.requireNonNull(systemId, "PostgreSQL system identity must be present") + .toBigIntegerExact() + .toString(), + row.get("postgres_database_oid", Long.class), + row.get("postgres_storage_uid", String.class), + row.get("redis_run_id", String.class), + row.get("redis_storage_uid", String.class)); + if (!identity.digest().equals(row.get("storage_identity_digest", String.class))) { + throw conflict("Stored immutable storage identity digest is malformed"); + } + return new CanonicalGameplayLegacyMigrationOperation( + row.get("operation_id", UUID.class), + row.get("cohort_id", UUID.class), + row.get("legacy_writer_fence", UUID.class), + identity, + CanonicalGameplayLegacyMigrationOperation.State.valueOf(row.get("state", String.class)), + readNullableBigInteger(row, "source_snapshot_revision"), + readNullableBigInteger(row, "canonical_snapshot_revision"), + readNullableBigInteger(row, "publication_inventory_revision"), + row.get("source_snapshot_digest", String.class), + row.get("canonical_snapshot_digest", String.class), + row.get("rebuild_digest", String.class), + readNullableBigInteger(row, "namespace_index_readback_revision"), + row.get("namespace_index_readback_digest", String.class), + row.get("evidence_digest", String.class), + row.get("blocked_reason", String.class)); + } + + private static SnapshotJson readCanonicalSnapshot(DSLContext transaction) { + Record revisionCheck = + Objects.requireNonNull( + transaction.fetchOne(HAS_FUTURE_REVISION_SQL), + "canonical inventory clock and revision families must exist"); + if (!Boolean.FALSE.equals(revisionCheck.get("has_future_revision", Boolean.class))) { + throw conflict("Canonical durable family contains rows beyond the inventory clock"); + } + Record row = + Objects.requireNonNull( + transaction.fetchOne(CANONICAL_SNAPSHOT_SQL), + "canonical inventory clock and snapshot tables must exist"); + return new SnapshotJson( + readBigInteger(row, "inventory_revision"), row.get("snapshot_json", String.class)); + } + + private static String expectedActiveProjectionDigest(DSLContext transaction, UUID operationId) { + Record row = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT COALESCE(jsonb_agg(binding ORDER BY binding->>'binding_ref'), '[]'::jsonb)::text" + + " AS active_projection FROM " + + OPERATION + + " o CROSS JOIN LATERAL jsonb_array_elements(o.canonical_snapshot->'bindings') AS items(binding)" + + " WHERE o.operation_id = ? AND binding->>'lifecycle' = 'ACTIVE'", + operationId), + "migration canonical snapshot must exist"); + return sha256(row.get("active_projection", String.class)); + } + + private static List activeBindings( + CanonicalGameplayBindingInventorySnapshot snapshot) { + return snapshot.bindings().stream() + .filter( + binding -> + binding.lifecycle() == CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE) + .sorted(Comparator.comparing(binding -> hex(binding.bindingRef().bytes()))) + .toList(); + } + + private static boolean sameRows( + List expected, + List actual) { + return activeSorted(expected).equals(activeSorted(actual)); + } + + private static List activeSorted( + List rows) { + return rows.stream() + .sorted(Comparator.comparing(binding -> hex(binding.bindingRef().bytes()))) + .toList(); + } + + private static String digestSource(CanonicalGameplayLegacyMigrationSourceSnapshot source) { + StringBuilder framed = new StringBuilder("canonical-gameplay-legacy-source/v1|"); + source.scannedFamilies().stream() + .map(Enum::name) + .sorted() + .forEach(family -> append(framed, family)); + source.entries().stream() + .sorted( + Comparator.comparing( + CanonicalGameplayLegacyMigrationSourceSnapshot.Entry::sourceKeyDigest)) + .forEach( + entry -> { + append(framed, entry.family().name()); + append(framed, entry.sourceKeyDigest()); + append(framed, entry.disposition().name()); + }); + return sha256(framed.toString()); + } + + private static String familiesJson( + java.util.Set families) { + return families.stream() + .map(Enum::name) + .sorted() + .map(value -> "\"" + value + "\"") + .collect(java.util.stream.Collectors.joining(",", "[", "]")); + } + + private static java.util.Set parseFamilies( + String json) { + String compact = json == null ? null : json.replaceAll("\\s+", ""); + if (compact == null || !compact.matches("\\[(\\\"[A-Z_]+\\\"(,\\\"[A-Z_]+\\\")*)?\\]")) { + throw conflict("Persisted legacy source-family inventory is malformed"); + } + String body = compact.substring(1, compact.length() - 1); + if (body.isEmpty()) { + return java.util.Set.of(); + } + java.util.Set families = + new java.util.HashSet<>(); + for (String token : body.split(",")) { + String name = token.substring(1, token.length() - 1); + if (!families.add(CanonicalGameplayLegacyMigrationSourceSnapshot.Family.valueOf(name))) { + throw conflict("Persisted legacy source-family inventory contains duplicates"); + } + } + return java.util.Set.copyOf(families); + } + + private static String digestReadback(CanonicalGameplayLegacyMigrationReadback readback) { + StringBuilder framed = new StringBuilder("canonical-gameplay-legacy-readback/v1|"); + framed.append("session|"); + readback.sessionRecords().stream() + .sorted(Comparator.comparing(binding -> hex(binding.bindingRef().bytes()))) + .forEach(binding -> append(framed, bindingFingerprint(binding))); + framed.append("index|"); + readback.characterIndexRecords().stream() + .sorted(Comparator.comparing(binding -> hex(binding.bindingRef().bytes()))) + .forEach(binding -> append(framed, bindingFingerprint(binding))); + readback.remainingLegacySourceKeyDigests().stream() + .sorted() + .forEach(value -> append(framed, value)); + readback.unexpectedNamespaceKeyDigests().stream() + .sorted() + .forEach(value -> append(framed, value)); + return sha256(framed.toString()); + } + + private static String bindingFingerprint(CanonicalGameplayBindingInventoryEntry binding) { + return binding.identity() + + "|" + + hex(binding.bindingRef().bytes()) + + "|" + + binding.bindingGeneration() + + "|" + + binding.accountIndexFence() + + "|" + + binding.issuerReservationId() + + "|" + + binding.transitionId() + + "|" + + binding.lifecycle() + + "|" + + binding.accountIndexState() + + "|" + + binding.issuerIndexState() + + "|" + + binding.inventoryRevision(); + } + + private static String digestEvidence( + CanonicalGameplayLegacyMigrationOperation operation, BigInteger publicationRevision) { + StringBuilder framed = new StringBuilder("canonical-gameplay-legacy-migration-evidence/v1|"); + for (String value : + List.of( + operation.operationId().toString(), + operation.cohortId().toString(), + operation.legacyWriterFence().toString(), + operation.storageIdentity().digest(), + operation.sourceSnapshotRevision().toString(), + operation.canonicalSnapshotRevision().toString(), + publicationRevision.toString(), + operation.namespaceIndexReadbackRevision().toString(), + operation.sourceSnapshotDigest(), + operation.canonicalSnapshotDigest(), + operation.rebuildDigest(), + operation.namespaceIndexReadbackDigest())) { + append(framed, value); + } + return sha256(framed.toString()); + } + + private static void requireSameCohort( + CanonicalGameplayLegacyMigrationOperation operation, + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort) { + if (!operation.cohortId().equals(cohort.cohortId()) + || !operation.legacyWriterFence().equals(cohort.legacyWriterFence()) + || !operation.storageIdentity().equals(cohort.storageIdentity())) { + throw conflict( + "Current all-writer fence or physical storage identity differs from the staged cohort"); + } + } + + private static void requirePublishedDispositionMatches( + DSLContext transaction, CanonicalGameplayLegacyMigrationOperation operation) { + Record disposition = + Objects.requireNonNull( + transaction.fetchOne("SELECT * FROM " + LEGACY_DISPOSITION + " WHERE singleton_id = 1"), + "V31 disposition row must exist"); + if (!"VERIFIED".equals(disposition.get("disposition_state", String.class)) + || !operation.cohortId().equals(disposition.get("cohort_id", UUID.class)) + || !operation.operationId().equals(disposition.get("owner_operation_id", UUID.class)) + || !operation.legacyWriterFence().equals(disposition.get("legacy_writer_fence", UUID.class)) + || !operation + .sourceSnapshotRevision() + .equals(readBigInteger(disposition, "source_snapshot_revision")) + || !operation + .publicationInventoryRevision() + .equals(readBigInteger(disposition, "canonical_inventory_revision")) + || !operation + .namespaceIndexReadbackRevision() + .equals(readBigInteger(disposition, "namespace_index_readback_revision")) + || !operation.evidenceDigest().equals(disposition.get("evidence_digest", String.class))) { + throw conflict("V31 VERIFIED disposition differs from this exact durable owner operation"); + } + } + + private static BigInteger readBigInteger(Record row, String field) { + BigDecimal value = row.get(field, BigDecimal.class); + if (value == null) { + throw conflict("Durable migration field " + field + " is missing"); + } + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Durable migration field " + field + " is not an integer"); + } + } + + private static BigInteger readNullableBigInteger(Record row, String field) { + BigDecimal value = row.get(field, BigDecimal.class); + return value == null ? null : value.toBigIntegerExact(); + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + 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 requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw conflict("Legacy migration owner refuses to join an ambient Spring transaction"); + } + } + + private static void requireOne(int rows, String message) { + if (rows != 1) { + throw conflict(message); + } + } + + private static String sha256(String value) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable for migration evidence", impossible); + } + } + + private static String hex(byte[] value) { + return HexFormat.of().formatHex(value); + } + + private static void append(StringBuilder output, String value) { + int byteLength = value.getBytes(StandardCharsets.UTF_8).length; + output.append(byteLength).append(':').append(value); + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + private record SnapshotJson(BigInteger revision, String json) { + private SnapshotJson { + Objects.requireNonNull(revision, "revision"); + Objects.requireNonNull(json, "json"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSource.java new file mode 100644 index 0000000000..12c38bc445 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSource.java @@ -0,0 +1,297 @@ +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.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.TreeMap; +import java.util.UUID; +import java.util.regex.Pattern; +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; + +/** + * Bounded read-only inventory of the legacy Game Session Redis keyspace. Values are never read or + * deserialized; retained rows remain non-authorizing and block migration until a mapping owner is + * implemented. + */ +final class CanonicalGameplayLegacyRedisSource + implements CanonicalGameplayLegacyMigrationOwner.CompleteLegacySource { + private static final String OWNED_PREFIX = "sessionctx:"; + private static final String SCAN_PATTERN = OWNED_PREFIX + "*"; + private static final Pattern TENANT_SESSION_CONTEXT = + Pattern.compile("sessionctx:[0-9]+:[0-9]+:context"); + private static final Pattern SESSION_ALIAS_CONTEXT = + Pattern.compile("sessionctx:session:[0-9]+:context"); + private static final Pattern GAMEPLAY_IDENTITY_CONTEXT = + Pattern.compile("sessionctx:[0-9]+:identity:[0-9]+:[0-9]+:context"); + private static final Pattern GAMEPLAY_NAME_CONTEXT = + Pattern.compile("sessionctx:[0-9]+:identity:[0-9]+:name:.+:context"); + private static final Pattern MOVEMENT_EFFECT = + Pattern.compile("sessionctx:[0-9]+:[0-9]+:movement-effect:.+"); + private static final Pattern DURABLE_EFFECT = + Pattern.compile("sessionctx:[0-9]+:[0-9]+:durable-effect:.+"); + private static final EnumSet + KNOWN_FAMILIES = + EnumSet.of( + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.TENANT_SESSION_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.SESSION_ALIAS_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_IDENTITY_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_NAME_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.MOVEMENT_EFFECT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.DURABLE_EFFECT); + private static final ScanLimits DEFAULT_LIMITS = + new ScanLimits(128, 5_000, 20_000, 1_024, Duration.ofSeconds(30)); + + private final StringRedisTemplate redis; + private final ScanLimits limits; + + CanonicalGameplayLegacyRedisSource(StringRedisTemplate redis) { + this(redis, DEFAULT_LIMITS); + } + + CanonicalGameplayLegacyRedisSource(StringRedisTemplate redis, ScanLimits limits) { + this.redis = Objects.requireNonNull(redis, "redis"); + this.limits = Objects.requireNonNull(limits, "limits"); + } + + @Override + public CanonicalGameplayLegacyMigrationSourceSnapshot captureEveryKnownFamily( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort) { + Objects.requireNonNull(cohort, "cohort"); + FenceIdentity fence = FenceIdentity.capture(cohort); + long startedAt = System.nanoTime(); + requireFenceAndTime(cohort, fence, startedAt); + Map first = + scanOnce(cohort, fence, startedAt); + requireFenceAndTime(cohort, fence, startedAt); + Map second = + scanOnce(cohort, fence, startedAt); + requireFenceAndTime(cohort, fence, startedAt); + if (!first.equals(second)) { + throw conflict("Legacy Redis key inventory changed between complete fenced scans"); + } + + List entries = new ArrayList<>(); + first.forEach( + (key, family) -> + entries.add( + new CanonicalGameplayLegacyMigrationSourceSnapshot.Entry( + family, + digestKey(key), + family == CanonicalGameplayLegacyMigrationSourceSnapshot.Family.UNCLASSIFIED + ? CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN + : CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNMAPPABLE))); + return new CanonicalGameplayLegacyMigrationSourceSnapshot(KNOWN_FAMILIES, entries); + } + + private Map scanOnce( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, + FenceIdentity fence, + long startedAt) { + Map scanned = + redis.execute( + (RedisCallback>) + connection -> scanConnection(connection, cohort, fence, startedAt)); + if (scanned == null) { + throw conflict("Legacy Redis key cursor returned no complete inventory"); + } + return scanned; + } + + private Map scanConnection( + RedisConnection connection, + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, + FenceIdentity fence, + long startedAt) { + requireFenceAndTime(cohort, fence, startedAt); + if (connection instanceof RedisClusterConnection) { + throw conflict("Legacy Redis cluster scan cannot prove complete cluster-wide inventory"); + } + try { + Properties clusterInformation = connection.serverCommands().info("cluster"); + CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology(clusterInformation); + } catch (RuntimeException unprovenTopology) { + throw conflict("Legacy Redis standalone topology could not be proven"); + } + + Map keys = new TreeMap<>(); + ScanOptions options = + ScanOptions.scanOptions().match(SCAN_PATTERN).count(limits.scanCount()).build(); + try (Cursor cursor = connection.scan(options)) { + if (cursor == null) { + throw conflict("Legacy Redis key cursor was unavailable"); + } + int visited = 0; + int sinceFenceCheck = 0; + while (true) { + requireWithinTime(startedAt); + boolean hasNext = cursor.hasNext(); + requireWithinTime(startedAt); + if (!hasNext) { + break; + } + byte[] serializedKey = cursor.next(); + String key = decodeKey(serializedKey); + if (!key.startsWith(OWNED_PREFIX)) { + throw conflict("Legacy Redis scan returned a key outside its pinned prefix"); + } + visited++; + if (visited > limits.maxVisitedKeys()) { + throw conflict("Legacy Redis key cursor exceeded its duplicate-safe visit bound"); + } + keys.putIfAbsent(key, classify(key)); + if (keys.size() > limits.maxUniqueKeys()) { + throw conflict("Legacy Redis key inventory exceeded its unique-key bound"); + } + if (++sinceFenceCheck >= limits.scanCount()) { + requireFenceAndTime(cohort, fence, startedAt); + sinceFenceCheck = 0; + } + } + if (cursor.getCursorId() != 0L) { + throw conflict("Legacy Redis key cursor stopped before the terminal cursor identity"); + } + requireFenceAndTime(cohort, fence, startedAt); + return keys; + } catch (CanonicalGameplayBindingInventoryConflictException rejected) { + throw rejected; + } catch (RuntimeException incompleteCursor) { + throw conflict("Legacy Redis key cursor failed before complete exhaustion"); + } + } + + private void requireFenceAndTime( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort, + FenceIdentity expected, + long startedAt) { + requireWithinTime(startedAt); + if (!expected.equals(FenceIdentity.capture(cohort))) { + throw conflict("Legacy Redis cohort identity or writer fence changed during inventory"); + } + cohort.requireStillFenced(expected.storageIdentity()); + if (!expected.equals(FenceIdentity.capture(cohort))) { + throw conflict("Legacy Redis cohort identity or writer fence changed during inventory"); + } + } + + private void requireWithinTime(long startedAt) { + if (System.nanoTime() - startedAt >= limits.maxDuration().toNanos()) { + throw conflict("Legacy Redis key inventory exceeded its time bound"); + } + } + + private String decodeKey(byte[] serializedKey) { + if (serializedKey == null + || serializedKey.length == 0 + || serializedKey.length > limits.maxKeyBytes()) { + throw conflict("Legacy Redis key is empty or exceeds its byte bound"); + } + try { + String key = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(serializedKey)) + .toString(); + if (!key.equals(key.strip()) || key.chars().anyMatch(Character::isISOControl)) { + throw conflict("Legacy Redis key is not a canonical text key"); + } + return key; + } catch (CharacterCodingException malformedUtf8) { + throw conflict("Legacy Redis key is not valid UTF-8"); + } + } + + private static CanonicalGameplayLegacyMigrationSourceSnapshot.Family classify(String key) { + if (TENANT_SESSION_CONTEXT.matcher(key).matches()) { + return CanonicalGameplayLegacyMigrationSourceSnapshot.Family.TENANT_SESSION_CONTEXT; + } + if (SESSION_ALIAS_CONTEXT.matcher(key).matches()) { + return CanonicalGameplayLegacyMigrationSourceSnapshot.Family.SESSION_ALIAS_CONTEXT; + } + if (GAMEPLAY_IDENTITY_CONTEXT.matcher(key).matches()) { + return CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_IDENTITY_CONTEXT; + } + if (GAMEPLAY_NAME_CONTEXT.matcher(key).matches()) { + return CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_NAME_CONTEXT; + } + if (MOVEMENT_EFFECT.matcher(key).matches()) { + return CanonicalGameplayLegacyMigrationSourceSnapshot.Family.MOVEMENT_EFFECT; + } + if (DURABLE_EFFECT.matcher(key).matches()) { + return CanonicalGameplayLegacyMigrationSourceSnapshot.Family.DURABLE_EFFECT; + } + return CanonicalGameplayLegacyMigrationSourceSnapshot.Family.UNCLASSIFIED; + } + + private static String digestKey(String key) { + try { + return "sha256:" + + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(key.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException( + "SHA-256 is unavailable for legacy Redis source inventory", impossible); + } + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + record ScanLimits( + int scanCount, int maxUniqueKeys, int maxVisitedKeys, int maxKeyBytes, Duration maxDuration) { + ScanLimits { + Objects.requireNonNull(maxDuration, "maxDuration"); + if (scanCount <= 0 + || maxUniqueKeys <= 0 + || maxVisitedKeys < maxUniqueKeys + || maxKeyBytes <= 0 + || maxDuration.isZero() + || maxDuration.isNegative()) { + throw new IllegalArgumentException( + "legacy Redis scan limits must be positive and coherent"); + } + } + } + + private record FenceIdentity( + UUID cohortId, + UUID legacyWriterFence, + CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity) { + private FenceIdentity { + Objects.requireNonNull(cohortId, "cohortId"); + Objects.requireNonNull(legacyWriterFence, "legacyWriterFence"); + Objects.requireNonNull(storageIdentity, "storageIdentity"); + if (cohortId.equals(new UUID(0L, 0L)) || legacyWriterFence.equals(new UUID(0L, 0L))) { + throw conflict("Legacy Redis source requires non-nil cohort and writer-fence identities"); + } + } + + private static FenceIdentity capture( + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort) { + return new FenceIdentity( + cohort.cohortId(), cohort.legacyWriterFence(), cohort.storageIdentity()); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java new file mode 100644 index 0000000000..883c241e7b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java @@ -0,0 +1,19 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.PrintStream; + +/** JDK-only entry point that reserves stdout for the finite driver's framed protocol. */ +public final class CanonicalGameplayMigrationDriverLauncher { + private CanonicalGameplayMigrationDriverLauncher() {} + + public static void main(String[] args) { + PrintStream protocolOutput = preserveProtocolOutputAndRedirectDiagnostics(); + CanonicalGameplayMigrationDriverMain.launch(args, protocolOutput, System.err); + } + + static PrintStream preserveProtocolOutputAndRedirectDiagnostics() { + PrintStream protocolOutput = System.out; + System.setOut(System.err); + return protocolOutput; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java new file mode 100644 index 0000000000..2664952edc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java @@ -0,0 +1,1159 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.SslOptions; +import io.lettuce.core.SslVerifyMode; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import javax.sql.DataSource; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.CoreMigrationType; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.configuration.FluentConfiguration; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.postgresql.ds.PGSimpleDataSource; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisPassword; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.core.StringRedisTemplate; + +/** Finite, non-listening implementation for the trusted Game Session empty-cohort migration. */ +@SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "These fixed trusted Pod paths bind PostgreSQL to its Unix socket and credentials/CA to protected projections; no path override or network fallback is allowed.") +public final class CanonicalGameplayMigrationDriverMain { + private static final Path POSTGRES_SOCKET = Path.of("/var/run/postgresql/.s.PGSQL.5432"); + private static final Path POSTGRES_PASSWORD = Path.of("/run/gs-owner/password"); + private static final Path REDIS_PASSWORD = Path.of("/run/gs-owner/redis/password"); + private static final Path REDIS_CA = Path.of("/run/gs-owner/redis/ca.crt"); + + private static final String POSTGRES_SOCKET_FACTORY = + "org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg"; + private static final Pattern SQL_IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,62}"); + private static final Pattern REDIS_RUN_ID = Pattern.compile("[0-9a-f]{40}"); + private static final Pattern SHA256_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final ObjectMapper CANONICAL_JSON_MAPPER = + new ObjectMapper().enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + private static final Duration REDIS_TIMEOUT = Duration.ofSeconds(5); + private static final Duration TOTAL_RUN_TIMEOUT = Duration.ofSeconds(1800); + private static final int MAX_CATALOG_ROWS = 65_536; + private static final int MAX_CATALOG_BYTES = 16 * 1024 * 1024; + private static final Map EXPECTED_MIGRATION_SCRIPTS = expectedMigrationScripts(); + private static final String USER_SCHEMA_FILTER = + "n.nspname <> 'information_schema' AND n.nspname <> 'pg_catalog'" + + " AND n.nspname NOT LIKE 'pg_toast%' AND n.nspname NOT LIKE 'pg_temp_%'"; + private static final String SCHEMA_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'owner', pg_catalog.pg_get_userbyid(n.nspowner)," + + " 'acl', n.nspacl::text)::text FROM pg_catalog.pg_namespace n WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname"; + private static final String RELATION_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'name', c.relname, 'kind', c.relkind::text," + + " 'persistence', c.relpersistence::text, 'owner', pg_catalog.pg_get_userbyid(c.relowner)," + + " 'partitioned', c.relispartition, 'accessMethod', am.amname, 'tablespace', ts.spcname," + + " 'options', c.reloptions, 'rowSecurity', c.relrowsecurity, 'forceRowSecurity', c.relforcerowsecurity," + + " 'replicaIdentity', c.relreplident::text, 'viewDefinition', CASE WHEN c.relkind IN ('v','m')" + + " THEN pg_catalog.pg_get_viewdef(c.oid, true) END, 'partitionBound', CASE WHEN c.relispartition" + + " THEN pg_catalog.pg_get_expr(c.relpartbound, c.oid, true) END, 'acl', c.relacl::text," + + " 'foreignOptions', ft.ftoptions)::text FROM pg_catalog.pg_class c" + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace" + + " LEFT JOIN pg_catalog.pg_am am ON am.oid = c.relam" + + " LEFT JOIN pg_catalog.pg_tablespace ts ON ts.oid = c.reltablespace" + + " LEFT JOIN pg_catalog.pg_foreign_table ft ON ft.ftrelid = c.oid WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, c.relname, c.relkind"; + private static final String COLUMN_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'relation', c.relname, 'name', a.attname," + + " 'ordinal', a.attnum, 'type', pg_catalog.format_type(a.atttypid, a.atttypmod)," + + " 'typeSchema', tn.nspname, 'typeName', t.typname, 'notNull', a.attnotnull," + + " 'hasDefault', a.atthasdef, 'default', pg_catalog.pg_get_expr(d.adbin, d.adrelid, true)," + + " 'identity', a.attidentity::text, 'generated', a.attgenerated::text, 'storage', a.attstorage::text," + + " 'compression', a.attcompression::text, 'collationSchema', cn.nspname, 'collation', co.collname," + + " 'statisticsTarget', a.attstattarget, 'acl', a.attacl::text)::text FROM pg_catalog.pg_attribute a" + + " JOIN pg_catalog.pg_class c ON c.oid = a.attrelid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace" + + " JOIN pg_catalog.pg_type t ON t.oid = a.atttypid" + + " JOIN pg_catalog.pg_namespace tn ON tn.oid = t.typnamespace" + + " LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum" + + " LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation" + + " LEFT JOIN pg_catalog.pg_namespace cn ON cn.oid = co.collnamespace" + + " WHERE a.attnum > 0 AND NOT a.attisdropped AND " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, c.relname, a.attnum"; + private static final String INDEX_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'table', tbl.relname, 'index', idx.relname," + + " 'owner', pg_catalog.pg_get_userbyid(idx.relowner), 'definition', pg_catalog.pg_get_indexdef(idx.oid)," + + " 'unique', i.indisunique, 'primary', i.indisprimary, 'valid', i.indisvalid, 'ready', i.indisready," + + " 'live', i.indislive, 'clustered', i.indisclustered, 'replicaIdentity', i.indisreplident," + + " 'nullsNotDistinct', i.indnullsnotdistinct, 'keyAttributes', i.indnkeyatts, 'attributes', i.indnatts," + + " 'keys', i.indkey::text, 'classes', i.indclass::text, 'collations', i.indcollation::text," + + " 'options', i.indoption::text, 'accessMethod', am.amname, 'tablespace', ts.spcname," + + " 'relationOptions', idx.reloptions, 'acl', idx.relacl::text)::text" + + " FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class tbl ON tbl.oid = i.indrelid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = tbl.relnamespace" + + " JOIN pg_catalog.pg_class idx ON idx.oid = i.indexrelid" + + " LEFT JOIN pg_catalog.pg_am am ON am.oid = idx.relam" + + " LEFT JOIN pg_catalog.pg_tablespace ts ON ts.oid = idx.reltablespace WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, tbl.relname, idx.relname"; + private static final String CONSTRAINT_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'relation', c.relname, 'name', con.conname," + + " 'type', con.contype::text, 'definition', pg_catalog.pg_get_constraintdef(con.oid, true)," + + " 'deferrable', con.condeferrable, 'deferred', con.condeferred, 'validated', con.convalidated," + + " 'local', con.conislocal, 'inheritanceCount', con.coninhcount, 'noInherit', con.connoinherit," + + " 'keys', con.conkey::text, 'referencedKeys', con.confkey::text, 'matchType', con.confmatchtype::text," + + " 'updateAction', con.confupdtype::text, 'deleteAction', con.confdeltype::text," + + " 'index', ic.relname)::text FROM pg_catalog.pg_constraint con" + + " JOIN pg_catalog.pg_class c ON c.oid = con.conrelid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace" + + " LEFT JOIN pg_catalog.pg_class ic ON ic.oid = con.conindid WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, c.relname, con.conname"; + private static final String TYPE_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'name', t.typname, 'owner'," + + " pg_catalog.pg_get_userbyid(t.typowner), 'kind', t.typtype::text, 'category', t.typcategory::text," + + " 'defined', t.typisdefined, 'length', t.typlen, 'byValue', t.typbyval, 'delimiter', t.typdelim::text," + + " 'input', t.typinput::regprocedure::text, 'output', t.typoutput::regprocedure::text," + + " 'receive', t.typreceive::regprocedure::text, 'send', t.typsend::regprocedure::text," + + " 'modifierInput', t.typmodin::regprocedure::text, 'modifierOutput', t.typmodout::regprocedure::text," + + " 'analyze', t.typanalyze::regprocedure::text, 'alignment', t.typalign::text," + + " 'storage', t.typstorage::text, 'subscript', t.typsubscript::regprocedure::text," + + " 'relation', t.typrelid::regclass::text, 'element', t.typelem::regtype::text," + + " 'array', t.typarray::regtype::text, 'base', t.typbasetype::regtype::text," + + " 'notNull', t.typnotnull, 'default', t.typdefault, 'baseTypeModifier', t.typtypmod," + + " 'collation', t.typcollation::regcollation::text, 'acl', t.typacl::text)::text" + + " FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, t.typname"; + private static final String DOMAIN_CONSTRAINT_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'type', t.typname, 'name', con.conname," + + " 'definition', pg_catalog.pg_get_constraintdef(con.oid, true), 'validated', con.convalidated," + + " 'local', con.conislocal, 'inheritanceCount', con.coninhcount)::text" + + " FROM pg_catalog.pg_constraint con JOIN pg_catalog.pg_type t ON t.oid = con.contypid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, t.typname, con.conname"; + private static final String ENUM_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'type', t.typname, 'label', e.enumlabel," + + " 'sortOrder', e.enumsortorder)::text FROM pg_catalog.pg_enum e" + + " JOIN pg_catalog.pg_type t ON t.oid = e.enumtypid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, t.typname, e.enumsortorder"; + private static final String SEQUENCE_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'name', c.relname, 'owner'," + + " pg_catalog.pg_get_userbyid(c.relowner), 'start', s.seqstart, 'increment', s.seqincrement," + + " 'maximum', s.seqmax, 'minimum', s.seqmin, 'cache', s.seqcache, 'cycle', s.seqcycle," + + " 'acl', c.relacl::text)::text FROM pg_catalog.pg_sequence s" + + " JOIN pg_catalog.pg_class c ON c.oid = s.seqrelid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, c.relname"; + private static final String ROUTINE_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'name', p.proname, 'identityArguments'," + + " pg_catalog.pg_get_function_identity_arguments(p.oid), 'result', pg_catalog.pg_get_function_result(p.oid)," + + " 'kind', p.prokind::text, 'language', l.lanname, 'owner', pg_catalog.pg_get_userbyid(p.proowner)," + + " 'arguments', p.proargtypes::regtype[]::text, 'configuration', p.proconfig::text, 'acl', p.proacl::text," + + " 'definition', CASE WHEN p.prokind = 'a' THEN NULL ELSE pg_catalog.pg_get_functiondef(p.oid) END)::text" + + " FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace" + + " JOIN pg_catalog.pg_language l ON l.oid = p.prolang WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, p.proname, pg_catalog.pg_get_function_identity_arguments(p.oid)"; + private static final String TRIGGER_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'relation', c.relname, 'name', t.tgname," + + " 'definition', pg_catalog.pg_get_triggerdef(t.oid, true), 'enabled', t.tgenabled::text," + + " 'internal', t.tgisinternal, 'constraint', t.tgconstraint::regclass::text," + + " 'arguments', encode(t.tgargs, 'hex'), 'when', pg_catalog.pg_get_expr(t.tgqual, t.tgrelid, true)," + + " 'function', t.tgfoid::regprocedure::text)::text FROM pg_catalog.pg_trigger t" + + " JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, c.relname, t.tgname"; + private static final String POLICY_INVENTORY_SQL = + "SELECT jsonb_build_object('schema', n.nspname, 'relation', c.relname, 'name', p.polname," + + " 'command', p.polcmd::text, 'permissive', p.polpermissive, 'roles', p.polroles::text," + + " 'using', pg_catalog.pg_get_expr(p.polqual, p.polrelid, true)," + + " 'check', pg_catalog.pg_get_expr(p.polwithcheck, p.polrelid, true))::text" + + " FROM pg_catalog.pg_policy p JOIN pg_catalog.pg_class c ON c.oid = p.polrelid" + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY n.nspname, c.relname, p.polname"; + private static final String EXTENSION_INVENTORY_SQL = + "SELECT jsonb_build_object('name', e.extname, 'version', e.extversion, 'owner'," + + " pg_catalog.pg_get_userbyid(e.extowner), 'schema', n.nspname, 'relocatable', e.extrelocatable," + + " 'configurationRelations', e.extconfig::text, 'conditions', e.extcondition::text)::text" + + " FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace" + + " WHERE " + + USER_SCHEMA_FILTER + + " ORDER BY e.extname"; + + /* + * This source cut is intentionally the complete packaged Game Session migration directory + * (V1-V15, V20-V34, V34.1, V34.2, and + * V34.3__canonical_initial_admission_intent_request_id_width.sql) plus the three common-saga + * migrations (V1000-V1002). Flyway computes checksums from those packaged SQL resources and + * validates the applied schema history against them; no filesystem, callback, or additional + * migration location is accepted. + */ + + private CanonicalGameplayMigrationDriverMain() {} + + static void launch(String[] args, java.io.PrintStream protocolOutput, java.io.PrintStream error) { + ScheduledExecutorService deadline = + Executors.newSingleThreadScheduledExecutor( + task -> { + Thread thread = new Thread(task, "gs-migration-driver-deadline"); + thread.setDaemon(true); + return thread; + }); + deadline.schedule( + () -> { + error.println( + "migration driver exceeded its finite run bound; retain the same cohort and writer fence"); + Runtime.getRuntime().halt(4); + }, + TOTAL_RUN_TIMEOUT.toSeconds(), + TimeUnit.SECONDS); + int exitCode; + try { + exitCode = run(args, System.in, protocolOutput, error); + } finally { + deadline.shutdownNow(); + } + if (exitCode != 0) { + System.exit(exitCode); + } + } + + static int run( + String[] args, + java.io.InputStream input, + java.io.OutputStream output, + java.io.PrintStream error) { + if (args.length != 0) { + error.println("migration driver accepts no command-line arguments"); + return 2; + } + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol(input, output)) { + CanonicalGameplayMigrationDriverProtocol.Initialization initialization = + protocol.readInitialization(); + DriverConfiguration configuration = DriverConfiguration.fromEnvironment(initialization); + DataSource postgres = createPostgresDataSource(configuration); + LettuceConnectionFactory redisFactory = createRedisConnectionFactory(configuration); + try { + redisFactory.afterPropertiesSet(); + StringRedisTemplate redis = new StringRedisTemplate(redisFactory); + redis.afterPropertiesSet(); + LiveObservationReader observationReader = + new LiveObservationReader(postgres, redis, REDIS_CA); + CanonicalGameplayMigrationDriverProtocol.LocalObservation initialObservation = + observationReader.read(); + requireIdentityMatches( + initialization, + initialObservation, + configuration.postgresUser(), + configuration.redisCaDigest()); + + ProtocolFencedCohort cohort = + new ProtocolFencedCohort( + initialization, + protocol, + observationReader, + initialObservation, + configuration.postgresUser(), + configuration.redisCaDigest()); + cohort.requireStillFenced(initialization.storageIdentity()); + // A partial Flyway run is intentionally not replayed as an "empty" cohort. After any + // interrupted schema creation the same external fence must remain retained for owner-led + // reconciliation; this driver invents no side marker or schema exemption. + PhysicalSchemaSnapshot beforeMigration = readPhysicalSchemaSnapshot(postgres); + requireEmptyCohortSchema(beforeMigration); + cohort.requireStillFenced(initialization.storageIdentity()); + Flyway flyway = createFlyway(configuration, postgres); + List packagedMigrationSources = migrationSourceInventory(flyway); + requireCompletePackagedMigrationSources(packagedMigrationSources); + cohort.requireStillFenced(initialization.storageIdentity()); + flyway.migrate(); + cohort.requireStillFenced(initialization.storageIdentity()); + flyway.validate(); + requireFlywayCurrent(flyway); + cohort.requireStillFenced(initialization.storageIdentity()); + PhysicalSchemaSnapshot ownerCreatedSchema = readPhysicalSchemaSnapshot(postgres); + cohort.requireStillFenced(initialization.storageIdentity()); + flyway.validate(); + requireFlywayCurrent(flyway); + requireSameMigrationSources(packagedMigrationSources, migrationSourceInventory(flyway)); + PhysicalSchemaSnapshot physicalReadback = readPhysicalSchemaSnapshot(postgres); + requireSamePhysicalSchema(ownerCreatedSchema, physicalReadback); + cohort.requireStillFenced(initialization.storageIdentity()); + + DSLContext dsl = DSL.using(postgres, SQLDialect.POSTGRES); + CanonicalGameplayBindingInventoryRepository inventory = + new CanonicalGameplayBindingInventoryRepository(dsl); + CanonicalGameplayLegacyMigrationOwner owner = + new CanonicalGameplayLegacyMigrationOwner( + new CanonicalGameplayLegacyMigrationRepository(dsl, inventory), + inventory, + () -> cohort, + new CanonicalGameplayLegacyRedisSource(redis), + new CanonicalGameplayFreshNamespaceRedisReconciler(redis)); + CanonicalGameplayLegacyMigrationOperation operation = owner.migrate(); + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + error.println("migration driver did not verify the empty cohort; retain the fence"); + return 3; + } + return 0; + } finally { + redisFactory.destroy(); + } + } catch (RuntimeException | IOException failure) { + error.println("migration driver denied or failed; retain the same cohort and writer fence"); + return 4; + } + } + + private static DataSource createPostgresDataSource(DriverConfiguration configuration) { + PostgresSocketConfiguration socket = postgresSocketConfiguration(); + PGSimpleDataSource dataSource = new PGSimpleDataSource(); + dataSource.setServerNames(new String[] {socket.host()}); + dataSource.setPortNumbers(new int[] {socket.port()}); + dataSource.setDatabaseName(configuration.postgresDatabase()); + dataSource.setUser(configuration.postgresUser()); + dataSource.setPassword(configuration.postgresPassword()); + try { + dataSource.setProperty("socketFactory", socket.factoryClass()); + dataSource.setProperty("socketFactoryArg", socket.socketPath()); + dataSource.setProperty("sslmode", socket.sslMode()); + dataSource.setProperty("connectTimeout", "5"); + dataSource.setProperty("socketTimeout", "300"); + dataSource.setProperty("currentSchema", configuration.serviceSchema()); + } catch (SQLException invalidConfiguration) { + throw new IllegalStateException("could not configure the socket-only PostgreSQL source"); + } + dataSource.setApplicationName("gs-canonical-gameplay-migration-driver"); + return dataSource; + } + + static PostgresSocketConfiguration postgresSocketConfiguration() { + return new PostgresSocketConfiguration( + "localhost", 5432, POSTGRES_SOCKET_FACTORY, POSTGRES_SOCKET.toString(), "disable"); + } + + record PostgresSocketConfiguration( + String host, int port, String factoryClass, String socketPath, String sslMode) {} + + private static LettuceConnectionFactory createRedisConnectionFactory( + DriverConfiguration configuration) throws IOException { + RedisStandaloneConfiguration standalone = + new RedisStandaloneConfiguration(configuration.redisHost(), 6380); + if (configuration.redisUsername() != null) { + standalone.setUsername(configuration.redisUsername()); + } + standalone.setPassword(RedisPassword.of(configuration.redisPassword())); + SslOptions sslOptions = + SslOptions.builder().jdkSslProvider().trustManager(REDIS_CA.toFile()).build(); + ClientOptions clientOptions = ClientOptions.builder().sslOptions(sslOptions).build(); + LettuceClientConfiguration clientConfiguration = + LettuceClientConfiguration.builder() + .clientOptions(clientOptions) + .commandTimeout(REDIS_TIMEOUT) + .shutdownTimeout(REDIS_TIMEOUT) + .useSsl() + .verifyPeer(SslVerifyMode.FULL) + .and() + .build(); + LettuceConnectionFactory factory = + new LettuceConnectionFactory(standalone, clientConfiguration); + factory.setShareNativeConnection(false); + return factory; + } + + private static Flyway createFlyway(DriverConfiguration configuration, DataSource dataSource) { + return configuredFlyway(configuration.serviceSchema(), dataSource).load(); + } + + static FluentConfiguration configuredFlyway(String serviceSchema, DataSource dataSource) { + return Flyway.configure() + .dataSource(dataSource) + .schemas(serviceSchema) + .defaultSchema(serviceSchema) + .table(flywayHistoryTable(serviceSchema)) + .createSchemas(true) + .locations("classpath:db/migration", "classpath:db/migration/saga") + .placeholders(Map.of("serviceSchema", serviceSchema)) + .cleanDisabled(true) + .baselineOnMigrate(false); + } + + static String flywayHistoryTable(String serviceSchema) { + if (serviceSchema == null + || !SQL_IDENTIFIER.matcher(serviceSchema).matches() + || ("flyway_schema_history_" + serviceSchema).length() > 63) { + throw new IllegalArgumentException("migration service schema is not canonical"); + } + return "flyway_schema_history_" + serviceSchema; + } + + static Map validatedRedisObservation( + String runId, String plainPortText, String tlsPortText, String trustCaDigest) { + if (runId == null + || !REDIS_RUN_ID.matcher(runId).matches() + || !"0".equals(plainPortText) + || !"6380".equals(tlsPortText) + || trustCaDigest == null + || !SHA256_DIGEST.matcher(trustCaDigest).matches()) { + throw new IllegalStateException("Redis identity or TLS configuration was incomplete"); + } + Map observed = new LinkedHashMap<>(); + observed.put("runId", runId); + observed.put("tlsEnabled", true); + observed.put("tlsPort", 6380); + observed.put("trustCaSha256", trustCaDigest); + return observed; + } + + static void requireStandaloneRedisTopology(Properties clusterInformation) { + if (clusterInformation == null + || !"0".equals(clusterInformation.getProperty("cluster_enabled"))) { + throw new IllegalStateException( + "Redis server topology is missing, ambiguous, or cluster-enabled"); + } + } + + private static void requireFlywayCurrent(Flyway flyway) { + var info = flyway.info(); + if (info.current() == null || info.pending().length != 0) { + throw new IllegalStateException("Flyway did not reach the current schema version"); + } + requireCompletePackagedMigrationSources(migrationSourceInventory(flyway)); + } + + private static void requireCompletePackagedMigrationSources( + List migrations) { + if (migrations.size() != EXPECTED_MIGRATION_SCRIPTS.size() + || migrations.stream() + .anyMatch( + migration -> + !expectedMigrationScriptName(migration.script()) + .equals(EXPECTED_MIGRATION_SCRIPTS.get(migration.version())) + || !"SQL".equals(migration.type()) + || migration.checksum() == null)) { + throw new IllegalStateException("packaged migration source inventory was incomplete"); + } + } + + private static void requireSameMigrationSources( + List expected, List actual) { + requireCompletePackagedMigrationSources(actual); + if (!expected.equals(actual)) { + throw new IllegalStateException("packaged Flyway migration checksum inventory changed"); + } + } + + private static Map expectedMigrationScripts() { + return Map.ofEntries( + Map.entry("1", "V1__baseline.sql"), + Map.entry("2", "V2__scope_gameplay_command_identity.sql"), + Map.entry("3", "V3__retain_exact_script_patch_base_provenance.sql"), + Map.entry("4", "V4__retain_gameplay_command_script_patch_base_provenance.sql"), + Map.entry("5", "V5__separate_gameplay_catalog_revision.sql"), + Map.entry("6", "V6__persist_gameplay_realm_identity.sql"), + Map.entry("7", "V7__audit_gameplay_catalog_revision.sql"), + Map.entry("8", "V8__repair_legacy_bootstrap_public_realm.sql"), + Map.entry("9", "V9__initial_admission_bind_owner_ledger.sql"), + Map.entry("10", "V10__run_owned_initial_launch_identity.sql"), + Map.entry("11", "V11__gameplay_command_account_uuid.sql"), + Map.entry("12", "V12__retained_tenant_association.sql"), + Map.entry("13", "V13__retained_tenant_payload_retention.sql"), + Map.entry("14", "V14__published_realm_catalog_snapshots.sql"), + Map.entry("15", "V15__published_initial_admission_bind.sql"), + Map.entry("20", "V20__closed_published_realm_policy_evidence.sql"), + Map.entry("21", "V21__canonical_game_instance_owner_identity.sql"), + Map.entry("22", "V22__authored_world_source_intake.sql"), + Map.entry("23", "V23__canonical_realm_catalog.sql"), + Map.entry("24", "V24__canonical_launch_preparation.sql"), + Map.entry("25", "V25__fresh_tenant_association.sql"), + Map.entry("26", "V26__canonical_instance_launch_association.sql"), + Map.entry("27", "V27__canonical_closed_admission_pointer.sql"), + Map.entry("28", "V28__canonical_initial_admission_owner_and_intent.sql"), + Map.entry("29", "V29__canonical_gameplay_binding_inventory_foundation.sql"), + Map.entry("30", "V30__retain_canonical_account_index_projection_readback.sql"), + Map.entry("31", "V31__canonical_account_coverage_fence_snapshot_and_ack.sql"), + Map.entry("32", "V32__canonical_gameplay_admission_decision.sql"), + Map.entry("33", "V33__canonical_legacy_binding_migration_operation.sql"), + Map.entry("34", "V34__canonical_gameplay_decision_runtime_fence.sql"), + Map.entry("34.1", "V34.1__canonical_gameplay_integrity_guards.sql"), + Map.entry("34.2", "V34.2__canonical_gameplay_runtime_update_and_identifier_guards.sql"), + Map.entry("34.3", "V34.3__canonical_initial_admission_intent_request_id_width.sql"), + Map.entry("1000", "V1000__create_saga_schema.sql"), + Map.entry("1001", "V1001__saga_instance_table.sql"), + Map.entry("1002", "V1002__saga_step_table.sql")); + } + + private static List migrationSourceInventory(Flyway flyway) { + return migrationSourceInventory(flyway.info().all()); + } + + static List migrationSourceInventory(MigrationInfo[] migrationInfos) { + if (migrationInfos == null) { + throw new IllegalStateException("packaged migration source inventory was incomplete"); + } + List migrations = new ArrayList<>(); + int schemaMarkers = 0; + for (MigrationInfo migration : migrationInfos) { + if (migration == null) { + throw new IllegalStateException("packaged migration source identity was incomplete"); + } + if (migration.getType() == CoreMigrationType.SCHEMA) { + if (++schemaMarkers > 1) { + throw new IllegalStateException("packaged Flyway schema marker was ambiguous"); + } + continue; + } + if (migration.getVersion() == null + || migration.getScript() == null + || migration.getType() == null) { + throw new IllegalStateException("packaged migration source identity was incomplete"); + } + migrations.add( + new MigrationSourceIdentity( + migration.getVersion().getVersion(), + migration.getScript(), + migration.getType().name(), + migration.getChecksum())); + } + migrations.sort( + java.util.Comparator.comparing(MigrationSourceIdentity::version) + .thenComparing(MigrationSourceIdentity::script)); + if (migrations.stream().map(MigrationSourceIdentity::version).distinct().count() + != migrations.size()) { + throw new IllegalStateException("packaged migration source versions were ambiguous"); + } + return List.copyOf(migrations); + } + + private static String expectedMigrationScriptName(String script) { + int separator = Math.max(script.lastIndexOf('/'), script.lastIndexOf('\\')); + return script.substring(separator + 1); + } + + private static PhysicalSchemaSnapshot readPhysicalSchemaSnapshot(DataSource dataSource) { + try (Connection connection = dataSource.getConnection()) { + connection.setReadOnly(true); + connection.setAutoCommit(false); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + List schemas = catalogRows(connection, SCHEMA_INVENTORY_SQL); + List relations = catalogRows(connection, RELATION_INVENTORY_SQL); + List columns = catalogRows(connection, COLUMN_INVENTORY_SQL); + List indexes = catalogRows(connection, INDEX_INVENTORY_SQL); + List constraints = catalogRows(connection, CONSTRAINT_INVENTORY_SQL); + List types = catalogRows(connection, TYPE_INVENTORY_SQL); + List domainConstraints = catalogRows(connection, DOMAIN_CONSTRAINT_INVENTORY_SQL); + List enumLabels = catalogRows(connection, ENUM_INVENTORY_SQL); + List sequences = catalogRows(connection, SEQUENCE_INVENTORY_SQL); + List routines = catalogRows(connection, ROUTINE_INVENTORY_SQL); + List triggers = catalogRows(connection, TRIGGER_INVENTORY_SQL); + List policies = catalogRows(connection, POLICY_INVENTORY_SQL); + List extensions = catalogRows(connection, EXTENSION_INVENTORY_SQL); + connection.commit(); + return new PhysicalSchemaSnapshot( + schemas, + relations, + columns, + indexes, + constraints, + types, + domainConstraints, + enumLabels, + sequences, + routines, + triggers, + policies, + extensions); + } catch (SQLException failure) { + throw new IllegalStateException("physical PostgreSQL schema inventory failed"); + } + } + + private static List catalogRows(Connection connection, String sql) throws SQLException { + List rows = new ArrayList<>(); + int totalBytes = 0; + try (PreparedStatement statement = connection.prepareStatement(sql); + ResultSet results = statement.executeQuery()) { + while (results.next()) { + String row = results.getString(1); + if (row == null) { + throw new SQLException("physical schema inventory contained a null record"); + } + int rowBytes = row.getBytes(StandardCharsets.UTF_8).length; + totalBytes += rowBytes; + if (rows.size() >= MAX_CATALOG_ROWS || totalBytes > MAX_CATALOG_BYTES) { + throw new SQLException("physical schema inventory exceeded its finite bound"); + } + rows.add(row); + } + } + return List.copyOf(rows); + } + + private static void requireEmptyCohortSchema(PhysicalSchemaSnapshot snapshot) { + if (!snapshot.isEmptyCohort()) { + throw new IllegalStateException( + "pre-migration PostgreSQL user relations or schema objects are not empty"); + } + } + + private static void requireSamePhysicalSchema( + PhysicalSchemaSnapshot expected, PhysicalSchemaSnapshot actual) { + if (!expected.equals(actual)) { + throw new IllegalStateException( + "fresh PostgreSQL physical schema readback differed from owner-created migrations"); + } + } + + private static void requireIdentityMatches( + CanonicalGameplayMigrationDriverProtocol.Initialization initialization, + CanonicalGameplayMigrationDriverProtocol.LocalObservation observation, + String postgresUser, + String redisCaDigest) { + Map postgres = observation.postgres(); + Map redis = observation.redis(); + CanonicalGameplayLegacyMigrationStorageIdentity identity = initialization.storageIdentity(); + if (!identity.postgresSystemIdentifier().equals(postgres.get("systemIdentifier")) + || !Long.valueOf(identity.postgresDatabaseOid()).equals(postgres.get("databaseOid")) + || !identity.redisRunId().equals(redis.get("runId")) + || !postgresUser.equals("gs_storage_owner")) { + throw new IllegalStateException( + "local PostgreSQL or Redis identity did not match the cohort"); + } + if (!"".equals(postgres.get("listenAddresses")) + || postgres.get("serverAddress") != null + || postgres.get("serverPort") != null + || !hasRequiredUnixSocketDirectory(postgres.get("unixSocketDirectories"))) { + throw new IllegalStateException("PostgreSQL is not restricted to the required Unix socket"); + } + if (!Boolean.TRUE.equals(redis.get("tlsEnabled")) + || !Integer.valueOf(6380).equals(redis.get("tlsPort")) + || !redisCaDigest.equals(redis.get("trustCaSha256"))) { + throw new IllegalStateException("Redis TLS identity did not match the pinned endpoint"); + } + } + + private static boolean hasRequiredUnixSocketDirectory(Object value) { + if (!(value instanceof String directories)) { + return false; + } + for (String directory : directories.split(",", -1)) { + if ("/var/run/postgresql".equals(directory.strip())) { + return true; + } + } + return false; + } + + private static String requiredEnvironment(Map environment, String name) { + String value = environment.get(name); + if (value == null + || value.isBlank() + || !value.equals(value.strip()) + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalStateException("required migration driver configuration is unavailable"); + } + return value; + } + + private static String optionalEnvironment(Map environment, String name) { + String value = environment.get(name); + if (value == null || value.isBlank()) { + return null; + } + if (!value.equals(value.strip()) || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalStateException("optional migration driver configuration is invalid"); + } + return value; + } + + private static String readSecret(Path path) throws IOException { + long size = Files.size(path); + if (size <= 0 || size > 4 * 1024) { + throw new IOException("mounted credential file is empty or exceeds its bound"); + } + byte[] bytes = Files.readAllBytes(path); + if (bytes.length == 0 || bytes.length > 4 * 1024) { + throw new IOException("mounted credential file changed beyond its bound"); + } + String value = decodeUtf8(bytes); + if (value.endsWith("\r\n")) { + value = value.substring(0, value.length() - 2); + } else if (value.endsWith("\n")) { + value = value.substring(0, value.length() - 1); + } + if (value.isBlank() || value.chars().anyMatch(Character::isISOControl)) { + throw new IOException("mounted credential file is not canonical text"); + } + return value; + } + + private static String decodeUtf8(byte[] bytes) throws IOException { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw new IOException("mounted file is not UTF-8", malformed); + } + } + + private static String sha256(byte[] value) { + try { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String canonicalJsonDigest(Object value) { + try { + return sha256(CANONICAL_JSON_MAPPER.writeValueAsBytes(value)); + } catch (IOException serializationFailure) { + throw new IllegalStateException("local PostgreSQL observation could not be canonicalized"); + } + } + + private static String singleText(Connection connection, String sql) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(sql); + ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + throw new SQLException("local PostgreSQL observation returned no row"); + } + String value = rows.getString(1); + if (rows.next()) { + throw new SQLException("local PostgreSQL observation returned multiple rows"); + } + return value; + } + } + + private static String digestRoles(Connection connection) throws SQLException { + List loginRoles = new ArrayList<>(); + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT rolname FROM pg_catalog.pg_roles WHERE rolcanlogin ORDER BY rolname"); + ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + loginRoles.add(rows.getString(1)); + if (loginRoles.size() > 128) { + throw new SQLException("PostgreSQL login-role inventory exceeded its bound"); + } + } + } + if (!loginRoles.equals(List.of("gs_storage_owner"))) { + throw new SQLException("PostgreSQL login-role inventory did not match the owner-only policy"); + } + return canonicalJsonDigest(loginRoles); + } + + private static String digestHbaRules(Connection connection) throws SQLException { + List> rules = new ArrayList<>(); + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT type, database, user_name AS user, address, auth_method AS \"authMethod\", error" + + " FROM pg_catalog.pg_hba_file_rules ORDER BY rule_number NULLS LAST, line_number"); + ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + Object error = rows.getObject("error"); + if (error != null) { + throw new SQLException("PostgreSQL HBA rules contain a parse error"); + } + Map rule = new LinkedHashMap<>(); + rule.put("type", rows.getObject("type")); + rule.put("database", postgresTextArray(rows.getArray("database"))); + rule.put("user", postgresTextArray(rows.getArray("user"))); + rule.put("address", rows.getObject("address")); + rule.put("authMethod", rows.getObject("authMethod")); + rule.put("error", null); + rules.add(rule); + if (rules.size() > 256) { + throw new SQLException("PostgreSQL HBA inventory exceeded its bound"); + } + } + } + return canonicalJsonDigest(rules); + } + + private static List postgresTextArray(java.sql.Array array) throws SQLException { + if (array == null) { + return null; + } + Object values = array.getArray(); + if (!(values instanceof Object[] entries)) { + throw new SQLException("PostgreSQL HBA text array has an unsupported representation"); + } + List result = new ArrayList<>(entries.length); + for (Object entry : entries) { + if (entry != null && !(entry instanceof String)) { + throw new SQLException("PostgreSQL HBA text array contains a non-text value"); + } + result.add((String) entry); + } + return result; + } + + private static String sha256File(Path path) throws IOException { + long size = Files.size(path); + if (size <= 0 || size > 1024 * 1024) { + throw new IOException("mounted Redis CA file is empty or exceeds its bound"); + } + byte[] bytes = Files.readAllBytes(path); + if (bytes.length == 0 || bytes.length > 1024 * 1024) { + throw new IOException("mounted Redis CA file changed beyond its bound"); + } + return sha256(bytes); + } + + private record DriverConfiguration( + String postgresDatabase, + String postgresUser, + String postgresPassword, + String serviceSchema, + String redisHost, + String redisUsername, + String redisPassword, + String redisCaDigest) { + private DriverConfiguration { + Objects.requireNonNull(postgresDatabase, "postgresDatabase"); + Objects.requireNonNull(postgresUser, "postgresUser"); + Objects.requireNonNull(postgresPassword, "postgresPassword"); + Objects.requireNonNull(serviceSchema, "serviceSchema"); + Objects.requireNonNull(redisHost, "redisHost"); + Objects.requireNonNull(redisPassword, "redisPassword"); + Objects.requireNonNull(redisCaDigest, "redisCaDigest"); + } + + private static DriverConfiguration fromEnvironment( + CanonicalGameplayMigrationDriverProtocol.Initialization initialization) throws IOException { + Map environment = System.getenv(); + String database = requiredEnvironment(environment, "FIREMUD_POSTGRES_DB"); + String user = requiredEnvironment(environment, "FIREMUD_POSTGRES_USER"); + String schema = requiredEnvironment(environment, "SERVICE_SCHEMA"); + if (!SQL_IDENTIFIER.matcher(database).matches() + || !SQL_IDENTIFIER.matcher(user).matches() + || !SQL_IDENTIFIER.matcher(schema).matches()) { + throw new IllegalStateException("migration database identifiers are not canonical"); + } + String configuredHistoryTable = environment.get("SPRING_FLYWAY_TABLE"); + if (configuredHistoryTable != null + && !flywayHistoryTable(schema).equals(configuredHistoryTable)) { + throw new IllegalStateException("migration Flyway history table is not canonical"); + } + return new DriverConfiguration( + database, + user, + readSecret(POSTGRES_PASSWORD), + schema, + initialization.redisHost(), + optionalEnvironment(environment, "FIREMUD_REDIS_USERNAME"), + readSecret(REDIS_PASSWORD), + sha256File(REDIS_CA)); + } + } + + private static final class LiveObservationReader { + private final DataSource postgres; + private final StringRedisTemplate redis; + private final Path redisCaFile; + + private LiveObservationReader( + DataSource postgres, StringRedisTemplate redis, Path redisCaFile) { + this.postgres = Objects.requireNonNull(postgres, "postgres"); + this.redis = Objects.requireNonNull(redis, "redis"); + this.redisCaFile = Objects.requireNonNull(redisCaFile, "redisCaFile"); + } + + private CanonicalGameplayMigrationDriverProtocol.LocalObservation read() { + return new CanonicalGameplayMigrationDriverProtocol.LocalObservation( + readPostgres(), readRedis()); + } + + private Map readPostgres() { + try (Connection connection = postgres.getConnection()) { + String systemIdentifier = + singleText( + connection, "SELECT system_identifier::text FROM pg_catalog.pg_control_system()"); + long databaseOid; + try (PreparedStatement statement = + connection.prepareStatement( + "SELECT oid::bigint FROM pg_catalog.pg_database" + + " WHERE datname = pg_catalog.current_database()"); + ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + throw new SQLException("PostgreSQL database identity was unavailable"); + } + databaseOid = rows.getLong(1); + if (rows.wasNull() || rows.next()) { + throw new SQLException("PostgreSQL database identity was ambiguous"); + } + } + String listenAddresses = singleText(connection, "SHOW listen_addresses"); + String hbaFile = singleText(connection, "SHOW hba_file"); + String unixSocketDirectories = singleText(connection, "SHOW unix_socket_directories"); + String serverAddress = + singleNullableText(connection, "SELECT pg_catalog.inet_server_addr()::text"); + Integer serverPort = + singleNullableInteger(connection, "SELECT pg_catalog.inet_server_port()"); + String rolesDigest = digestRoles(connection); + String hbaRulesDigest = digestHbaRules(connection); + if (systemIdentifier == null + || !systemIdentifier.matches("[1-9][0-9]{0,19}") + || databaseOid <= 0L + || databaseOid > 0xffff_ffffL + || hbaFile == null + || hbaFile.isBlank() + || unixSocketDirectories == null + || listenAddresses == null) { + throw new SQLException("PostgreSQL local identity or configuration was incomplete"); + } + Map values = new LinkedHashMap<>(); + values.put("systemIdentifier", systemIdentifier); + values.put("databaseOid", databaseOid); + values.put("serverAddress", serverAddress); + values.put("serverPort", serverPort); + values.put("listenAddresses", listenAddresses); + values.put("hbaFile", hbaFile); + values.put("unixSocketDirectories", unixSocketDirectories); + values.put("rolesDigest", rolesDigest); + values.put("hbaRulesDigest", hbaRulesDigest); + return values; + } catch (SQLException failure) { + throw new IllegalStateException("local PostgreSQL identity/configuration recheck failed"); + } + } + + private Map readRedis() { + String trustCaDigest; + try { + trustCaDigest = sha256File(redisCaFile); + } catch (IOException failure) { + throw new IllegalStateException("local Redis trust anchor recheck failed"); + } + try { + Map values = + redis.execute( + (RedisConnection connection) -> { + requireStandaloneRedisTopology(connection.serverCommands().info("cluster")); + Properties info = connection.serverCommands().info("server"); + String runId = info == null ? null : info.getProperty("run_id"); + Properties plainConfiguration = connection.serverCommands().getConfig("port"); + String plainPortText = + plainConfiguration == null ? null : plainConfiguration.getProperty("port"); + Properties tlsConfiguration = connection.serverCommands().getConfig("tls-port"); + String tlsPortText = + tlsConfiguration == null ? null : tlsConfiguration.getProperty("tls-port"); + return validatedRedisObservation( + runId, plainPortText, tlsPortText, trustCaDigest); + }); + if (values == null) { + throw new IllegalStateException("Redis live observation was unavailable"); + } + return values; + } catch (RuntimeException failure) { + throw new IllegalStateException("local Redis identity/TLS recheck failed"); + } + } + } + + private static String singleNullableText(Connection connection, String sql) throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(sql); + ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + throw new SQLException("local PostgreSQL observation returned no row"); + } + String value = rows.getString(1); + if (rows.next()) { + throw new SQLException("local PostgreSQL observation returned multiple rows"); + } + return value; + } + } + + private static Integer singleNullableInteger(Connection connection, String sql) + throws SQLException { + try (PreparedStatement statement = connection.prepareStatement(sql); + ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + throw new SQLException("local PostgreSQL observation returned no row"); + } + int value = rows.getInt(1); + Integer result = rows.wasNull() ? null : value; + if (rows.next()) { + throw new SQLException("local PostgreSQL observation returned multiple rows"); + } + return result; + } + } + + private static final class ProtocolFencedCohort + implements CanonicalGameplayLegacyMigrationOwner.FencedCohort { + private final CanonicalGameplayMigrationDriverProtocol.Initialization initialization; + private final CanonicalGameplayMigrationDriverProtocol protocol; + private final LiveObservationReader observationReader; + private final CanonicalGameplayMigrationDriverProtocol.LocalObservation baseline; + private final String postgresUser; + private final String redisCaDigest; + + private ProtocolFencedCohort( + CanonicalGameplayMigrationDriverProtocol.Initialization initialization, + CanonicalGameplayMigrationDriverProtocol protocol, + LiveObservationReader observationReader, + CanonicalGameplayMigrationDriverProtocol.LocalObservation baseline, + String postgresUser, + String redisCaDigest) { + this.initialization = Objects.requireNonNull(initialization, "initialization"); + this.protocol = Objects.requireNonNull(protocol, "protocol"); + this.observationReader = Objects.requireNonNull(observationReader, "observationReader"); + this.baseline = Objects.requireNonNull(baseline, "baseline"); + this.postgresUser = Objects.requireNonNull(postgresUser, "postgresUser"); + this.redisCaDigest = Objects.requireNonNull(redisCaDigest, "redisCaDigest"); + } + + @Override + public java.util.UUID cohortId() { + return initialization.cohortId(); + } + + @Override + public java.util.UUID legacyWriterFence() { + return initialization.legacyWriterFence(); + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return initialization.storageIdentity(); + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + if (!initialization.storageIdentity().equals(expectedIdentity)) { + throw new IllegalStateException("migration storage identity changed"); + } + CanonicalGameplayMigrationDriverProtocol.LocalObservation current = observationReader.read(); + requireIdentityMatches(initialization, current, postgresUser, redisCaDigest); + if (!baseline.equals(current)) { + throw new IllegalStateException( + "local PostgreSQL/Redis configuration changed during migration"); + } + protocol.requireFreshObservation(initialization, current); + } + } + + record MigrationSourceIdentity(String version, String script, String type, Integer checksum) {} + + private record PhysicalSchemaSnapshot( + List schemas, + List relations, + List columns, + List indexes, + List constraints, + List types, + List domainConstraints, + List enumLabels, + List sequences, + List routines, + List triggers, + List policies, + List extensions) { + private PhysicalSchemaSnapshot { + schemas = List.copyOf(schemas); + relations = List.copyOf(relations); + columns = List.copyOf(columns); + indexes = List.copyOf(indexes); + constraints = List.copyOf(constraints); + types = List.copyOf(types); + domainConstraints = List.copyOf(domainConstraints); + enumLabels = List.copyOf(enumLabels); + sequences = List.copyOf(sequences); + routines = List.copyOf(routines); + triggers = List.copyOf(triggers); + policies = List.copyOf(policies); + extensions = List.copyOf(extensions); + int totalRows = 0; + long totalBytes = 0; + for (List inventory : + List.of( + schemas, + relations, + columns, + indexes, + constraints, + types, + domainConstraints, + enumLabels, + sequences, + routines, + triggers, + policies, + extensions)) { + totalRows += inventory.size(); + for (String row : inventory) { + totalBytes += row.getBytes(StandardCharsets.UTF_8).length; + } + } + if (totalRows > MAX_CATALOG_ROWS || totalBytes > MAX_CATALOG_BYTES) { + throw new IllegalArgumentException( + "physical PostgreSQL schema inventory exceeded its total bound"); + } + } + + private boolean isEmptyCohort() { + return relations.isEmpty() + && columns.isEmpty() + && indexes.isEmpty() + && constraints.isEmpty() + && types.isEmpty() + && domainConstraints.isEmpty() + && enumLabels.isEmpty() + && sequences.isEmpty() + && routines.isEmpty() + && triggers.isEmpty() + && policies.isEmpty() + && extensions.isEmpty(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java new file mode 100644 index 0000000000..456833fdce --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java @@ -0,0 +1,472 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +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.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.regex.Pattern; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; + +/** Bounded, closed-shape stdin/stdout protocol used only by the trusted finite migration runner. */ +final class CanonicalGameplayMigrationDriverProtocol implements AutoCloseable { + static final String SCHEMA = "firemud.gs.migration-driver/v1"; + static final int MAX_FRAME_BYTES = 32 * 1024; + static final int MAX_REOBSERVATIONS = 128; + static final Duration INITIAL_FRAME_TIMEOUT = Duration.ofSeconds(30); + static final Duration OUTPUT_FRAME_TIMEOUT = Duration.ofSeconds(30); + static final Duration OBSERVATION_REPLY_TIMEOUT = Duration.ofSeconds(600); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern HOST = + Pattern.compile( + "(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*"); + private static final Set IDENTITY_FIELDS = + Set.of( + "kubernetesClusterUid", + "kubernetesNamespaceUid", + "producerPodUid", + "producerContainerId", + "producerNodeUid", + "postgresSystemIdentifier", + "postgresDatabaseOid", + "postgresStorageUid", + "redisRunId", + "redisStorageUid"); + private static final Set INITIAL_FIELDS = + Set.of( + "schema", + "kind", + "operation", + "cohortId", + "legacyWriterFence", + "storageIdentity", + "fenceDigest", + "redisHost", + "redisPort"); + private static final Set POSTGRES_OBSERVATION_FIELDS = + Set.of( + "systemIdentifier", + "databaseOid", + "serverAddress", + "serverPort", + "listenAddresses", + "hbaFile", + "unixSocketDirectories", + "rolesDigest", + "hbaRulesDigest"); + private static final Set REDIS_OBSERVATION_FIELDS = + Set.of("runId", "tlsEnabled", "tlsPort", "trustCaSha256"); + private static final Set REPLY_FIELDS = + Set.of( + "schema", + "kind", + "sequence", + "nonce", + "cohortId", + "legacyWriterFence", + "storageIdentity", + "fenceDigest"); + + private final InputStream input; + private final OutputStream output; + private final ObjectMapper mapper; + private final ExecutorService reader; + private final ExecutorService writer; + private final Duration outputFrameTimeout; + private final Set issuedNonces = new HashSet<>(); + private long sequence; + private boolean initialized; + + CanonicalGameplayMigrationDriverProtocol(InputStream input, OutputStream output) { + this(input, output, OUTPUT_FRAME_TIMEOUT); + } + + CanonicalGameplayMigrationDriverProtocol( + InputStream input, OutputStream output, Duration outputFrameTimeout) { + this.input = Objects.requireNonNull(input, "input"); + this.output = Objects.requireNonNull(output, "output"); + this.outputFrameTimeout = Objects.requireNonNull(outputFrameTimeout, "outputFrameTimeout"); + if (outputFrameTimeout.isZero() || outputFrameTimeout.isNegative()) { + throw new IllegalArgumentException("output frame timeout must be positive"); + } + JsonFactory factory = + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + mapper = + new ObjectMapper(factory) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); + reader = + Executors.newSingleThreadExecutor( + task -> { + Thread thread = new Thread(task, "gs-migration-driver-stdin"); + thread.setDaemon(true); + return thread; + }); + writer = + Executors.newSingleThreadExecutor( + task -> { + Thread thread = new Thread(task, "gs-migration-driver-stdout"); + thread.setDaemon(true); + return thread; + }); + } + + Initialization readInitialization() { + if (initialized) { + throw reject("migration driver protocol was already initialized"); + } + JsonNode root = requireObject(readFrame(INITIAL_FRAME_TIMEOUT), "initialize request"); + requireExactFields(root, INITIAL_FIELDS, "initialize request"); + requireTextEquals(root, "schema", SCHEMA); + requireTextEquals(root, "kind", "initialize"); + requireTextEquals(root, "operation", "migrate-empty-cohort"); + UUID cohortId = parseUuid(root, "cohortId"); + UUID legacyWriterFence = parseUuid(root, "legacyWriterFence"); + if (!isUuidV4(cohortId) || !isUuidV4(legacyWriterFence)) { + throw reject( + "migration initialization requires persisted UUIDv4 cohort and fence identities"); + } + CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity = + parseStorageIdentity(root.get("storageIdentity")); + String fenceDigest = requireSha256(root, "fenceDigest"); + String redisHost = requireText(root, "redisHost"); + if (!HOST.matcher(redisHost).matches()) { + throw reject("migration Redis host is not canonical DNS text"); + } + JsonNode redisPort = root.get("redisPort"); + if (redisPort == null + || !redisPort.isIntegralNumber() + || !redisPort.canConvertToInt() + || redisPort.intValue() != 6380) { + throw reject("migration Redis port must be exactly 6380"); + } + initialized = true; + return new Initialization( + cohortId, legacyWriterFence, storageIdentity, fenceDigest, redisHost, 6380); + } + + void requireFreshObservation(Initialization initialization, LocalObservation observation) { + Objects.requireNonNull(initialization, "initialization"); + Objects.requireNonNull(observation, "observation"); + if (!initialized) { + throw reject("migration driver protocol is not initialized"); + } + if (sequence >= MAX_REOBSERVATIONS) { + throw reject("migration driver exceeded its live re-observation bound"); + } + sequence++; + UUID nonce = UUID.randomUUID(); + if (nonce.equals(new UUID(0L, 0L)) || !issuedNonces.add(nonce)) { + throw reject("migration driver could not issue a fresh protocol nonce"); + } + + Map request = new LinkedHashMap<>(); + request.put("schema", SCHEMA); + request.put("kind", "reobserve"); + request.put("sequence", sequence); + request.put("nonce", nonce.toString()); + request.put("cohortId", initialization.cohortId().toString()); + request.put("legacyWriterFence", initialization.legacyWriterFence().toString()); + request.put("storageIdentityDigest", initialization.storageIdentity().digest()); + request.put("fenceDigest", initialization.fenceDigest()); + request.put( + "postgres", validatedObservation(observation.postgres(), POSTGRES_OBSERVATION_FIELDS)); + request.put("redis", validatedObservation(observation.redis(), REDIS_OBSERVATION_FIELDS)); + writeFrame(request); + + JsonNode reply = requireObject(readFrame(OBSERVATION_REPLY_TIMEOUT), "fresh observation reply"); + requireExactFields(reply, REPLY_FIELDS, "fresh observation reply"); + requireTextEquals(reply, "schema", SCHEMA); + requireTextEquals(reply, "kind", "observed"); + requireLongEquals(reply, "sequence", sequence); + requireTextEquals(reply, "nonce", nonce.toString()); + requireTextEquals(reply, "cohortId", initialization.cohortId().toString()); + requireTextEquals(reply, "legacyWriterFence", initialization.legacyWriterFence().toString()); + requireTextEquals(reply, "fenceDigest", initialization.fenceDigest()); + CanonicalGameplayLegacyMigrationStorageIdentity observedIdentity = + parseStorageIdentity(reply.get("storageIdentity")); + if (!initialization.storageIdentity().equals(observedIdentity)) { + throw reject("trusted runner observed a different physical storage identity"); + } + } + + private Map validatedObservation( + Map values, Set expectedFields) { + Objects.requireNonNull(values, "local observation"); + if (!values.keySet().equals(expectedFields)) { + throw reject("local observation fields do not match the closed protocol shape"); + } + return values; + } + + private JsonNode readFrame(Duration timeout) { + Future frame = reader.submit(this::readFrameBytes); + try { + byte[] bytes = frame.get(timeout.toMillis(), TimeUnit.MILLISECONDS); + if (bytes == null || bytes.length == 0) { + throw reject("migration driver protocol reached EOF or an empty frame"); + } + String json = decodeUtf8(bytes); + JsonNode node = mapper.readTree(json); + if (node == null) { + throw reject("migration driver protocol frame is empty"); + } + return node; + } catch (TimeoutException timedOut) { + frame.cancel(true); + throw reject("migration driver protocol frame timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + frame.cancel(true); + throw reject("migration driver protocol was interrupted"); + } catch (ExecutionException | IOException malformed) { + throw reject("migration driver protocol frame is malformed"); + } + } + + private byte[] readFrameBytes() throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + while (true) { + int next = input.read(); + if (next < 0) { + return null; + } + if (next == '\n') { + byte[] frame = bytes.toByteArray(); + if (frame.length > 0 && frame[frame.length - 1] == '\r') { + return java.util.Arrays.copyOf(frame, frame.length - 1); + } + return frame; + } + if (bytes.size() >= MAX_FRAME_BYTES) { + throw new IOException("frame exceeds bound"); + } + bytes.write(next); + } + } + + private String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw reject("migration driver protocol frame is not canonical UTF-8"); + } + } + + private void writeFrame(Map value) { + byte[] frame; + try { + byte[] encoded = mapper.writeValueAsBytes(value); + if (encoded.length == 0 || encoded.length > MAX_FRAME_BYTES) { + throw reject("migration driver protocol output exceeded its frame bound"); + } + frame = java.util.Arrays.copyOf(encoded, encoded.length + 1); + frame[frame.length - 1] = '\n'; + } catch (IOException serializationFailure) { + throw reject("migration driver protocol output could not be encoded"); + } + Future writing = + writer.submit( + () -> { + try { + output.write(frame); + output.flush(); + } catch (IOException failed) { + throw new java.io.UncheckedIOException(failed); + } + }); + try { + writing.get(outputFrameTimeout.toNanos(), TimeUnit.NANOSECONDS); + } catch (TimeoutException timedOut) { + writing.cancel(true); + writer.shutdownNow(); + throw reject("migration driver protocol output timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + writing.cancel(true); + writer.shutdownNow(); + throw reject("migration driver protocol output was interrupted"); + } catch (ExecutionException failed) { + throw reject("migration driver protocol output failed"); + } + } + + private static JsonNode requireObject(JsonNode node, String label) { + if (node == null || !node.isObject()) { + throw reject(label + " must be one JSON object"); + } + return node; + } + + private static void requireExactFields(JsonNode node, Set expected, String label) { + Set actual = new HashSet<>(); + node.fieldNames().forEachRemaining(actual::add); + if (!actual.equals(expected)) { + throw reject(label + " has missing or unknown fields"); + } + } + + private static void requireTextEquals(JsonNode node, String field, String expected) { + if (!node.has(field) + || !node.get(field).isTextual() + || !expected.equals(node.get(field).textValue())) { + throw reject("migration driver protocol field " + field + " did not match"); + } + } + + private static String requireText(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw reject("migration driver protocol field " + field + " must be text"); + } + String text = value.textValue(); + if (text.isBlank() + || !text.equals(text.strip()) + || text.chars().anyMatch(Character::isISOControl)) { + throw reject("migration driver protocol field " + field + " is not canonical text"); + } + return text; + } + + private static UUID parseUuid(JsonNode node, String field) { + String text = requireText(node, field); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text)) { + throw reject("migration driver protocol field " + field + " is not a canonical UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw reject("migration driver protocol field " + field + " is not a canonical UUID"); + } + } + + private static boolean isUuidV4(UUID value) { + return value.version() == 4 && value.variant() == 2 && !value.equals(new UUID(0L, 0L)); + } + + private static String requireSha256(JsonNode node, String field) { + String value = requireText(node, field); + if (!SHA256.matcher(value).matches()) { + throw reject("migration driver protocol field " + field + " is not a SHA-256 digest"); + } + return value; + } + + private static void requireLongEquals(JsonNode node, String field, long expected) { + JsonNode value = node.get(field); + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToLong() + || value.longValue() != expected) { + throw reject("migration driver protocol field " + field + " did not match"); + } + } + + private static CanonicalGameplayLegacyMigrationStorageIdentity parseStorageIdentity( + JsonNode node) { + requireObject(node, "storageIdentity"); + requireExactFields(node, IDENTITY_FIELDS, "storageIdentity"); + String clusterUid = requireText(node, "kubernetesClusterUid"); + String namespaceUid = requireText(node, "kubernetesNamespaceUid"); + String podUid = requireText(node, "producerPodUid"); + String containerId = requireText(node, "producerContainerId"); + String nodeUid = requireText(node, "producerNodeUid"); + String postgresSystemIdentifier = requireText(node, "postgresSystemIdentifier"); + JsonNode databaseOid = node.get("postgresDatabaseOid"); + if (databaseOid == null + || !databaseOid.isIntegralNumber() + || !databaseOid.canConvertToLong() + || databaseOid.longValue() <= 0L + || databaseOid.longValue() > 0xffff_ffffL) { + throw reject("storageIdentity.postgresDatabaseOid must be an unsigned 32-bit JSON integer"); + } + String postgresStorageUid = requireText(node, "postgresStorageUid"); + String redisRunId = requireText(node, "redisRunId"); + String redisStorageUid = requireText(node, "redisStorageUid"); + try { + return new CanonicalGameplayLegacyMigrationStorageIdentity( + clusterUid, + namespaceUid, + podUid, + containerId, + nodeUid, + postgresSystemIdentifier, + databaseOid.longValue(), + postgresStorageUid, + redisRunId, + redisStorageUid); + } catch (IllegalArgumentException invalid) { + throw reject("migration driver storage identity is invalid"); + } + } + + private static IllegalStateException reject(String message) { + return new IllegalStateException(message); + } + + @Override + public void close() { + reader.shutdownNow(); + writer.shutdownNow(); + try { + input.close(); + } catch (IOException ignored) { + // The finite driver denies the operation regardless; no stream error details are exposed. + } + } + + record Initialization( + UUID cohortId, + UUID legacyWriterFence, + CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity, + String fenceDigest, + String redisHost, + int redisPort) { + Initialization { + Objects.requireNonNull(cohortId, "cohortId"); + Objects.requireNonNull(legacyWriterFence, "legacyWriterFence"); + Objects.requireNonNull(storageIdentity, "storageIdentity"); + Objects.requireNonNull(fenceDigest, "fenceDigest"); + Objects.requireNonNull(redisHost, "redisHost"); + } + } + + record LocalObservation(Map postgres, Map redis) { + LocalObservation { + postgres = + java.util.Collections.unmodifiableMap( + new LinkedHashMap<>(Objects.requireNonNull(postgres, "postgres"))); + redis = + java.util.Collections.unmodifiableMap( + new LinkedHashMap<>(Objects.requireNonNull(redis, "redis"))); + } + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V12__retained_tenant_association.sql b/services/game-session-service/src/main/resources/db/migration/V12__retained_tenant_association.sql new file mode 100644 index 0000000000..402b46cfe6 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V12__retained_tenant_association.sql @@ -0,0 +1,105 @@ +CREATE TABLE game_session_retained_tenant_association ( + operation_id UUID PRIMARY KEY, + approval_schema_version INTEGER NOT NULL, + target_namespace VARCHAR(63) NOT NULL, + association_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + approval_operation_id UUID NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + game_session_evidence_digest VARCHAR(71) NOT NULL, + approval_manifest_digest VARCHAR(71) NOT NULL, + approval_signature VARCHAR(88) NOT NULL, + snapshot_canonical_json TEXT NOT NULL, + snapshot_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_retained_tenant_association_request + UNIQUE (target_namespace, association_request_id), + CONSTRAINT uq_gs_retained_tenant_association_canonical + UNIQUE (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_retained_tenant_association_legacy_key + UNIQUE (target_namespace, legacy_game_session_tenant_id), + CONSTRAINT chk_gs_retained_tenant_association_schema + CHECK (approval_schema_version = 1), + CONSTRAINT chk_gs_retained_tenant_association_operation_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND approval_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_retained_tenant_association_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gs_retained_tenant_association_approval_labels CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_retained_tenant_association_signed_at CHECK ( + char_length(signed_at) BETWEEN 1 AND 64 + ), + CONSTRAINT chk_gs_retained_tenant_association_retained_key CHECK ( + legacy_game_session_tenant_id > 0 + ), + CONSTRAINT chk_gs_retained_tenant_association_canonical_tenant CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_retained_tenant_association_source_row CHECK (source_game_row_id > 0), + CONSTRAINT chk_gs_retained_tenant_association_source_key CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_retained_tenant_association_provenance CHECK ( + provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29') + ), + CONSTRAINT chk_gs_retained_tenant_association_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND approval_manifest_digest ~ '^sha256:[0-9a-f]{64}$' + AND snapshot_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gs_retained_tenant_association_signature CHECK ( + approval_signature ~ '^[A-Za-z0-9+/]{86}==$' + ), + CONSTRAINT chk_gs_retained_tenant_association_snapshot CHECK ( + octet_length(snapshot_canonical_json) > 0 + ) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_retained_tenant_association_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained tenant association evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_retained_tenant_association_immutable +BEFORE UPDATE OR DELETE ON game_session_retained_tenant_association +FOR EACH ROW EXECUTE FUNCTION reject_game_session_retained_tenant_association_mutation(); + +CREATE TRIGGER game_session_retained_tenant_association_no_truncate +BEFORE TRUNCATE ON game_session_retained_tenant_association +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_retained_tenant_association_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql new file mode 100644 index 0000000000..185fd8f07f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V13__retained_tenant_payload_retention.sql @@ -0,0 +1,267 @@ +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_schema; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_approval_labels; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_signed_at; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_operation_ids; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_digests; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_signature; +ALTER TABLE game_session_retained_tenant_association + DROP CONSTRAINT chk_gs_retained_tenant_association_snapshot; + +ALTER TABLE game_session_retained_tenant_association + ADD COLUMN captured_at TIMESTAMPTZ; +ALTER TABLE game_session_retained_tenant_association + ADD COLUMN terminal_outcome VARCHAR(32) NOT NULL DEFAULT 'ASSOCIATED'; + +CREATE TABLE game_session_retained_tenant_association_payload ( + operation_id UUID PRIMARY KEY + REFERENCES game_session_retained_tenant_association(operation_id) ON DELETE RESTRICT, + request_digest VARCHAR(71) NOT NULL, + approval_operation_id UUID NOT NULL, + approval_schema_version INTEGER NOT NULL, + signer_key_id VARCHAR(128) NOT NULL, + approved_by VARCHAR(256) NOT NULL, + approval_reference VARCHAR(512) NOT NULL, + signed_at TEXT NOT NULL, + game_session_projection_digest VARCHAR(71), + game_session_evidence_digest VARCHAR(71) NOT NULL, + approval_manifest_digest VARCHAR(71) NOT NULL, + approval_signature VARCHAR(88) NOT NULL, + snapshot_canonical_json TEXT NOT NULL, + snapshot_evidence_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT chk_gs_retained_tenant_association_payload_schema + CHECK (approval_schema_version IN (1, 2)), + CONSTRAINT chk_gs_retained_tenant_association_payload_capture CHECK ( + (approval_schema_version = 1 AND game_session_projection_digest IS NULL) + OR (approval_schema_version = 2 + AND game_session_projection_digest IS NOT NULL + AND game_session_projection_digest ~ '^sha256:[0-9a-f]{64}$') + ), + CONSTRAINT chk_gs_retained_assoc_payload_approval_operation_id CHECK ( + approval_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_retained_tenant_association_payload_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_session_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND approval_manifest_digest ~ '^sha256:[0-9a-f]{64}$' + AND snapshot_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gs_retained_tenant_association_payload_signature CHECK ( + approval_signature ~ '^[A-Za-z0-9+/]{86}==$' + ), + CONSTRAINT chk_gs_retained_tenant_association_payload_text CHECK ( + char_length(signer_key_id) BETWEEN 1 AND 128 + AND char_length(approved_by) BETWEEN 1 AND 256 + AND char_length(approval_reference) BETWEEN 1 AND 512 + AND char_length(signed_at) BETWEEN 1 AND 64 + AND octet_length(signer_key_id) <= 128 + AND octet_length(approved_by) <= 256 + AND octet_length(approval_reference) <= 512 + AND signer_key_id !~ '[[:cntrl:]]' + AND approved_by !~ '[[:cntrl:]]' + AND approval_reference !~ '[[:cntrl:]]' + AND signer_key_id !~ '^[[:space:]]*$' + AND approved_by !~ '^[[:space:]]*$' + AND approval_reference !~ '^[[:space:]]*$' + ) +); + +INSERT INTO game_session_retained_tenant_association_payload ( + operation_id, + request_digest, + approval_operation_id, + approval_schema_version, + signer_key_id, + approved_by, + approval_reference, + signed_at, + game_session_evidence_digest, + approval_manifest_digest, + approval_signature, + snapshot_canonical_json, + snapshot_evidence_digest, + receipt_digest +) +SELECT + operation_id, + request_digest, + approval_operation_id, + approval_schema_version, + signer_key_id, + approved_by, + approval_reference, + signed_at, + game_session_evidence_digest, + approval_manifest_digest, + approval_signature, + snapshot_canonical_json, + snapshot_evidence_digest, + receipt_digest +FROM game_session_retained_tenant_association; + +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_schema_version; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN request_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_operation_id; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN signer_key_id; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approved_by; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_reference; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN signed_at; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN game_session_evidence_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_manifest_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN approval_signature; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN snapshot_canonical_json; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN snapshot_evidence_digest; +ALTER TABLE game_session_retained_tenant_association + DROP COLUMN receipt_digest; + +ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT chk_gs_retained_tenant_association_operation_ids CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ); + +ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT chk_gs_retained_tenant_association_capture_time CHECK ( + captured_at IS NULL OR captured_at <= created_at + ); +ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT chk_gs_retained_tenant_association_terminal_outcome CHECK ( + terminal_outcome IN ('ASSOCIATED') + ); + +CREATE TABLE game_session_retained_tenant_association_legal_hold ( + hold_id UUID PRIMARY KEY, + operation_id UUID NOT NULL + REFERENCES game_session_retained_tenant_association(operation_id) ON DELETE RESTRICT, + hold_scope VARCHAR(32) NOT NULL, + reason_code VARCHAR(32) NOT NULL, + case_reference VARCHAR(256) NOT NULL, + authorization_id UUID NOT NULL, + authorized_principal VARCHAR(256) NOT NULL, + authorized_at TIMESTAMPTZ NOT NULL, + review_at TIMESTAMPTZ NOT NULL, + released_at TIMESTAMPTZ, + released_by VARCHAR(256), + release_reference VARCHAR(256), + CONSTRAINT chk_gs_retained_tenant_hold_scope CHECK (hold_scope = 'RAW_PAYLOAD'), + CONSTRAINT chk_gs_retained_tenant_hold_reason CHECK ( + reason_code IN ('LITIGATION', 'REGULATORY', 'SECURITY_CASE') + ), + CONSTRAINT chk_gs_retained_tenant_hold_authorization CHECK ( + hold_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND authorization_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND char_length(case_reference) BETWEEN 1 AND 256 + AND char_length(authorized_principal) BETWEEN 1 AND 256 + AND review_at > authorized_at + ), + CONSTRAINT chk_gs_retained_tenant_hold_release CHECK ( + (released_at IS NULL AND released_by IS NULL AND release_reference IS NULL) + OR (released_at IS NOT NULL + AND released_by IS NOT NULL + AND release_reference IS NOT NULL + AND char_length(released_by) BETWEEN 1 AND 256 + AND char_length(release_reference) BETWEEN 1 AND 256) + ) +); + +CREATE UNIQUE INDEX uq_gs_retained_tenant_association_active_hold + ON game_session_retained_tenant_association_legal_hold (operation_id) + WHERE released_at IS NULL; + +CREATE INDEX ix_gs_retained_tenant_association_payload_expiry + ON game_session_retained_tenant_association (captured_at, operation_id); + +-- [jooq ignore start] +CREATE FUNCTION reject_unverified_game_session_retained_tenant_hold() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained-tenant legal holds require an authenticated owner authorization boundary' + USING ERRCODE = 'insufficient_privilege'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_hold_authentication_required + BEFORE INSERT ON game_session_retained_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION reject_unverified_game_session_retained_tenant_hold(); + +CREATE FUNCTION guard_game_session_retained_tenant_payload_update() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained tenant payload is immutable' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_payload_immutable + BEFORE UPDATE ON game_session_retained_tenant_association_payload + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_payload_update(); + +CREATE FUNCTION guard_game_session_retained_tenant_payload_delete() RETURNS trigger AS $$ +BEGIN + IF OLD.operation_id IN ( + SELECT operation_id + FROM game_session_retained_tenant_association_legal_hold + WHERE released_at IS NULL + ) THEN + RAISE EXCEPTION 'Game Session retained tenant payload is protected by an active legal hold' + USING ERRCODE = 'check_violation'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association association + WHERE association.operation_id = OLD.operation_id + AND association.captured_at IS NOT NULL + AND association.captured_at > clock_timestamp() - INTERVAL '30 days' + ) THEN + RAISE EXCEPTION 'Game Session retained tenant payload has not reached its capture-based expiry' + USING ERRCODE = 'check_violation'; + END IF; + RETURN OLD; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_payload_expiry_guard + BEFORE DELETE ON game_session_retained_tenant_association_payload + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_payload_delete(); + +CREATE FUNCTION guard_game_session_retained_tenant_hold_update() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant legal hold release requires an authenticated owner authorization boundary' + USING ERRCODE = 'insufficient_privilege'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_hold_release_only + BEFORE UPDATE ON game_session_retained_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_hold_update(); + +CREATE FUNCTION guard_game_session_retained_tenant_hold_delete() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant legal hold audit records require a finite policy-controlled expiry' + USING ERRCODE = 'check_violation'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER game_session_retained_tenant_hold_audit_no_delete + BEFORE DELETE ON game_session_retained_tenant_association_legal_hold + FOR EACH ROW EXECUTE FUNCTION guard_game_session_retained_tenant_hold_delete(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V14__published_realm_catalog_snapshots.sql b/services/game-session-service/src/main/resources/db/migration/V14__published_realm_catalog_snapshots.sql new file mode 100644 index 0000000000..4fa680bab2 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V14__published_realm_catalog_snapshots.sql @@ -0,0 +1,244 @@ +CREATE TABLE gameplay_published_realm_catalog_snapshot ( + target_namespace VARCHAR(63) NOT NULL, + tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + catalog_revision BIGINT NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(36) NOT NULL, + tenant_identity_provenance_kind VARCHAR(32) NOT NULL, + version_id BIGINT NOT NULL, + version_number INTEGER NOT NULL, + release_bundle_identity VARCHAR(71) NOT NULL, + publish_workflow_id VARCHAR(1024) NOT NULL, + manifest_hash VARCHAR(128) NOT NULL, + policy_set_digest VARCHAR(71) NOT NULL, + policy_count INTEGER NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_published_realm_catalog_snapshot + PRIMARY KEY (target_namespace, tenant_id, catalog_revision), + CONSTRAINT uq_gs_published_realm_catalog_snapshot_version + UNIQUE (target_namespace, tenant_id, version_id), + CONSTRAINT uq_gs_published_realm_catalog_snapshot_canonical + UNIQUE (target_namespace, canonical_tenant_id, catalog_revision), + CONSTRAINT uq_gs_published_realm_catalog_snapshot_owner_identity + UNIQUE (target_namespace, tenant_id, catalog_revision, canonical_tenant_id), + CONSTRAINT fk_gs_published_realm_catalog_snapshot_association + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_retained_tenant_association + (target_namespace, canonical_tenant_id), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_identity + CHECK (tenant_id > 0 AND source_game_row_id > 0 AND version_id > 0 + AND version_number > 0 AND catalog_revision > 0), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_tenant + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_provenance + CHECK (tenant_identity_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_release_digest + CHECK (release_bundle_identity ~ '^sha256:[0-9a-f]{64}$' + AND policy_set_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_policy_count + CHECK (policy_count BETWEEN 1 AND 128), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_namespace + CHECK (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_source_key + CHECK (char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$'), + CONSTRAINT chk_gs_published_realm_catalog_snapshot_labels + CHECK (char_length(publish_workflow_id) BETWEEN 1 AND 1024 + AND char_length(manifest_hash) BETWEEN 1 AND 128) +); + +CREATE TABLE gameplay_published_realm_catalog_identity ( + target_namespace VARCHAR(63) NOT NULL, + tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + initial_world_slug VARCHAR(64) NOT NULL, + realm_id UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_published_realm_catalog_identity + PRIMARY KEY (target_namespace, canonical_tenant_id, realm_slug), + CONSTRAINT uq_gs_published_realm_catalog_identity_id UNIQUE (realm_id), + CONSTRAINT uq_gs_published_realm_catalog_identity_realm_key + UNIQUE (target_namespace, canonical_tenant_id, realm_slug, realm_id), + CONSTRAINT fk_gs_published_realm_catalog_identity_association + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_retained_tenant_association + (target_namespace, canonical_tenant_id), + CONSTRAINT chk_gs_published_realm_catalog_identity_tenant + CHECK (tenant_id > 0 + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_identity_realm_id + CHECK (realm_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_identity_namespace + CHECK (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT chk_gs_published_realm_catalog_identity_selectors + CHECK (realm_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND initial_world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$') +); + +CREATE TABLE gameplay_published_realm_catalog_entry ( + target_namespace VARCHAR(63) NOT NULL, + tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + catalog_revision BIGINT NOT NULL, + realm_id UUID NOT NULL, + policy_id UUID NOT NULL, + source_revision_id BIGINT NOT NULL, + world_slug VARCHAR(64) NOT NULL, + world_display_name VARCHAR(128) NOT NULL, + realm_slug VARCHAR(64) NOT NULL, + realm_display_name VARCHAR(128) NOT NULL, + visible BOOLEAN NOT NULL, + public_production BOOLEAN NOT NULL, + state_scope VARCHAR(16) NOT NULL, + entry_policy VARCHAR(32) NOT NULL, + policy_json VARCHAR(4096) NOT NULL, + policy_digest VARCHAR(71) NOT NULL, + playable_state_namespace_id UUID, + namespace_resolution VARCHAR(32) NOT NULL, + CONSTRAINT pk_gs_published_realm_catalog_entry + PRIMARY KEY (target_namespace, tenant_id, catalog_revision, realm_id), + CONSTRAINT uq_gs_published_realm_catalog_entry_selector + UNIQUE (target_namespace, tenant_id, catalog_revision, world_slug, realm_slug), + CONSTRAINT uq_gs_published_realm_catalog_entry_realm_slug + UNIQUE (target_namespace, tenant_id, catalog_revision, realm_slug), + CONSTRAINT fk_gs_published_realm_catalog_entry_snapshot + FOREIGN KEY (target_namespace, tenant_id, catalog_revision, canonical_tenant_id) + REFERENCES gameplay_published_realm_catalog_snapshot + (target_namespace, tenant_id, catalog_revision, canonical_tenant_id), + CONSTRAINT fk_gs_published_realm_catalog_entry_identity + FOREIGN KEY (target_namespace, canonical_tenant_id, realm_slug, realm_id) + REFERENCES gameplay_published_realm_catalog_identity + (target_namespace, canonical_tenant_id, realm_slug, realm_id), + CONSTRAINT chk_gs_published_realm_catalog_entry_identity + CHECK (catalog_revision > 0 AND source_revision_id > 0 + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND policy_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_realm_catalog_entry_scope + CHECK (state_scope IN ('SHARED', 'ISOLATED') AND entry_policy = 'PRESEEDED_ONLY'), + CONSTRAINT chk_gs_published_realm_catalog_entry_namespace_resolution + CHECK ((namespace_resolution = 'RESOLVED' + AND playable_state_namespace_id IS NOT NULL + AND playable_state_namespace_id <> + '00000000-0000-0000-0000-000000000000'::UUID) + OR (namespace_resolution = 'AWAITING_LIFECYCLE_PROOF' + AND playable_state_namespace_id IS NULL)), + CONSTRAINT chk_gs_published_realm_catalog_entry_isolated_lifecycle_gate + CHECK (NOT (state_scope = 'ISOLATED' AND namespace_resolution = 'RESOLVED')), + CONSTRAINT chk_gs_published_realm_catalog_entry_selectors + CHECK (world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND realm_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'), + CONSTRAINT chk_gs_published_realm_catalog_entry_digests + CHECK (policy_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(policy_json) BETWEEN 1 AND 4096), + CONSTRAINT chk_gs_published_realm_catalog_entry_display + CHECK (char_length(world_display_name) BETWEEN 1 AND 128 + AND char_length(realm_display_name) BETWEEN 1 AND 128) +); + +CREATE TABLE gameplay_published_tenant_shared_playable_state_namespace ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + allocated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_published_tenant_shared_namespace + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_published_tenant_shared_namespace_id + UNIQUE (playable_state_namespace_id), + CONSTRAINT fk_gs_published_tenant_shared_namespace_association + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_retained_tenant_association + (target_namespace, canonical_tenant_id), + CONSTRAINT chk_gs_published_tenant_shared_namespace_identity + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> + '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_published_tenant_shared_namespace_namespace + CHECK (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$') +); + +-- Completeness and tenant-wide realmSlug uniqueness are checked at commit after all rows in the +-- bounded policy set have been inserted. No truncated prefix can become a committed snapshot. +-- [jooq ignore start] +CREATE FUNCTION validate_gameplay_published_realm_catalog_set() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + expected_count INTEGER; + actual_count INTEGER; + public_count INTEGER; +BEGIN + SELECT snapshot.policy_count + INTO expected_count + FROM gameplay_published_realm_catalog_snapshot snapshot + WHERE snapshot.target_namespace = NEW.target_namespace + AND snapshot.tenant_id = NEW.tenant_id + AND snapshot.catalog_revision = NEW.catalog_revision; + + SELECT COUNT(*)::INTEGER, + COUNT(*) FILTER (WHERE entry.visible AND entry.public_production)::INTEGER + INTO actual_count, public_count + FROM gameplay_published_realm_catalog_entry entry + WHERE entry.target_namespace = NEW.target_namespace + AND entry.tenant_id = NEW.tenant_id + AND entry.catalog_revision = NEW.catalog_revision; + + IF expected_count IS NULL OR actual_count <> expected_count OR public_count <> 1 THEN + RAISE EXCEPTION 'published realm catalog snapshot is incomplete or ambiguous' + USING ERRCODE = 'check_violation'; + END IF; + + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER gameplay_published_realm_catalog_complete_set +AFTER INSERT ON gameplay_published_realm_catalog_entry +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION validate_gameplay_published_realm_catalog_set(); + +CREATE CONSTRAINT TRIGGER gameplay_published_realm_catalog_header_complete_set +AFTER INSERT ON gameplay_published_realm_catalog_snapshot +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION validate_gameplay_published_realm_catalog_set(); + +CREATE FUNCTION reject_gameplay_published_realm_catalog_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session published realm catalog evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER gameplay_published_realm_catalog_snapshot_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_realm_catalog_snapshot +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_snapshot_no_truncate +BEFORE TRUNCATE ON gameplay_published_realm_catalog_snapshot +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_identity_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_realm_catalog_identity +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_identity_no_truncate +BEFORE TRUNCATE ON gameplay_published_realm_catalog_identity +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_entry_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_realm_catalog_entry +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_realm_catalog_entry_no_truncate +BEFORE TRUNCATE ON gameplay_published_realm_catalog_entry +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_tenant_shared_namespace_immutable +BEFORE UPDATE OR DELETE ON gameplay_published_tenant_shared_playable_state_namespace +FOR EACH ROW EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +CREATE TRIGGER gameplay_published_tenant_shared_namespace_no_truncate +BEFORE TRUNCATE ON gameplay_published_tenant_shared_playable_state_namespace +FOR EACH STATEMENT EXECUTE FUNCTION reject_gameplay_published_realm_catalog_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql new file mode 100644 index 0000000000..2fbd6429e1 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V15__published_initial_admission_bind.sql @@ -0,0 +1,82 @@ +-- Keep V9 fixture attempts readable as historical fixture evidence while allowing a new +-- production attempt to reference the exact immutable V14 published snapshot and entry. +ALTER TABLE gameplay_published_realm_catalog_snapshot + ADD CONSTRAINT uq_gs_published_realm_catalog_snapshot_bind_identity + UNIQUE (target_namespace, tenant_id, catalog_revision, canonical_tenant_id, version_id); + +ALTER TABLE gameplay_published_realm_catalog_entry + ADD CONSTRAINT uq_gs_published_realm_catalog_entry_bind_identity + UNIQUE (target_namespace, tenant_id, catalog_revision, realm_id, + playable_state_namespace_id); + +ALTER TABLE gameplay_initial_admission_bind_attempt + ADD COLUMN catalog_source_kind character varying(16) NOT NULL DEFAULT 'V9_FIXTURE', + ADD COLUMN fixture_catalog_realm_id uuid, + ADD COLUMN published_target_namespace character varying(63), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN game_template_id bigint, + ADD COLUMN launch_descriptor_id character varying(128), + ADD COLUMN release_bundle_id bigint, + ADD COLUMN published_release_bundle_ref character varying(200), + ADD COLUMN version_state_epoch bigint; + +UPDATE gameplay_initial_admission_bind_attempt + SET fixture_catalog_realm_id = realm_id; + +ALTER TABLE gameplay_initial_admission_bind_attempt + DROP CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_fk; + +ALTER TABLE gameplay_initial_admission_bind_attempt + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_fixture_catalog_fk + FOREIGN KEY (tenant_id, fixture_catalog_realm_id, playable_state_namespace_id, catalog_revision) + REFERENCES gameplay_initial_admission_bind_catalog + (tenant_id, realm_id, playable_state_namespace_id, catalog_revision), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_snapshot_fk + FOREIGN KEY (published_target_namespace, tenant_id, catalog_revision, + canonical_tenant_id, version_id) + REFERENCES gameplay_published_realm_catalog_snapshot + (target_namespace, tenant_id, catalog_revision, canonical_tenant_id, version_id), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_entry_fk + FOREIGN KEY (published_target_namespace, tenant_id, catalog_revision, realm_id, + playable_state_namespace_id) + REFERENCES gameplay_published_realm_catalog_entry + (target_namespace, tenant_id, catalog_revision, realm_id, + playable_state_namespace_id), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_source_shape + CHECK ( + (catalog_source_kind = 'V9_FIXTURE' + AND fixture_catalog_realm_id = realm_id + AND published_target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND game_template_id IS NULL + AND launch_descriptor_id IS NULL + AND release_bundle_id IS NULL + AND published_release_bundle_ref IS NULL + AND version_state_epoch IS NULL) + OR + (catalog_source_kind = 'V14_PUBLISHED' + AND fixture_catalog_realm_id IS NULL + AND published_target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND game_template_id IS NOT NULL AND game_template_id > 0 + AND launch_descriptor_id IS NOT NULL + AND release_bundle_id IS NOT NULL AND release_bundle_id > 0 + AND published_release_bundle_ref IS NOT NULL + AND version_state_epoch IS NOT NULL AND version_state_epoch > 0 + AND playable_state_scope = 'SHARED' + AND expected_no_prior_pointer) + ); + +ALTER TABLE gameplay_initial_admission_bind_attempt + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_namespace + CHECK (published_target_namespace IS NULL OR + (octet_length(published_target_namespace) BETWEEN 1 AND 63 + AND published_target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_identity + CHECK (canonical_tenant_id IS NULL OR + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + ADD CONSTRAINT gameplay_initial_admission_bind_attempt_published_launch + CHECK ((launch_descriptor_id IS NULL OR + char_length(launch_descriptor_id) BETWEEN 1 AND 128) + AND (published_release_bundle_ref IS NULL OR + char_length(published_release_bundle_ref) BETWEEN 1 AND 200)); diff --git a/services/game-session-service/src/main/resources/db/migration/V20__closed_published_realm_policy_evidence.sql b/services/game-session-service/src/main/resources/db/migration/V20__closed_published_realm_policy_evidence.sql new file mode 100644 index 0000000000..4718421c79 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V20__closed_published_realm_policy_evidence.sql @@ -0,0 +1,64 @@ +-- Preserve V14/V15 rows as historical evidence. Only newly written rows with the complete +-- canonical Game Design carrier and canonical Version UUID are eligible for owner reads. +ALTER TABLE gameplay_published_realm_catalog_snapshot + ADD COLUMN canonical_version_id UUID, + ADD COLUMN policy_set_evidence BYTEA, + ADD COLUMN published_release_bundle_ref VARCHAR(1024), + ADD CONSTRAINT chk_gs_published_realm_catalog_snapshot_closed_evidence + CHECK ( + (canonical_version_id IS NULL + AND policy_set_evidence IS NULL + AND published_release_bundle_ref IS NULL) + OR + (canonical_version_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND policy_set_evidence IS NOT NULL + AND octet_length(policy_set_evidence) BETWEEN 1 AND 4194304 + AND published_release_bundle_ref IS NOT NULL + AND char_length(published_release_bundle_ref) BETWEEN 1 AND 1024) + ); + +-- V14's numeric-only uniqueness is retained within historical rows but cannot prevent a new +-- exact closed carrier for that same sealed private-row correlation from being stored. +ALTER TABLE gameplay_published_realm_catalog_snapshot + DROP CONSTRAINT uq_gs_published_realm_catalog_snapshot_version; + +CREATE UNIQUE INDEX uq_gs_published_realm_catalog_snapshot_legacy_version + ON gameplay_published_realm_catalog_snapshot (target_namespace, tenant_id, version_id) + WHERE canonical_version_id IS NULL; + +CREATE UNIQUE INDEX uq_gs_published_realm_catalog_snapshot_closed_private_version + ON gameplay_published_realm_catalog_snapshot (target_namespace, tenant_id, version_id) + WHERE canonical_version_id IS NOT NULL; + +CREATE UNIQUE INDEX uq_gs_published_realm_catalog_snapshot_canonical_version + ON gameplay_published_realm_catalog_snapshot + (target_namespace, canonical_tenant_id, canonical_version_id) + WHERE canonical_version_id IS NOT NULL; + +ALTER TABLE gameplay_published_realm_catalog_entry + ADD COLUMN source_revision_uuid UUID; + +ALTER TABLE gameplay_published_realm_catalog_entry + ALTER COLUMN source_revision_id DROP NOT NULL; + +ALTER TABLE gameplay_published_realm_catalog_entry + DROP CONSTRAINT chk_gs_published_realm_catalog_entry_identity; + +ALTER TABLE gameplay_published_realm_catalog_entry + ADD CONSTRAINT chk_gs_published_realm_catalog_entry_closed_source_identity + CHECK ( + (source_revision_id IS NOT NULL + AND source_revision_id > 0 + AND source_revision_uuid IS NULL) + OR + (source_revision_id IS NULL + AND source_revision_uuid IS NOT NULL + AND source_revision_uuid <> '00000000-0000-0000-0000-000000000000'::UUID) + ); + +ALTER TABLE gameplay_published_realm_catalog_entry + ADD CONSTRAINT chk_gs_published_realm_catalog_entry_identity_v20 + CHECK (catalog_revision > 0 + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND policy_id <> '00000000-0000-0000-0000-000000000000'::UUID); diff --git a/services/game-session-service/src/main/resources/db/migration/V21__canonical_game_instance_owner_identity.sql b/services/game-session-service/src/main/resources/db/migration/V21__canonical_game_instance_owner_identity.sql new file mode 100644 index 0000000000..f047de30bf --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V21__canonical_game_instance_owner_identity.sql @@ -0,0 +1,55 @@ +-- Preserve historical numeric owner identifiers exactly; no Account UUID reverse mapping exists. +ALTER TABLE game_instances + ALTER COLUMN owner_account_id DROP NOT NULL; + +ALTER TABLE game_instances + ADD COLUMN owner_account_uuid uuid; + +ALTER TABLE game_instances + ADD CONSTRAINT game_instances_owner_identity_present_and_valid + CHECK ( + (owner_account_id IS NOT NULL OR owner_account_uuid IS NOT NULL) + AND ( + owner_account_uuid IS NULL + OR owner_account_uuid <> '00000000-0000-0000-0000-000000000000'::uuid + ) + ); + +CREATE UNIQUE INDEX uq_game_instances_running_tenant_owner_uuid + ON game_instances (tenant_id, owner_account_uuid) + WHERE status = 'RUNNING' AND owner_account_uuid IS NOT NULL; + +-- Allocate canonical Game Session identity only for rows created after this forward migration. +ALTER TABLE game_instances + ADD COLUMN game_instance_uuid uuid; + +ALTER TABLE game_instances + ADD CONSTRAINT game_instances_game_instance_uuid_non_nil + CHECK ( + game_instance_uuid IS NULL + OR game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::uuid + ); + +ALTER TABLE game_instances + ADD CONSTRAINT uq_game_instances_game_instance_uuid UNIQUE (game_instance_uuid); + +-- [jooq ignore start] +CREATE FUNCTION enforce_game_instance_uuid_immutable() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.game_instance_uuid IS DISTINCT FROM OLD.game_instance_uuid THEN + RAISE EXCEPTION 'Game Session game_instance_uuid identity is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'game_instances_game_instance_uuid_immutable'; + END IF; + + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_instances_game_instance_uuid_immutable + BEFORE UPDATE OF game_instance_uuid ON game_instances + FOR EACH ROW + EXECUTE FUNCTION enforce_game_instance_uuid_immutable(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V22__authored_world_source_intake.sql b/services/game-session-service/src/main/resources/db/migration/V22__authored_world_source_intake.sql new file mode 100644 index 0000000000..d41a988f98 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V22__authored_world_source_intake.sql @@ -0,0 +1,186 @@ +CREATE TABLE game_session_authored_world_tenant_source_binding ( + target_namespace character varying(63) NOT NULL, + canonical_tenant_id uuid NOT NULL, + tenant_slug character varying(120) NOT NULL, + source_game_row_id bigint NOT NULL, + source_game_tenant_key character varying(36) NOT NULL, + provenance_kind character varying(32) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_authored_world_tenant_source_binding + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_authored_world_tenant_source_slug + UNIQUE (target_namespace, tenant_slug), + CONSTRAINT uq_gs_authored_world_tenant_source_row + UNIQUE (target_namespace, source_game_row_id), + CONSTRAINT uq_gs_authored_world_tenant_source_tuple + UNIQUE ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gs_authored_world_tenant_source_namespace + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT chk_gs_authored_world_tenant_source_tenant_id + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid), + CONSTRAINT chk_gs_authored_world_tenant_source_slug + CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gs_authored_world_tenant_source_row_id + CHECK (source_game_row_id > 0), + CONSTRAINT chk_gs_authored_world_tenant_source_key + CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_authored_world_tenant_source_provenance + CHECK (provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30')) +); + +CREATE TABLE game_session_authored_world_source_intake ( + operation_id uuid NOT NULL, + schema_version integer NOT NULL, + target_namespace character varying(63) NOT NULL, + intake_request_id uuid NOT NULL, + request_digest character varying(71) NOT NULL, + source_schema_version integer NOT NULL, + source_registration_request_id uuid NOT NULL, + source_operation_id uuid NOT NULL, + source_request_digest character varying(71) NOT NULL, + canonical_tenant_id uuid NOT NULL, + tenant_slug character varying(120) NOT NULL, + world_slug character varying(120) NOT NULL, + world_display_name character varying(400) NOT NULL, + source_game_row_id bigint NOT NULL, + source_game_tenant_key character varying(36) NOT NULL, + source_provenance_kind character varying(32) NOT NULL, + source_evidence_digest character varying(71) NOT NULL, + receipt_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_authored_world_source_intake PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_authored_world_source_intake_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_gs_authored_world_source_intake_source_request + UNIQUE (target_namespace, source_registration_request_id), + CONSTRAINT uq_gs_authored_world_source_intake_source_operation + UNIQUE (target_namespace, source_operation_id), + CONSTRAINT uq_gs_authored_world_source_intake_selector + UNIQUE (target_namespace, canonical_tenant_id, world_slug), + CONSTRAINT fk_gs_authored_world_source_tenant_binding + FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + source_provenance_kind + ) + REFERENCES game_session_authored_world_tenant_source_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT chk_gs_authored_world_source_intake_schema + CHECK (schema_version = 1 AND source_schema_version = 1), + CONSTRAINT chk_gs_authored_world_source_intake_ids + CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + ), + CONSTRAINT chk_gs_authored_world_source_intake_namespace + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT chk_gs_authored_world_source_intake_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT chk_gs_authored_world_source_intake_tenant_slug + CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gs_authored_world_source_intake_world_slug + CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gs_authored_world_source_intake_display_name + CHECK ( + char_length(world_display_name) BETWEEN 1 AND 100 + AND world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_authored_world_source_intake_source_row + CHECK (source_game_row_id > 0), + CONSTRAINT chk_gs_authored_world_source_intake_source_key + CHECK ( + char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_authored_world_source_intake_provenance + CHECK (source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30')) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_authored_world_source_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session authored-world source evidence is immutable'; +END; +$$; + +CREATE TRIGGER game_session_authored_world_tenant_binding_immutable +BEFORE UPDATE OR DELETE ON game_session_authored_world_tenant_source_binding +FOR EACH ROW EXECUTE FUNCTION reject_game_session_authored_world_source_mutation(); + +CREATE TRIGGER game_session_authored_world_source_intake_immutable +BEFORE UPDATE OR DELETE ON game_session_authored_world_source_intake +FOR EACH ROW EXECUTE FUNCTION reject_game_session_authored_world_source_mutation(); + +CREATE TRIGGER game_session_authored_world_tenant_binding_no_truncate +BEFORE TRUNCATE ON game_session_authored_world_tenant_source_binding +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_authored_world_source_mutation(); + +CREATE TRIGGER game_session_authored_world_source_intake_no_truncate +BEFORE TRUNCATE ON game_session_authored_world_source_intake +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_authored_world_source_mutation(); + +CREATE FUNCTION require_game_session_authored_world_source_for_tenant_binding() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM game_session_authored_world_source_intake source_intake + WHERE source_intake.target_namespace = NEW.target_namespace + AND source_intake.canonical_tenant_id = NEW.canonical_tenant_id + AND source_intake.tenant_slug = NEW.tenant_slug + AND source_intake.source_game_row_id = NEW.source_game_row_id + AND source_intake.source_game_tenant_key = NEW.source_game_tenant_key + AND source_intake.source_provenance_kind = NEW.provenance_kind + ) THEN + RAISE EXCEPTION 'Game Session tenant source binding cannot commit without a world source'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER game_session_authored_world_tenant_binding_requires_source +AFTER INSERT ON game_session_authored_world_tenant_source_binding +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_authored_world_source_for_tenant_binding(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V23__canonical_realm_catalog.sql b/services/game-session-service/src/main/resources/db/migration/V23__canonical_realm_catalog.sql new file mode 100644 index 0000000000..cfa3f364c6 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V23__canonical_realm_catalog.sql @@ -0,0 +1,488 @@ +-- Preserve all retained numeric keys and namespace bytes. The namespace UUID is the stable +-- primary identity; tenant_id remains nullable/unique for the existing numeric runtime selector. +-- [jooq ignore start] +-- This PostgreSQL-only identity reshape replaces V6's implicit constraint name. H2's jOOQ schema +-- export assigns a different generated name; no generated typed binding consumes these columns. +ALTER TABLE gameplay_tenant_shared_playable_state_namespace + DROP CONSTRAINT gameplay_tenant_shared_playable_state_namespace_pkey; + +ALTER TABLE gameplay_tenant_shared_playable_state_namespace + ALTER COLUMN tenant_id DROP NOT NULL; + +ALTER TABLE gameplay_tenant_shared_playable_state_namespace + ADD CONSTRAINT pk_gameplay_tenant_shared_playable_state_namespace + PRIMARY KEY (playable_state_namespace_id), + ADD CONSTRAINT uq_gameplay_tenant_shared_namespace_legacy_tenant + UNIQUE (tenant_id), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN target_namespace character varying(63), + ADD COLUMN source_intake_operation_id uuid, + ADD COLUMN source_intake_schema_version integer, + ADD COLUMN source_intake_request_id uuid, + ADD COLUMN source_intake_request_digest character varying(71), + ADD COLUMN source_intake_receipt_digest character varying(71), + ADD COLUMN source_schema_version integer, + ADD COLUMN source_registration_request_id uuid, + ADD COLUMN source_operation_id uuid, + ADD COLUMN source_request_digest character varying(71), + ADD COLUMN source_game_row_id bigint, + ADD COLUMN source_game_tenant_key character varying(36), + ADD COLUMN source_provenance_kind character varying(32), + ADD COLUMN source_evidence_digest character varying(71), + ADD CONSTRAINT uq_gameplay_tenant_shared_namespace_canonical_tenant + UNIQUE (canonical_tenant_id), + ADD CONSTRAINT fk_gameplay_tenant_shared_namespace_tenant_source + FOREIGN KEY (target_namespace, canonical_tenant_id) + REFERENCES game_session_authored_world_tenant_source_binding + (target_namespace, canonical_tenant_id), + ADD CONSTRAINT fk_gameplay_tenant_shared_namespace_source_intake + FOREIGN KEY (source_intake_operation_id) + REFERENCES game_session_authored_world_source_intake (operation_id), + ADD CONSTRAINT chk_gameplay_tenant_shared_namespace_non_nil + CHECK ( + canonical_tenant_id IS NULL + OR playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + ), + ADD CONSTRAINT chk_gameplay_tenant_shared_namespace_identity_mode CHECK ( + (tenant_id IS NOT NULL + AND canonical_tenant_id IS NULL + AND target_namespace IS NULL + AND source_intake_operation_id IS NULL + AND source_intake_schema_version IS NULL + AND source_intake_request_id IS NULL + AND source_intake_request_digest IS NULL + AND source_intake_receipt_digest IS NULL + AND source_schema_version IS NULL + AND source_registration_request_id IS NULL + AND source_operation_id IS NULL + AND source_request_digest IS NULL + AND source_game_row_id IS NULL + AND source_game_tenant_key IS NULL + AND source_provenance_kind IS NULL + AND source_evidence_digest IS NULL) + OR (tenant_id IS NULL + AND canonical_tenant_id IS NOT NULL + AND target_namespace IS NOT NULL + AND source_intake_operation_id IS NOT NULL + AND source_intake_schema_version IS NOT NULL + AND source_intake_schema_version = 1 + AND source_intake_request_id IS NOT NULL + AND source_intake_request_digest IS NOT NULL + AND source_intake_receipt_digest IS NOT NULL + AND source_schema_version IS NOT NULL + AND source_schema_version = 1 + AND source_registration_request_id IS NOT NULL + AND source_operation_id IS NOT NULL + AND source_request_digest IS NOT NULL + AND source_game_row_id IS NOT NULL + AND source_game_tenant_key IS NOT NULL + AND source_provenance_kind IS NOT NULL + AND source_provenance_kind = 'NEW_GAME_ROW' + AND source_evidence_digest IS NOT NULL) + ), + ADD CONSTRAINT chk_gameplay_tenant_shared_namespace_fresh_source CHECK ( + canonical_tenant_id IS NULL + OR (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_game_row_id > 0 + AND char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$') + ); +-- [jooq ignore stop] + +CREATE TABLE game_session_canonical_realm_catalog ( + target_namespace character varying(63) NOT NULL, + canonical_tenant_id uuid NOT NULL, + tenant_slug character varying(120) NOT NULL, + world_slug character varying(120) NOT NULL, + realm_id uuid NOT NULL, + realm_slug character varying(120) NOT NULL, + realm_display_name character varying(200) NOT NULL, + visible boolean NOT NULL, + public_production boolean NOT NULL, + state_scope character varying(16) NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_creation_policy character varying(64) NOT NULL, + catalog_revision bigint NOT NULL, + creation_request_id uuid NOT NULL, + request_digest character varying(71) NOT NULL, + receipt_digest character varying(71) NOT NULL, + source_intake_operation_id uuid NOT NULL, + source_intake_schema_version integer NOT NULL, + source_intake_request_id uuid NOT NULL, + source_intake_request_digest character varying(71) NOT NULL, + source_intake_receipt_digest character varying(71) NOT NULL, + source_schema_version integer NOT NULL, + source_registration_request_id uuid NOT NULL, + source_operation_id uuid NOT NULL, + source_request_digest character varying(71) NOT NULL, + source_world_display_name character varying(400) NOT NULL, + source_game_row_id bigint NOT NULL, + source_game_tenant_key character varying(36) NOT NULL, + source_provenance_kind character varying(32) NOT NULL, + source_evidence_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_realm_catalog + PRIMARY KEY (target_namespace, realm_id), + CONSTRAINT uq_gs_canonical_realm_catalog_realm_id + UNIQUE (realm_id), + CONSTRAINT uq_gs_canonical_realm_catalog_request + UNIQUE (target_namespace, creation_request_id), + CONSTRAINT uq_gs_canonical_realm_catalog_tenant_slug + UNIQUE (target_namespace, canonical_tenant_id, realm_slug), + CONSTRAINT fk_gs_canonical_realm_catalog_tenant_source + FOREIGN KEY ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + source_provenance_kind + ) + REFERENCES game_session_authored_world_tenant_source_binding ( + target_namespace, + canonical_tenant_id, + tenant_slug, + source_game_row_id, + source_game_tenant_key, + provenance_kind + ), + CONSTRAINT fk_gs_canonical_realm_catalog_source_intake + FOREIGN KEY (source_intake_operation_id) + REFERENCES game_session_authored_world_source_intake (operation_id), + CONSTRAINT chk_gs_canonical_realm_catalog_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_ids CHECK ( + canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND creation_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + ), + CONSTRAINT chk_gs_canonical_realm_catalog_selector CHECK ( + octet_length(tenant_slug) BETWEEN 1 AND 120 + AND tenant_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + AND char_length(realm_slug) BETWEEN 1 AND 120 + AND octet_length(realm_slug) BETWEEN 1 AND 120 + AND realm_slug !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_public_initial CHECK ( + visible AND public_production + ), + CONSTRAINT chk_gs_canonical_realm_catalog_scope CHECK ( + state_scope IN ('SHARED', 'ISOLATED') + ), + CONSTRAINT chk_gs_canonical_realm_catalog_revision CHECK (catalog_revision = 1), + CONSTRAINT chk_gs_canonical_realm_catalog_policy CHECK ( + char_length(character_creation_policy) BETWEEN 1 AND 64 + AND octet_length(character_creation_policy) <= 256 + AND character_creation_policy !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_names CHECK ( + char_length(realm_display_name) BETWEEN 1 AND 100 + AND octet_length(realm_display_name) <= 400 + AND realm_display_name !~ '^[[:space:]]*$' + AND char_length(source_world_display_name) BETWEEN 1 AND 100 + AND octet_length(source_world_display_name) <= 400 + AND source_world_display_name !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_versions CHECK ( + source_intake_schema_version = 1 + AND source_schema_version = 1 + ), + CONSTRAINT chk_gs_canonical_realm_catalog_source_key CHECK ( + source_game_row_id > 0 + AND char_length(source_game_tenant_key) BETWEEN 1 AND 36 + AND source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_provenance CHECK ( + source_provenance_kind = 'NEW_GAME_ROW' + ), + CONSTRAINT chk_gs_canonical_realm_catalog_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE UNIQUE INDEX uq_gs_canonical_realm_catalog_public_tenant + ON game_session_canonical_realm_catalog (target_namespace, canonical_tenant_id) + WHERE public_production; + +CREATE UNIQUE INDEX uq_gs_canonical_realm_catalog_isolated_namespace + ON game_session_canonical_realm_catalog (playable_state_namespace_id) + WHERE state_scope = 'ISOLATED'; + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_canonical_realm_catalog_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session canonical realm catalog evidence is immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE FUNCTION protect_fresh_shared_namespace_identity() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.canonical_tenant_id IS NOT NULL OR NEW.canonical_tenant_id IS NOT NULL THEN + RAISE EXCEPTION 'Game Session fresh shared namespace identity is immutable' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_fresh_shared_namespace_immutable +BEFORE UPDATE OR DELETE ON gameplay_tenant_shared_playable_state_namespace +FOR EACH ROW EXECUTE FUNCTION protect_fresh_shared_namespace_identity(); + +CREATE TRIGGER game_session_canonical_realm_catalog_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_realm_catalog +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_realm_catalog_mutation(); + +CREATE TRIGGER game_session_canonical_realm_catalog_no_truncate +BEFORE TRUNCATE ON game_session_canonical_realm_catalog +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_realm_catalog_mutation(); + +CREATE FUNCTION require_game_session_canonical_realm_source_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended(NEW.target_namespace || ':' || NEW.canonical_tenant_id::text, 1)); + IF NOT EXISTS ( + SELECT 1 + FROM game_session_authored_world_source_intake source_intake + WHERE source_intake.operation_id = NEW.source_intake_operation_id + AND source_intake.schema_version = NEW.source_intake_schema_version + AND source_intake.target_namespace = NEW.target_namespace + AND source_intake.intake_request_id = NEW.source_intake_request_id + AND source_intake.request_digest = NEW.source_intake_request_digest + AND source_intake.source_schema_version = NEW.source_schema_version + AND source_intake.source_registration_request_id = NEW.source_registration_request_id + AND source_intake.source_operation_id = NEW.source_operation_id + AND source_intake.source_request_digest = NEW.source_request_digest + AND source_intake.canonical_tenant_id = NEW.canonical_tenant_id + AND source_intake.tenant_slug = NEW.tenant_slug + AND source_intake.world_slug = NEW.world_slug + AND source_intake.world_display_name = NEW.source_world_display_name + AND source_intake.source_game_row_id = NEW.source_game_row_id + AND source_intake.source_game_tenant_key = NEW.source_game_tenant_key + AND source_intake.source_provenance_kind = NEW.source_provenance_kind + AND source_intake.source_evidence_digest = NEW.source_evidence_digest + AND source_intake.receipt_digest = NEW.source_intake_receipt_digest + ) THEN + RAISE EXCEPTION 'Canonical realm catalog requires exact committed authored-world intake evidence' + USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE retained.target_namespace = NEW.target_namespace + AND retained.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Canonical realm catalog cannot replace retained numeric tenant namespace authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_realm_catalog_requires_source +BEFORE INSERT ON game_session_canonical_realm_catalog +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_realm_source_evidence(); + +CREATE FUNCTION require_game_session_canonical_namespace_allocation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended(NEW.playable_state_namespace_id::text, 0)); + IF NEW.state_scope = 'SHARED' THEN + IF NOT EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.tenant_id IS NULL + AND shared_namespace.canonical_tenant_id = NEW.canonical_tenant_id + AND shared_namespace.target_namespace = NEW.target_namespace + AND shared_namespace.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'SHARED canonical realm requires its exact tenant namespace allocation' + USING ERRCODE = '23514'; + END IF; + ELSIF EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'ISOLATED canonical realm namespace conflicts with a tenant SHARED namespace' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_catalog_requires_namespace +BEFORE INSERT ON game_session_canonical_realm_catalog +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_namespace_allocation(); + +CREATE FUNCTION require_game_session_shared_namespace_source() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended(NEW.playable_state_namespace_id::text, 0)); + IF NEW.canonical_tenant_id IS NULL AND EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.state_scope = 'ISOLATED' + AND catalog.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'Legacy tenant SHARED namespace conflicts with a canonical ISOLATED realm namespace' + USING ERRCODE = '23514'; + END IF; + IF NEW.canonical_tenant_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 + FROM game_session_authored_world_source_intake source_intake + WHERE source_intake.operation_id = NEW.source_intake_operation_id + AND source_intake.schema_version = NEW.source_intake_schema_version + AND source_intake.target_namespace = NEW.target_namespace + AND source_intake.intake_request_id = NEW.source_intake_request_id + AND source_intake.request_digest = NEW.source_intake_request_digest + AND source_intake.source_schema_version = NEW.source_schema_version + AND source_intake.source_registration_request_id = NEW.source_registration_request_id + AND source_intake.source_operation_id = NEW.source_operation_id + AND source_intake.source_request_digest = NEW.source_request_digest + AND source_intake.canonical_tenant_id = NEW.canonical_tenant_id + AND source_intake.source_game_row_id = NEW.source_game_row_id + AND source_intake.source_game_tenant_key = NEW.source_game_tenant_key + AND source_intake.source_provenance_kind = NEW.source_provenance_kind + AND source_intake.source_evidence_digest = NEW.source_evidence_digest + AND source_intake.receipt_digest = NEW.source_intake_receipt_digest + ) THEN + RAISE EXCEPTION 'Fresh SHARED namespace requires exact committed authored-world source receipt' + USING ERRCODE = '23514'; + END IF; + IF NEW.canonical_tenant_id IS NOT NULL AND EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE retained.target_namespace = NEW.target_namespace + AND retained.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Fresh SHARED namespace cannot replace retained numeric namespace authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_fresh_shared_namespace_requires_source +BEFORE INSERT OR UPDATE ON gameplay_tenant_shared_playable_state_namespace +FOR EACH ROW EXECUTE FUNCTION require_game_session_shared_namespace_source(); + +CREATE FUNCTION require_game_session_shared_namespace_catalog_reference() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.canonical_tenant_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.state_scope = 'SHARED' + AND catalog.target_namespace = NEW.target_namespace + AND catalog.canonical_tenant_id = NEW.canonical_tenant_id + AND catalog.playable_state_namespace_id = NEW.playable_state_namespace_id + ) THEN + RAISE EXCEPTION 'Fresh shared namespace cannot commit without its canonical realm catalog result' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER game_session_shared_namespace_requires_catalog +AFTER INSERT ON gameplay_tenant_shared_playable_state_namespace +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_shared_namespace_catalog_reference(); + +CREATE FUNCTION protect_fresh_shared_namespace_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace + WHERE canonical_tenant_id IS NOT NULL + ) THEN + RAISE EXCEPTION 'Game Session fresh shared namespace identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER game_session_fresh_shared_namespace_no_truncate +BEFORE TRUNCATE ON gameplay_tenant_shared_playable_state_namespace +FOR EACH STATEMENT EXECUTE FUNCTION protect_fresh_shared_namespace_truncate(); + +-- A retained association can only be recorded for a tenant that has not already acquired fresh +-- canonical realm/SHARED namespace authority. Existing association capture takes SHARE locks on +-- the namespace family; this tenant-scoped advisory fence also serializes any owner-local insert +-- with the catalog's source-evidence trigger. Existing rows and exact retries are unaffected. +CREATE FUNCTION reject_retained_association_for_fresh_canonical_tenant() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended(NEW.target_namespace || ':' || NEW.canonical_tenant_id::text, 1)); + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.target_namespace = NEW.target_namespace + AND catalog.canonical_tenant_id = NEW.canonical_tenant_id + ) OR EXISTS ( + SELECT 1 + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.target_namespace = NEW.target_namespace + AND shared_namespace.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Retained numeric association cannot replace fresh canonical tenant namespace authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_retained_association_rejects_fresh_tenant +BEFORE INSERT ON game_session_retained_tenant_association +FOR EACH ROW EXECUTE FUNCTION reject_retained_association_for_fresh_canonical_tenant(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V24__canonical_launch_preparation.sql b/services/game-session-service/src/main/resources/db/migration/V24__canonical_launch_preparation.sql new file mode 100644 index 0000000000..72545e354f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V24__canonical_launch_preparation.sql @@ -0,0 +1,88 @@ +-- Evidence-only canonical launch preparation. It creates no runtime instance or admission state. +CREATE TABLE game_session_canonical_launch_preparation ( + target_namespace character varying(63) NOT NULL, + control_plane_request_id character varying(128) NOT NULL, + operation_id uuid NOT NULL, + acting_account_uuid uuid NOT NULL, + canonical_tenant_id uuid NOT NULL, + realm_id uuid NOT NULL, + catalog_creation_request_id uuid NOT NULL, + catalog_revision bigint NOT NULL, + source_intake_operation_id uuid NOT NULL, + source_intake_request_id uuid NOT NULL, + source_registration_request_id uuid NOT NULL, + source_operation_id uuid NOT NULL, + catalog_request_digest character varying(71) NOT NULL, + catalog_receipt_digest character varying(71) NOT NULL, + source_intake_request_digest character varying(71) NOT NULL, + source_intake_receipt_digest character varying(71) NOT NULL, + source_evidence_digest character varying(71) NOT NULL, + descriptor_request_digest character varying(71) NOT NULL, + descriptor_result_digest character varying(71) NOT NULL, + request_digest character varying(71) NOT NULL, + receipt_digest character varying(71) NOT NULL, + request_evidence_json jsonb NOT NULL, + catalog_evidence_json jsonb NOT NULL, + source_intake_evidence_json jsonb NOT NULL, + launch_descriptor_evidence_json jsonb NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_launch_preparation + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_canonical_launch_preparation_operation UNIQUE (operation_id), + CONSTRAINT fk_gs_canonical_launch_preparation_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT fk_gs_canonical_launch_preparation_source_intake + FOREIGN KEY (source_intake_operation_id) + REFERENCES game_session_authored_world_source_intake (operation_id), + CONSTRAINT chk_gs_canonical_launch_preparation_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND octet_length(control_plane_request_id) BETWEEN 1 AND 128 + AND btrim(control_plane_request_id) <> '' + AND operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND acting_account_uuid <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_creation_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_revision > 0 + AND source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_registration_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid), + CONSTRAINT chk_gs_canonical_launch_preparation_digests CHECK ( + catalog_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND catalog_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_intake_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND request_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_canonical_launch_preparation_json CHECK ( + jsonb_typeof(request_evidence_json) = 'object' + AND jsonb_typeof(catalog_evidence_json) = 'object' + AND jsonb_typeof(source_intake_evidence_json) = 'object' + AND jsonb_typeof(launch_descriptor_evidence_json) = 'object') +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_canonical_launch_preparation_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Canonical launch preparation evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'gs_canonical_launch_preparation_immutable'; +END; +$$; + +CREATE TRIGGER game_session_canonical_launch_preparation_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_launch_preparation +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_launch_preparation_mutation(); + +CREATE TRIGGER game_session_canonical_launch_preparation_no_truncate +BEFORE TRUNCATE ON game_session_canonical_launch_preparation +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_launch_preparation_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V25__fresh_tenant_association.sql b/services/game-session-service/src/main/resources/db/migration/V25__fresh_tenant_association.sql new file mode 100644 index 0000000000..e20ee53a96 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V25__fresh_tenant_association.sql @@ -0,0 +1,325 @@ +CREATE TABLE game_session_tenant_scope_reservation ( + game_session_tenant_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + reservation_kind VARCHAR(32) NOT NULL, + reserved_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_tenant_scope_reservation_kind + UNIQUE (game_session_tenant_id, reservation_kind), + CONSTRAINT chk_gs_tenant_scope_reservation_positive + CHECK (game_session_tenant_id > 0), + CONSTRAINT chk_gs_tenant_scope_reservation_kind + CHECK (reservation_kind IN ('LEGACY_OCCUPIED', 'FRESH_SOURCE_BOUND')) +); + +CREATE TABLE game_session_tenant_canonical_claim ( + target_namespace VARCHAR(63) NOT NULL, + canonical_tenant_id UUID NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + association_kind VARCHAR(32) NOT NULL, + reservation_kind VARCHAR(32) NOT NULL, + association_operation_id UUID NOT NULL, + association_request_id UUID NOT NULL, + claimed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_tenant_canonical_claim + PRIMARY KEY (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_tenant_canonical_claim_private_key + UNIQUE (target_namespace, legacy_game_session_tenant_id), + CONSTRAINT uq_gs_tenant_canonical_claim_operation + UNIQUE (association_operation_id), + CONSTRAINT uq_gs_tenant_canonical_claim_request + UNIQUE (target_namespace, association_request_id), + CONSTRAINT uq_gs_tenant_canonical_claim_association + UNIQUE (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind), + CONSTRAINT fk_gs_tenant_canonical_claim_reservation + FOREIGN KEY (legacy_game_session_tenant_id, reservation_kind) + REFERENCES game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind), + CONSTRAINT chk_gs_tenant_canonical_claim_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + ), + CONSTRAINT chk_gs_tenant_canonical_claim_uuid + CHECK (canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT chk_gs_tenant_canonical_claim_ids CHECK ( + legacy_game_session_tenant_id > 0 + AND association_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_tenant_canonical_claim_kind CHECK ( + (association_kind = 'RETAINED_V8_1' AND reservation_kind = 'LEGACY_OCCUPIED') + OR + (association_kind = 'FRESH_SOURCE_BOUND' AND reservation_kind = 'FRESH_SOURCE_BOUND') + ) +); + +CREATE TABLE game_session_fresh_tenant_association ( + association_operation_id UUID PRIMARY KEY, + target_namespace VARCHAR(63) NOT NULL, + association_request_id UUID NOT NULL, + source_schema_version INTEGER NOT NULL, + source_target_namespace VARCHAR(63) NOT NULL, + source_request_id UUID NOT NULL, + source_canonical_tenant_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + legacy_game_session_tenant_id BIGINT NOT NULL, + source_game_row_id BIGINT NOT NULL, + source_game_tenant_key VARCHAR(72) NOT NULL, + provenance_kind VARCHAR(32) NOT NULL, + association_kind VARCHAR(32) NOT NULL DEFAULT 'FRESH_SOURCE_BOUND', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_fresh_tenant_association_request + UNIQUE (target_namespace, association_request_id), + CONSTRAINT uq_gs_fresh_tenant_association_canonical + UNIQUE (target_namespace, canonical_tenant_id), + CONSTRAINT uq_gs_fresh_tenant_association_private_key + UNIQUE (legacy_game_session_tenant_id), + CONSTRAINT fk_gs_fresh_tenant_association_reservation + FOREIGN KEY (legacy_game_session_tenant_id, association_kind) + REFERENCES game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind), + CONSTRAINT fk_gs_fresh_tenant_association_claim + FOREIGN KEY (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind) + REFERENCES game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind), + CONSTRAINT chk_gs_fresh_tenant_association_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND source_target_namespace = target_namespace + AND source_schema_version = 1 + AND source_request_id = association_request_id + AND source_canonical_tenant_id = canonical_tenant_id + AND association_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_fresh_tenant_association_source CHECK ( + legacy_game_session_tenant_id > 0 + AND source_game_row_id > 0 + AND char_length(source_game_tenant_key) BETWEEN 1 AND 72 + AND source_game_tenant_key !~ '^[[:space:]]*$' + AND provenance_kind = 'NEW_GAME_ROW' + AND association_kind = 'FRESH_SOURCE_BOUND' + ) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_game_session_tenant_owner_evidence_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant owner evidence is immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER game_session_tenant_scope_reservation_immutable + BEFORE UPDATE OR DELETE ON game_session_tenant_scope_reservation + FOR EACH ROW EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_tenant_scope_reservation_no_truncate + BEFORE TRUNCATE ON game_session_tenant_scope_reservation + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_tenant_canonical_claim_immutable + BEFORE UPDATE OR DELETE ON game_session_tenant_canonical_claim + FOR EACH ROW EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_tenant_canonical_claim_no_truncate + BEFORE TRUNCATE ON game_session_tenant_canonical_claim + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_fresh_tenant_association_immutable + BEFORE UPDATE OR DELETE ON game_session_fresh_tenant_association + FOR EACH ROW EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); +CREATE TRIGGER game_session_fresh_tenant_association_no_truncate + BEFORE TRUNCATE ON game_session_fresh_tenant_association + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_tenant_owner_evidence_mutation(); + +CREATE FUNCTION reserve_game_session_tenant_scope() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS NOT DISTINCT FROM OLD.tenant_id THEN + RETURN NEW; + END IF; + IF NEW.tenant_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.tenant_id <= 0 THEN + RAISE EXCEPTION 'Game Session tenant scope must be positive' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_tenant_scope_reservation_positive'; + END IF; + + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + VALUES (NEW.tenant_id, 'LEGACY_OCCUPIED') + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + SELECT reservation_kind + INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.tenant_id + FOR KEY SHARE; + IF current_kind IS DISTINCT FROM 'LEGACY_OCCUPIED' THEN + RAISE EXCEPTION 'Numeric-only tenant scope cannot use a fresh source-bound key' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_numeric_fresh_tenant_scope_denied'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION claim_retained_game_session_tenant_identity() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); +BEGIN + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + VALUES (NEW.legacy_game_session_tenant_id, 'LEGACY_OCCUPIED') + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + SELECT reservation_kind + INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.legacy_game_session_tenant_id + FOR KEY SHARE; + IF current_kind IS DISTINCT FROM 'LEGACY_OCCUPIED' THEN + RAISE EXCEPTION 'Retained tenant mapping cannot claim a fresh source-bound key' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_retained_fresh_tenant_scope_denied'; + END IF; + + INSERT INTO game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_kind, reservation_kind, association_operation_id, association_request_id) + VALUES + (NEW.target_namespace, NEW.canonical_tenant_id, NEW.legacy_game_session_tenant_id, + 'RETAINED_V8_1', 'LEGACY_OCCUPIED', NEW.operation_id, NEW.association_request_id) + ON CONFLICT DO NOTHING; + + IF NOT EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND legacy_game_session_tenant_id = NEW.legacy_game_session_tenant_id + AND association_kind = 'RETAINED_V8_1' + AND reservation_kind = 'LEGACY_OCCUPIED' + AND association_operation_id = NEW.operation_id + AND association_request_id = NEW.association_request_id + ) THEN + RAISE EXCEPTION 'Retained tenant mapping conflicts with a Game Session owner claim' + USING ERRCODE = '23505', CONSTRAINT = 'pk_gs_tenant_canonical_claim'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_retained_association_claim + BEFORE INSERT ON game_session_retained_tenant_association + FOR EACH ROW EXECUTE FUNCTION claim_retained_game_session_tenant_identity(); + +DO $$ +DECLARE + scope_table RECORD; + scope_count INTEGER := 0; + max_reserved_tenant BIGINT; + identity_sequence TEXT; +BEGIN + FOR scope_table IN + SELECT column_info.table_name + FROM information_schema.columns column_info + JOIN information_schema.tables table_info + ON table_info.table_schema = column_info.table_schema + AND table_info.table_name = column_info.table_name + WHERE column_info.table_schema = current_schema() + AND column_info.column_name = 'tenant_id' + AND table_info.table_type = 'BASE TABLE' + GROUP BY column_info.table_name + ORDER BY column_info.table_name + LOOP + scope_count := scope_count + 1; + EXECUTE format( + 'CREATE TRIGGER reserve_game_session_tenant_scope ' + || 'BEFORE INSERT OR UPDATE ON %I ' + || 'FOR EACH ROW EXECUTE FUNCTION reserve_game_session_tenant_scope()', + scope_table.table_name); + EXECUTE format( + 'INSERT INTO game_session_tenant_scope_reservation ' + || '(game_session_tenant_id, reservation_kind) ' + || 'SELECT DISTINCT tenant_id, ''LEGACY_OCCUPIED'' FROM %I ' + || 'WHERE tenant_id IS NOT NULL ' + || 'ON CONFLICT (game_session_tenant_id) DO NOTHING', + scope_table.table_name); + EXECUTE format( + 'ALTER TABLE %I ADD CONSTRAINT fk_tenant_scope_reservation ' + || 'FOREIGN KEY (tenant_id) REFERENCES game_session_tenant_scope_reservation ' + || '(game_session_tenant_id) NOT VALID', + scope_table.table_name); + EXECUTE format( + 'ALTER TABLE %I VALIDATE CONSTRAINT fk_tenant_scope_reservation', + scope_table.table_name); + END LOOP; + + IF scope_count = 0 THEN + RAISE EXCEPTION 'No Game Session tenant scope tables were found'; + END IF; + + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + SELECT DISTINCT legacy_game_session_tenant_id, 'LEGACY_OCCUPIED' + FROM game_session_retained_tenant_association + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + ALTER TABLE game_session_retained_tenant_association + ADD CONSTRAINT fk_gs_retained_tenant_reservation + FOREIGN KEY (legacy_game_session_tenant_id) + REFERENCES game_session_tenant_scope_reservation (game_session_tenant_id) NOT VALID; + ALTER TABLE game_session_retained_tenant_association + VALIDATE CONSTRAINT fk_gs_retained_tenant_reservation; + + INSERT INTO game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_kind, reservation_kind, association_operation_id, association_request_id) + SELECT target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + 'RETAINED_V8_1', 'LEGACY_OCCUPIED', operation_id, association_request_id + FROM game_session_retained_tenant_association + ON CONFLICT DO NOTHING; + + IF EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE NOT EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim claim + WHERE claim.target_namespace = retained.target_namespace + AND claim.canonical_tenant_id = retained.canonical_tenant_id + AND claim.legacy_game_session_tenant_id = retained.legacy_game_session_tenant_id + AND claim.association_kind = 'RETAINED_V8_1' + AND claim.reservation_kind = 'LEGACY_OCCUPIED' + AND claim.association_operation_id = retained.operation_id + AND claim.association_request_id = retained.association_request_id + ) + ) THEN + RAISE EXCEPTION 'Retained Game Session identity could not be claimed exactly'; + END IF; + + SELECT max(game_session_tenant_id) + INTO max_reserved_tenant + FROM game_session_tenant_scope_reservation; + identity_sequence := pg_get_serial_sequence( + 'game_session_tenant_scope_reservation', 'game_session_tenant_id'); + IF identity_sequence IS NULL THEN + RAISE EXCEPTION 'Game Session tenant reservation identity sequence is unavailable'; + ELSIF max_reserved_tenant IS NULL THEN + PERFORM setval(identity_sequence, 1, FALSE); + ELSE + PERFORM setval(identity_sequence, max_reserved_tenant, TRUE); + END IF; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V26__canonical_instance_launch_association.sql b/services/game-session-service/src/main/resources/db/migration/V26__canonical_instance_launch_association.sql new file mode 100644 index 0000000000..d93752b851 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V26__canonical_instance_launch_association.sql @@ -0,0 +1,407 @@ +-- A launch association is durable Game Session owner evidence, not World lifecycle authority. +-- Historical instances are intentionally neither inferred nor backfilled. +ALTER TABLE game_session_fresh_tenant_association + ADD CONSTRAINT uq_gs_fresh_tenant_association_launch_identity + UNIQUE (target_namespace, association_operation_id, association_request_id, + source_schema_version, source_target_namespace, source_request_id, + source_canonical_tenant_id, canonical_tenant_id, + legacy_game_session_tenant_id, source_game_row_id, + source_game_tenant_key, provenance_kind, association_kind); + +ALTER TABLE game_instances + ADD CONSTRAINT uq_game_instances_tenant_id_id UNIQUE (tenant_id, id); + +CREATE TABLE game_session_canonical_instance_launch ( + target_namespace VARCHAR(63) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + game_session_tenant_id BIGINT NOT NULL, + canonical_tenant_id UUID NOT NULL, + tenant_association_operation_id UUID NOT NULL, + tenant_association_request_id UUID NOT NULL, + tenant_source_schema_version INTEGER NOT NULL, + tenant_source_target_namespace VARCHAR(63) NOT NULL, + tenant_source_request_id UUID NOT NULL, + tenant_source_canonical_tenant_id UUID NOT NULL, + tenant_source_game_row_id BIGINT NOT NULL, + tenant_source_game_tenant_key VARCHAR(72) NOT NULL, + tenant_source_provenance_kind VARCHAR(32) NOT NULL, + tenant_association_kind VARCHAR(32) NOT NULL, + game_instance_id BIGINT NOT NULL, + game_instance_uuid UUID NOT NULL, + canonical_realm_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL, + public_production BOOLEAN NOT NULL, + captured_starting_row_version BIGINT NOT NULL, + game_template_id BIGINT NOT NULL, + launch_descriptor_id VARCHAR(128) NOT NULL, + version_id BIGINT NOT NULL, + release_bundle_id BIGINT NOT NULL, + generation_config_revision VARCHAR(128) NOT NULL, + version_state_epoch BIGINT NOT NULL, + complete_launch_binding_evidence JSONB NOT NULL, + captured_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_game_session_canonical_instance_launch + PRIMARY KEY (target_namespace, control_plane_request_id), + CONSTRAINT uq_gs_canonical_instance_launch_uuid + UNIQUE (target_namespace, game_instance_uuid), + CONSTRAINT uq_gs_canonical_instance_launch_runtime + UNIQUE (game_session_tenant_id, game_instance_id), + CONSTRAINT fk_gs_canonical_instance_launch_fresh_identity + FOREIGN KEY (target_namespace, tenant_association_operation_id, + tenant_association_request_id, tenant_source_schema_version, + tenant_source_target_namespace, tenant_source_request_id, + tenant_source_canonical_tenant_id, canonical_tenant_id, + game_session_tenant_id, tenant_source_game_row_id, + tenant_source_game_tenant_key, tenant_source_provenance_kind, + tenant_association_kind) + REFERENCES game_session_fresh_tenant_association + (target_namespace, association_operation_id, association_request_id, + source_schema_version, source_target_namespace, source_request_id, + source_canonical_tenant_id, canonical_tenant_id, + legacy_game_session_tenant_id, source_game_row_id, + source_game_tenant_key, provenance_kind, association_kind), + CONSTRAINT fk_gs_canonical_instance_launch_claim + FOREIGN KEY (target_namespace, canonical_tenant_id, game_session_tenant_id, + tenant_association_operation_id, tenant_association_kind) + REFERENCES game_session_tenant_canonical_claim + (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, + association_operation_id, association_kind), + CONSTRAINT fk_gs_canonical_instance_launch_runtime + FOREIGN KEY (game_session_tenant_id, game_instance_id) + REFERENCES game_instances (tenant_id, id), + CONSTRAINT fk_gs_canonical_instance_launch_realm + FOREIGN KEY (target_namespace, canonical_realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT chk_gs_canonical_instance_launch_namespace CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND tenant_source_target_namespace = target_namespace + ), + CONSTRAINT chk_gs_canonical_instance_launch_request CHECK ( + char_length(control_plane_request_id) BETWEEN 1 AND 128 + AND control_plane_request_id !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_instance_launch_source_identity CHECK ( + tenant_association_kind = 'FRESH_SOURCE_BOUND' + AND tenant_source_schema_version = 1 + AND tenant_association_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_association_request_id = tenant_source_request_id + AND canonical_tenant_id = tenant_source_canonical_tenant_id + AND tenant_source_provenance_kind = 'NEW_GAME_ROW' + AND tenant_source_game_row_id > 0 + AND char_length(tenant_source_game_tenant_key) BETWEEN 1 AND 72 + AND tenant_source_game_tenant_key !~ '^[[:space:]]*$' + ), + CONSTRAINT chk_gs_canonical_instance_launch_ids CHECK ( + game_session_tenant_id > 0 + AND game_instance_id > 0 + AND game_template_id > 0 + AND version_id > 0 + AND release_bundle_id > 0 + AND version_state_epoch > 0 + AND captured_starting_row_version >= 0 + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND tenant_association_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND game_instance_uuid <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_realm_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT chk_gs_canonical_instance_launch_world CHECK ( + octet_length(world_slug) BETWEEN 1 AND 120 + AND world_slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' + ), + CONSTRAINT chk_gs_canonical_instance_launch_owner_scope CHECK ( + playable_state_scope = 'SHARED' AND public_production + ), + CONSTRAINT chk_gs_canonical_instance_launch_binding CHECK ( + char_length(launch_descriptor_id) BETWEEN 1 AND 128 + AND launch_descriptor_id !~ '^[[:space:]]*$' + AND char_length(generation_config_revision) BETWEEN 1 AND 128 + AND generation_config_revision !~ '^[[:space:]]*$' + AND jsonb_typeof(complete_launch_binding_evidence) = 'object' + AND jsonb_typeof(complete_launch_binding_evidence -> 'descriptor') = 'object' + AND jsonb_typeof(complete_launch_binding_evidence -> 'releaseAttestation') = 'object' + ) +); + +-- A fresh tenant key can own a GameInstance, but no other numeric-only tenant writer may claim it. +-- [jooq ignore start] +CREATE FUNCTION require_starting_game_instance_for_launch_association() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; + descriptor JSONB; +BEGIN + SELECT * INTO runtime_row + FROM game_instances + WHERE tenant_id = NEW.game_session_tenant_id + AND id = NEW.game_instance_id + FOR UPDATE; + IF NOT FOUND OR runtime_row.status IS DISTINCT FROM 'STARTING' + OR runtime_row.row_version IS DISTINCT FROM NEW.captured_starting_row_version + OR runtime_row.game_instance_uuid IS DISTINCT FROM NEW.game_instance_uuid + OR runtime_row.run_owned_start_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR runtime_row.run_owned_start_published_release_bundle_ref IS DISTINCT FROM + (NEW.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef') THEN + RAISE EXCEPTION 'Launch association requires the exact persisted run-owned STARTING row' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_launch_association_starting_row_required'; + END IF; + + descriptor := NEW.complete_launch_binding_evidence -> 'descriptor'; + IF descriptor ->> 'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR descriptor ->> 'controlPlaneRequestId' IS DISTINCT FROM NEW.control_plane_request_id + OR descriptor ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::text + OR descriptor ->> 'worldSlug' IS DISTINCT FROM NEW.world_slug + OR descriptor ->> 'gameTemplateId' IS DISTINCT FROM NEW.game_template_id::text + OR descriptor ->> 'launchDescriptorId' IS DISTINCT FROM NEW.launch_descriptor_id + OR descriptor ->> 'versionId' IS DISTINCT FROM NEW.version_id::text + OR descriptor ->> 'releaseBundleId' IS DISTINCT FROM NEW.release_bundle_id::text + OR descriptor ->> 'generationConfigRevision' IS DISTINCT FROM NEW.generation_config_revision + OR descriptor ->> 'versionStateEpoch' IS DISTINCT FROM NEW.version_state_epoch::text + OR runtime_row.game_template_id IS DISTINCT FROM NEW.game_template_id + OR runtime_row.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR runtime_row.version_id IS DISTINCT FROM NEW.version_id + OR runtime_row.release_bundle_id IS DISTINCT FROM NEW.release_bundle_id + OR runtime_row.generation_config_revision IS DISTINCT FROM NEW.generation_config_revision + OR runtime_row.version_state_epoch IS DISTINCT FROM NEW.version_state_epoch THEN + RAISE EXCEPTION 'Launch association differs from its complete descriptor binding' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_launch_association_descriptor_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_instance_launch_starting_owner + BEFORE INSERT ON game_session_canonical_instance_launch + FOR EACH ROW EXECUTE FUNCTION require_starting_game_instance_for_launch_association(); + +CREATE OR REPLACE FUNCTION reserve_game_session_tenant_scope() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS NOT DISTINCT FROM OLD.tenant_id THEN + RETURN NEW; + END IF; + IF NEW.tenant_id IS NULL THEN + RETURN NEW; + END IF; + IF NEW.tenant_id <= 0 THEN + RAISE EXCEPTION 'Game Session tenant scope must be positive' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_tenant_scope_reservation_positive'; + END IF; + + INSERT INTO game_session_tenant_scope_reservation + (game_session_tenant_id, reservation_kind) + VALUES (NEW.tenant_id, 'LEGACY_OCCUPIED') + ON CONFLICT (game_session_tenant_id) DO NOTHING; + + SELECT reservation_kind INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.tenant_id + FOR KEY SHARE; + + IF current_kind = 'FRESH_SOURCE_BOUND' AND TG_TABLE_NAME = 'game_instances' + AND EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim claim + JOIN game_session_fresh_tenant_association association + ON association.target_namespace = claim.target_namespace + AND association.canonical_tenant_id = claim.canonical_tenant_id + AND association.legacy_game_session_tenant_id = claim.legacy_game_session_tenant_id + AND association.association_operation_id = claim.association_operation_id + AND association.association_kind = claim.association_kind + WHERE claim.legacy_game_session_tenant_id = NEW.tenant_id + AND claim.association_kind = 'FRESH_SOURCE_BOUND' + AND association.association_kind = 'FRESH_SOURCE_BOUND' + ) THEN + RETURN NEW; + END IF; + + IF current_kind IS DISTINCT FROM 'LEGACY_OCCUPIED' THEN + RAISE EXCEPTION 'Numeric-only tenant scope cannot use a fresh source-bound key' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_numeric_fresh_tenant_scope_denied'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION guard_fresh_game_instance_owner_write() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + current_kind VARCHAR(32); + previous_kind VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN + SELECT reservation_kind INTO previous_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = OLD.tenant_id; + IF previous_kind = 'FRESH_SOURCE_BOUND' THEN + RAISE EXCEPTION 'Fresh Game Session instance tenant scope is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_fresh_tenant_scope_immutable'; + END IF; + END IF; + + SELECT reservation_kind INTO current_kind + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = NEW.tenant_id + FOR KEY SHARE; + IF current_kind IS DISTINCT FROM 'FRESH_SOURCE_BOUND' THEN + RETURN NEW; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM game_session_tenant_canonical_claim claim + JOIN game_session_fresh_tenant_association association + ON association.target_namespace = claim.target_namespace + AND association.canonical_tenant_id = claim.canonical_tenant_id + AND association.legacy_game_session_tenant_id = claim.legacy_game_session_tenant_id + AND association.association_operation_id = claim.association_operation_id + AND association.association_kind = claim.association_kind + WHERE claim.legacy_game_session_tenant_id = NEW.tenant_id + AND claim.association_kind = 'FRESH_SOURCE_BOUND' + AND association.association_kind = 'FRESH_SOURCE_BOUND' + ) THEN + RAISE EXCEPTION 'Fresh Game Session instance requires exact persisted source identity' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_fresh_tenant_owner_missing'; + END IF; + + IF TG_OP = 'INSERT' + AND (NEW.status IS DISTINCT FROM 'STARTING' + OR NEW.run_owned_start_request_id IS NULL + OR NEW.run_owned_start_published_release_bundle_ref IS NULL) THEN + RAISE EXCEPTION 'Fresh Game Session runtime row must be owner-created in STARTING' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_fresh_starting_owner_required'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_instances_fresh_canonical_owner_guard + BEFORE INSERT OR UPDATE ON game_instances + FOR EACH ROW EXECUTE FUNCTION guard_fresh_game_instance_owner_write(); + +CREATE FUNCTION require_complete_game_instance_launch_association() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; + reservation_type VARCHAR(32); + match_count BIGINT; +BEGIN + SELECT * INTO runtime_row FROM game_instances WHERE id = NEW.id; + IF NOT FOUND THEN + RETURN NULL; + END IF; + + SELECT reservation_kind INTO reservation_type + FROM game_session_tenant_scope_reservation + WHERE game_session_tenant_id = runtime_row.tenant_id; + IF reservation_type IS DISTINCT FROM 'FRESH_SOURCE_BOUND' THEN + RETURN NULL; + END IF; + + SELECT count(*) INTO match_count + FROM game_session_canonical_instance_launch launch + JOIN game_session_fresh_tenant_association fresh + ON fresh.target_namespace = launch.target_namespace + AND fresh.association_operation_id = launch.tenant_association_operation_id + AND fresh.association_request_id = launch.tenant_association_request_id + AND fresh.source_schema_version = launch.tenant_source_schema_version + AND fresh.source_target_namespace = launch.tenant_source_target_namespace + AND fresh.source_request_id = launch.tenant_source_request_id + AND fresh.source_canonical_tenant_id = launch.tenant_source_canonical_tenant_id + AND fresh.canonical_tenant_id = launch.canonical_tenant_id + AND fresh.legacy_game_session_tenant_id = launch.game_session_tenant_id + AND fresh.source_game_row_id = launch.tenant_source_game_row_id + AND fresh.source_game_tenant_key = launch.tenant_source_game_tenant_key + AND fresh.provenance_kind = launch.tenant_source_provenance_kind + AND fresh.association_kind = launch.tenant_association_kind + JOIN game_session_canonical_realm_catalog realm + ON realm.target_namespace = launch.target_namespace + AND realm.realm_id = launch.canonical_realm_id + WHERE launch.target_namespace = realm.target_namespace + AND launch.game_session_tenant_id = runtime_row.tenant_id + AND launch.game_instance_id = runtime_row.id + AND launch.game_instance_uuid = runtime_row.game_instance_uuid + AND launch.canonical_tenant_id = fresh.canonical_tenant_id + AND realm.canonical_tenant_id = launch.canonical_tenant_id + AND launch.world_slug = realm.world_slug + AND launch.playable_state_namespace_id = realm.playable_state_namespace_id + AND realm.visible AND realm.public_production AND realm.state_scope = 'SHARED' + AND launch.playable_state_scope = 'SHARED' AND launch.public_production + AND launch.game_template_id = runtime_row.game_template_id + AND launch.launch_descriptor_id = runtime_row.launch_descriptor_id + AND launch.version_id = runtime_row.version_id + AND launch.release_bundle_id = runtime_row.release_bundle_id + AND launch.generation_config_revision = runtime_row.generation_config_revision + AND launch.version_state_epoch = runtime_row.version_state_epoch + AND launch.control_plane_request_id = runtime_row.run_owned_start_request_id + AND launch.captured_starting_row_version <= runtime_row.row_version + AND runtime_row.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'targetNamespace' = launch.target_namespace + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'controlPlaneRequestId' + = launch.control_plane_request_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'canonicalTenantId' + = launch.canonical_tenant_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'worldSlug' = launch.world_slug + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'launchDescriptorId' + = launch.launch_descriptor_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'gameTemplateId' + = launch.game_template_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionId' + = launch.version_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'releaseBundleId' + = launch.release_bundle_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'generationConfigRevision' + = launch.generation_config_revision + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionStateEpoch' + = launch.version_state_epoch::text; + + IF match_count <> 1 THEN + RAISE EXCEPTION 'Fresh Game Session instance requires one exact complete launch association' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_instance_complete_launch_association_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER game_instances_complete_launch_association_required + AFTER INSERT OR UPDATE ON game_instances + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION require_complete_game_instance_launch_association(); + +CREATE FUNCTION reject_game_session_canonical_instance_launch_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session canonical instance launch evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'gs_canonical_instance_launch_immutable'; +END; +$$; + +CREATE TRIGGER game_session_canonical_instance_launch_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_instance_launch + FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_instance_launch_mutation(); +CREATE TRIGGER game_session_canonical_instance_launch_no_truncate + BEFORE TRUNCATE ON game_session_canonical_instance_launch + FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_instance_launch_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V27__canonical_closed_admission_pointer.sql b/services/game-session-service/src/main/resources/db/migration/V27__canonical_closed_admission_pointer.sql new file mode 100644 index 0000000000..4ebd0592f9 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V27__canonical_closed_admission_pointer.sql @@ -0,0 +1,460 @@ +-- Preserve every retained pointer and audit value as representation version 1. New canonical +-- closed-only rows use version 2 and leave legacy numeric and catalog-policy copies absent. +-- [jooq ignore start] +ALTER TABLE gameplay_admission_pointer + ADD COLUMN representation_version integer NOT NULL DEFAULT 1, + ADD COLUMN target_namespace character varying(63), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN admission_state character varying(16); + +ALTER TABLE gameplay_admission_pointer + ALTER COLUMN tenant_id DROP NOT NULL, + ALTER COLUMN game_instance_id DROP NOT NULL, + ALTER COLUMN world_display_name DROP NOT NULL, + ALTER COLUMN realm_display_name DROP NOT NULL, + ALTER COLUMN visible DROP NOT NULL, + ALTER COLUMN public_production_realm DROP NOT NULL, + ALTER COLUMN public_production_realm DROP DEFAULT, + ALTER COLUMN requires_character_selection DROP NOT NULL, + ALTER COLUMN state_scope DROP NOT NULL, + ALTER COLUMN character_creation_policy DROP NOT NULL, + ALTER COLUMN last_updated_by DROP NOT NULL, + ALTER COLUMN last_update_reason DROP NOT NULL; + +ALTER TABLE gameplay_admission_pointer + DROP CONSTRAINT gameplay_admission_pointer_identity_pair_complete; + +ALTER TABLE gameplay_admission_pointer + ADD CONSTRAINT chk_gameplay_admission_pointer_representation CHECK ( + (representation_version = 1 + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND admission_state IS NULL + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS NOT NULL + AND requires_character_selection IS NOT NULL + AND state_scope IS NOT NULL + AND character_creation_policy IS NOT NULL + AND last_updated_by IS NOT NULL + AND last_update_reason IS NOT NULL) + OR (representation_version = 2 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL + AND admission_state IS NOT NULL + AND admission_state = 'CLOSED' + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND pointer_version = 1 + AND catalog_revision = 1 + AND world_display_name IS NULL + AND realm_display_name IS NULL + AND visible IS NULL + AND public_production_realm IS NULL + AND requires_character_selection IS NULL + AND state_scope IS NULL + AND character_creation_policy IS NULL + AND last_updated_by IS NULL + AND last_update_reason IS NULL)) + , + ADD CONSTRAINT gameplay_admission_pointer_identity_pair_complete CHECK ( + (representation_version = 1 + AND ((realm_id IS NULL) = (playable_state_namespace_id IS NULL))) + OR (representation_version = 2 + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL)) + , + ADD CONSTRAINT chk_gameplay_admission_pointer_canonical_identity CHECK ( + representation_version <> 2 + OR (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid)) + , + ADD CONSTRAINT fk_gameplay_admission_pointer_canonical_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id); + +ALTER TABLE gameplay_admission_pointer_event + ADD COLUMN representation_version integer NOT NULL DEFAULT 1, + ADD COLUMN target_namespace character varying(63), + ADD COLUMN canonical_tenant_id uuid, + ADD COLUMN admission_state character varying(16); + +ALTER TABLE gameplay_admission_pointer_event + ALTER COLUMN tenant_id DROP NOT NULL, + ALTER COLUMN game_instance_id DROP NOT NULL, + ALTER COLUMN world_display_name DROP NOT NULL, + ALTER COLUMN realm_display_name DROP NOT NULL, + ALTER COLUMN visible DROP NOT NULL, + ALTER COLUMN public_production_realm DROP NOT NULL, + ALTER COLUMN public_production_realm DROP DEFAULT, + ALTER COLUMN requires_character_selection DROP NOT NULL, + ALTER COLUMN state_scope DROP NOT NULL, + ALTER COLUMN character_creation_policy DROP NOT NULL; + +ALTER TABLE gameplay_admission_pointer_event + DROP CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete; + +ALTER TABLE gameplay_admission_pointer_event + ADD CONSTRAINT chk_gameplay_admission_pointer_event_representation CHECK ( + (representation_version = 1 + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND admission_state IS NULL + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS NOT NULL + AND requires_character_selection IS NOT NULL + AND state_scope IS NOT NULL + AND character_creation_policy IS NOT NULL) + OR (representation_version = 2 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL + AND catalog_revision IS NOT NULL + AND catalog_revision = 1 + AND admission_state IS NOT NULL + AND admission_state = 'CLOSED' + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND pointer_version = 1 + AND world_display_name IS NULL + AND realm_display_name IS NULL + AND visible IS NULL + AND public_production_realm IS NULL + AND requires_character_selection IS NULL + AND state_scope IS NULL + AND character_creation_policy IS NULL + AND prepared_version_upgrade_id IS NULL)) + , + ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete CHECK ( + (representation_version = 1 + AND ((realm_id IS NULL) = (playable_state_namespace_id IS NULL))) + OR (representation_version = 2 + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL)) + , + ADD CONSTRAINT chk_gameplay_admission_pointer_event_canonical_identity CHECK ( + representation_version <> 2 + OR (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid)) + , + ADD CONSTRAINT fk_gameplay_admission_pointer_event_canonical_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id); + +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_event_canonical_realm_version + ON gameplay_admission_pointer_event (target_namespace, canonical_tenant_id, realm_id, pointer_version) + WHERE representation_version = 2; + +CREATE TABLE game_session_canonical_closed_admission_pointer_request ( + target_namespace character varying(63) NOT NULL, + request_id uuid NOT NULL, + request_digest character varying(71) NOT NULL, + canonical_tenant_id uuid NOT NULL, + realm_id uuid NOT NULL, + catalog_creation_request_id uuid NOT NULL, + catalog_revision bigint NOT NULL, + catalog_request_digest character varying(71) NOT NULL, + catalog_receipt_digest character varying(71) NOT NULL, + actor_principal character varying(200) NOT NULL, + reason character varying(500) NOT NULL, + admission_state character varying(16) NOT NULL, + pointer_version bigint NOT NULL, + audit_event_id bigint NOT NULL, + receipt_digest character varying(71) NOT NULL, + updated_at timestamp with time zone NOT NULL, + CONSTRAINT pk_gs_canonical_closed_pointer_request PRIMARY KEY (target_namespace, request_id), + CONSTRAINT uq_gs_canonical_closed_pointer_request_realm + UNIQUE (target_namespace, canonical_tenant_id, realm_id), + CONSTRAINT uq_gs_canonical_closed_pointer_request_event UNIQUE (audit_event_id), + CONSTRAINT fk_gs_canonical_closed_pointer_request_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT fk_gs_canonical_closed_pointer_request_event + FOREIGN KEY (audit_event_id) REFERENCES gameplay_admission_pointer_event (id), + CONSTRAINT chk_gs_canonical_closed_pointer_request_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_creation_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_revision = 1 + AND pointer_version = 1 + AND audit_event_id > 0 + AND admission_state = 'CLOSED'), + CONSTRAINT chk_gs_canonical_closed_pointer_request_digests CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND catalog_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND catalog_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_canonical_closed_pointer_request_audit CHECK ( + char_length(actor_principal) BETWEEN 1 AND 200 + AND actor_principal !~ '^[[:space:]]*$' + AND char_length(reason) BETWEEN 1 AND 500 + AND reason !~ '^[[:space:]]*$') +); + +CREATE FUNCTION reject_game_session_canonical_closed_pointer_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'TRUNCATE' THEN + IF TG_TABLE_NAME = 'game_session_canonical_closed_admission_pointer_request' + AND EXISTS (SELECT 1 FROM game_session_canonical_closed_admission_pointer_request) + THEN + RAISE EXCEPTION 'Canonical CLOSED pointer request outcomes are immutable survivor evidence' + USING ERRCODE = '23514'; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer' + AND EXISTS ( + SELECT 1 FROM gameplay_admission_pointer WHERE representation_version = 2) + THEN + RAISE EXCEPTION 'Canonical CLOSED admission pointers are immutable survivor evidence' + USING ERRCODE = '23514'; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer_event' + AND EXISTS ( + SELECT 1 FROM gameplay_admission_pointer_event WHERE representation_version = 2) + THEN + RAISE EXCEPTION 'Canonical CLOSED pointer events are immutable survivor evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; + END IF; + + IF TG_TABLE_NAME = 'game_session_canonical_closed_admission_pointer_request' THEN + RAISE EXCEPTION 'Canonical CLOSED pointer evidence is immutable' + USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'gameplay_admission_pointer' + OR TG_TABLE_NAME = 'gameplay_admission_pointer_event' + THEN + IF OLD.representation_version = 2 + OR (TG_OP = 'UPDATE' AND NEW.representation_version = 2) + THEN + RAISE EXCEPTION 'Canonical CLOSED pointer evidence is immutable' + USING ERRCODE = '23514'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gameplay_admission_pointer_canonical_immutable +BEFORE UPDATE OR DELETE ON gameplay_admission_pointer +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER gameplay_admission_pointer_canonical_no_truncate +BEFORE TRUNCATE ON gameplay_admission_pointer +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER gameplay_admission_pointer_event_canonical_immutable +BEFORE UPDATE OR DELETE ON gameplay_admission_pointer_event +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER gameplay_admission_pointer_event_canonical_no_truncate +BEFORE TRUNCATE ON gameplay_admission_pointer_event +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER game_session_canonical_closed_pointer_request_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_closed_admission_pointer_request +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE TRIGGER game_session_canonical_closed_pointer_request_no_truncate +BEFORE TRUNCATE ON game_session_canonical_closed_admission_pointer_request +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE FUNCTION require_game_session_canonical_closed_pointer_catalog() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.representation_version = 2 AND NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + WHERE catalog.target_namespace = NEW.target_namespace + AND catalog.canonical_tenant_id = NEW.canonical_tenant_id + AND catalog.realm_id = NEW.realm_id + AND catalog.world_slug = NEW.world_slug + AND catalog.realm_slug = NEW.realm_slug + AND catalog.catalog_revision = NEW.catalog_revision + AND catalog.visible + AND catalog.public_production + ) THEN + RAISE EXCEPTION 'Canonical CLOSED pointer requires its exact initial public catalog row' + USING ERRCODE = '23514'; + END IF; + IF NEW.representation_version = 2 AND EXISTS ( + SELECT 1 + FROM game_session_retained_tenant_association retained + WHERE retained.target_namespace = NEW.target_namespace + AND retained.canonical_tenant_id = NEW.canonical_tenant_id + ) THEN + RAISE EXCEPTION 'Canonical CLOSED pointer cannot replace retained numeric tenant authority' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gameplay_admission_pointer_canonical_requires_catalog +BEFORE INSERT ON gameplay_admission_pointer +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_catalog(); + +CREATE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + expected_target_namespace character varying(63); + expected_tenant_id uuid; + expected_realm_id uuid; + expected_pointer_version bigint; + expected_event_id bigint; + expected_request_id uuid; +BEGIN + IF TG_TABLE_NAME = 'gameplay_admission_pointer' THEN + IF NEW.representation_version <> 2 THEN + RETURN NULL; + END IF; + expected_target_namespace := NEW.target_namespace; + expected_tenant_id := NEW.canonical_tenant_id; + expected_realm_id := NEW.realm_id; + expected_pointer_version := NEW.pointer_version; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer_event' THEN + IF NEW.representation_version <> 2 THEN + RETURN NULL; + END IF; + expected_target_namespace := NEW.target_namespace; + expected_tenant_id := NEW.canonical_tenant_id; + expected_realm_id := NEW.realm_id; + expected_pointer_version := NEW.pointer_version; + expected_event_id := NEW.id; + ELSE + expected_target_namespace := NEW.target_namespace; + expected_tenant_id := NEW.canonical_tenant_id; + expected_realm_id := NEW.realm_id; + expected_pointer_version := NEW.pointer_version; + expected_event_id := NEW.audit_event_id; + expected_request_id := NEW.request_id; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM gameplay_admission_pointer pointer + JOIN gameplay_admission_pointer_event event + ON event.representation_version = 2 + AND event.target_namespace = pointer.target_namespace + AND event.canonical_tenant_id = pointer.canonical_tenant_id + AND event.realm_id = pointer.realm_id + AND event.pointer_version = pointer.pointer_version + JOIN game_session_canonical_closed_admission_pointer_request outcome + ON outcome.target_namespace = pointer.target_namespace + AND outcome.canonical_tenant_id = pointer.canonical_tenant_id + AND outcome.realm_id = pointer.realm_id + AND outcome.pointer_version = pointer.pointer_version + AND outcome.audit_event_id = event.id + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = pointer.target_namespace + AND catalog.canonical_tenant_id = pointer.canonical_tenant_id + AND catalog.realm_id = pointer.realm_id + AND catalog.catalog_revision = pointer.catalog_revision + AND catalog.creation_request_id = outcome.catalog_creation_request_id + AND catalog.request_digest = outcome.catalog_request_digest + AND catalog.receipt_digest = outcome.catalog_receipt_digest + AND catalog.visible + AND catalog.public_production + WHERE pointer.representation_version = 2 + AND pointer.target_namespace = expected_target_namespace + AND pointer.canonical_tenant_id = expected_tenant_id + AND pointer.realm_id = expected_realm_id + AND pointer.pointer_version = expected_pointer_version + AND pointer.admission_state = 'CLOSED' + AND pointer.tenant_id IS NULL + AND pointer.game_instance_id IS NULL + AND pointer.playable_state_namespace_id IS NULL + AND pointer.world_slug = catalog.world_slug + AND pointer.realm_slug = catalog.realm_slug + AND pointer.world_display_name IS NULL + AND pointer.realm_display_name IS NULL + AND pointer.visible IS NULL + AND pointer.public_production_realm IS NULL + AND pointer.requires_character_selection IS NULL + AND pointer.state_scope IS NULL + AND pointer.character_creation_policy IS NULL + AND pointer.last_updated_by IS NULL + AND pointer.last_update_reason IS NULL + AND event.id = outcome.audit_event_id + AND event.target_namespace = pointer.target_namespace + AND event.canonical_tenant_id = pointer.canonical_tenant_id + AND event.realm_id = pointer.realm_id + AND event.pointer_version = pointer.pointer_version + AND event.catalog_revision = catalog.catalog_revision + AND event.admission_state = 'CLOSED' + AND event.tenant_id IS NULL + AND event.game_instance_id IS NULL + AND event.world_slug = catalog.world_slug + AND event.realm_slug = catalog.realm_slug + AND event.world_display_name IS NULL + AND event.realm_display_name IS NULL + AND event.visible IS NULL + AND event.public_production_realm IS NULL + AND event.requires_character_selection IS NULL + AND event.state_scope IS NULL + AND event.character_creation_policy IS NULL + AND event.prepared_version_upgrade_id IS NULL + AND event.control_plane_request_id = outcome.request_id::text + AND event.actor_principal = outcome.actor_principal + AND event.reason = outcome.reason + AND outcome.admission_state = 'CLOSED' + AND outcome.request_digest ~ '^sha256:[0-9a-f]{64}$' + AND outcome.receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND outcome.pointer_version = pointer.pointer_version + AND outcome.catalog_revision = catalog.catalog_revision + AND outcome.target_namespace = pointer.target_namespace + AND outcome.canonical_tenant_id = pointer.canonical_tenant_id + AND outcome.realm_id = pointer.realm_id + AND outcome.updated_at = (pointer.updated_at AT TIME ZONE 'UTC') + AND outcome.updated_at = (pointer.created_at AT TIME ZONE 'UTC') + AND event.occurred_at = (outcome.updated_at AT TIME ZONE 'UTC') + AND (expected_event_id IS NULL OR event.id = expected_event_id) + AND (expected_request_id IS NULL OR outcome.request_id = expected_request_id) + ) THEN + RAISE EXCEPTION 'Canonical CLOSED pointer, event, outcome and exact catalog must commit together' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER gameplay_admission_pointer_canonical_atomic_evidence +AFTER INSERT ON gameplay_admission_pointer +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence(); + +CREATE CONSTRAINT TRIGGER gameplay_admission_pointer_event_canonical_atomic_evidence +AFTER INSERT ON gameplay_admission_pointer_event +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence(); + +CREATE CONSTRAINT TRIGGER game_session_canonical_closed_pointer_request_atomic_evidence +AFTER INSERT ON game_session_canonical_closed_admission_pointer_request +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_closed_pointer_atomic_evidence(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V28__canonical_initial_admission_owner_and_intent.sql b/services/game-session-service/src/main/resources/db/migration/V28__canonical_initial_admission_owner_and_intent.sql new file mode 100644 index 0000000000..83de06db2b --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V28__canonical_initial_admission_owner_and_intent.sql @@ -0,0 +1,1044 @@ +-- Add the first canonical OPEN as a separate representation. The V13 CLOSED representation and +-- its original request/event remain immutable survivor evidence. +-- [jooq ignore start] +ALTER TABLE gameplay_admission_pointer + ADD COLUMN canonical_game_instance_id uuid, + ADD COLUMN canonical_version_id uuid, + ADD COLUMN runtime_version_id bigint, + ADD COLUMN initial_admission_request_id character varying(128), + ADD COLUMN initial_admission_request_digest character varying(64), + ADD COLUMN initial_admission_origin_kind character varying(24), + ADD COLUMN initial_admission_prior_pointer_version bigint, + ADD COLUMN initial_admission_active_epoch bigint, + ADD COLUMN initial_admission_hold_id uuid, + ADD COLUMN initial_admission_hold_fence uuid, + ADD COLUMN initial_admission_hold_binding_digest character varying(71); + +ALTER TABLE gameplay_admission_pointer_event + ADD COLUMN canonical_game_instance_id uuid, + ADD COLUMN canonical_version_id uuid, + ADD COLUMN runtime_version_id bigint, + ADD COLUMN initial_admission_request_id character varying(128), + ADD COLUMN initial_admission_request_digest character varying(64), + ADD COLUMN initial_admission_origin_kind character varying(24), + ADD COLUMN initial_admission_prior_pointer_version bigint, + ADD COLUMN initial_admission_active_epoch bigint, + ADD COLUMN initial_admission_hold_id uuid, + ADD COLUMN initial_admission_hold_fence uuid, + ADD COLUMN initial_admission_hold_binding_digest character varying(71); + +CREATE TABLE game_session_canonical_initial_admission_attempt ( + target_namespace character varying(63) NOT NULL, + initial_admission_request_id character varying(128) NOT NULL, + request_digest character varying(64) NOT NULL, + canonical_tenant_id uuid NOT NULL, + world_slug character varying(120) NOT NULL, + realm_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + playable_state_scope character varying(16) NOT NULL, + canonical_game_instance_id uuid NOT NULL, + canonical_version_id uuid NOT NULL, + game_session_tenant_id bigint NOT NULL, + game_instance_id bigint NOT NULL, + runtime_version_id bigint NOT NULL, + expected_catalog_revision bigint NOT NULL, + origin_kind character varying(24) NOT NULL, + expected_prior_pointer_version bigint, + active_lifecycle_epoch bigint NOT NULL, + hold_id uuid NOT NULL, + hold_fence uuid NOT NULL, + hold_binding_digest character varying(71) NOT NULL, + status character varying(16) NOT NULL DEFAULT 'PENDING', + pointer_id bigint, + pointer_version bigint, + audit_event_id bigint, + prior_pointer_request_id uuid, + prior_pointer_request_digest character varying(71), + prior_pointer_audit_event_id bigint, + commit_proof_digest character varying(71), + abort_proof_digest character varying(71), + abort_reason character varying(500), + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone NOT NULL, + terminal_at timestamp with time zone, + CONSTRAINT pk_gs_canonical_initial_admission_attempt + PRIMARY KEY (target_namespace, initial_admission_request_id), + CONSTRAINT uq_gs_canonical_initial_admission_hold UNIQUE (target_namespace, hold_id), + CONSTRAINT uq_gs_canonical_initial_admission_audit UNIQUE (audit_event_id), + CONSTRAINT fk_gs_canonical_initial_admission_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT fk_gs_canonical_initial_admission_launch + FOREIGN KEY (target_namespace, canonical_game_instance_id) + REFERENCES game_session_canonical_instance_launch (target_namespace, game_instance_uuid), + CONSTRAINT fk_gs_canonical_initial_admission_pointer + FOREIGN KEY (pointer_id) REFERENCES gameplay_admission_pointer (id), + CONSTRAINT fk_gs_canonical_initial_admission_event + FOREIGN KEY (audit_event_id) REFERENCES gameplay_admission_pointer_event (id), + CONSTRAINT fk_gs_canonical_initial_admission_prior_event + FOREIGN KEY (prior_pointer_audit_event_id) REFERENCES gameplay_admission_pointer_event (id), + CONSTRAINT chk_gs_canonical_initial_admission_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND char_length(initial_admission_request_id) BETWEEN 1 AND 128 + AND initial_admission_request_id !~ '^[[:space:]]*$' + AND initial_admission_request_id !~ '[[:cntrl:]]' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND hold_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND hold_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_session_tenant_id > 0 + AND game_instance_id > 0 + AND runtime_version_id > 0 + AND expected_catalog_revision > 0 + AND active_lifecycle_epoch > 0 + AND playable_state_scope = 'SHARED'), + CONSTRAINT chk_gs_canonical_initial_admission_digest CHECK ( + request_digest ~ '^[0-9a-f]{64}$' + AND hold_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND (commit_proof_digest IS NULL OR commit_proof_digest ~ '^sha256:[0-9a-f]{64}$') + AND (abort_proof_digest IS NULL OR abort_proof_digest ~ '^sha256:[0-9a-f]{64}$') + AND (prior_pointer_request_digest IS NULL + OR prior_pointer_request_digest ~ '^sha256:[0-9a-f]{64}$')), + CONSTRAINT chk_gs_canonical_initial_admission_origin CHECK ( + (origin_kind = 'NO_PRIOR_POINTER' + AND expected_prior_pointer_version IS NULL + AND prior_pointer_request_id IS NULL + AND prior_pointer_request_digest IS NULL + AND prior_pointer_audit_event_id IS NULL) + OR (origin_kind = 'EXPECT_CLOSED' + AND expected_prior_pointer_version > 0 + AND ((prior_pointer_request_id IS NULL + AND prior_pointer_request_digest IS NULL + AND prior_pointer_audit_event_id IS NULL) + OR (prior_pointer_request_id IS NOT NULL + AND prior_pointer_request_digest IS NOT NULL + AND prior_pointer_audit_event_id IS NOT NULL)))), + CONSTRAINT chk_gs_canonical_initial_admission_result CHECK ( + (status = 'PENDING' + AND terminal_at IS NULL + AND pointer_id IS NULL + AND pointer_version IS NULL + AND audit_event_id IS NULL + AND prior_pointer_request_id IS NULL + AND prior_pointer_request_digest IS NULL + AND prior_pointer_audit_event_id IS NULL + AND commit_proof_digest IS NULL + AND abort_proof_digest IS NULL + AND abort_reason IS NULL) + OR (status = 'COMMITTED' + AND terminal_at IS NOT NULL + AND pointer_id IS NOT NULL + AND pointer_version > 0 + AND audit_event_id IS NOT NULL + AND commit_proof_digest IS NOT NULL + AND abort_proof_digest IS NULL + AND abort_reason IS NULL + AND ((origin_kind = 'NO_PRIOR_POINTER' + AND prior_pointer_request_id IS NULL + AND prior_pointer_request_digest IS NULL + AND prior_pointer_audit_event_id IS NULL) + OR (origin_kind = 'EXPECT_CLOSED' + AND prior_pointer_request_id IS NOT NULL + AND prior_pointer_request_digest IS NOT NULL + AND prior_pointer_audit_event_id IS NOT NULL))) + OR (status = 'ABORTED' + AND terminal_at IS NOT NULL + AND pointer_id IS NULL + AND pointer_version IS NULL + AND audit_event_id IS NULL + AND commit_proof_digest IS NULL + AND abort_proof_digest IS NOT NULL + AND abort_reason IS NOT NULL + AND char_length(abort_reason) BETWEEN 1 AND 500 + AND abort_reason !~ '^[[:space:]]*$' + AND ((origin_kind = 'NO_PRIOR_POINTER' + AND prior_pointer_request_id IS NULL + AND prior_pointer_request_digest IS NULL + AND prior_pointer_audit_event_id IS NULL) + OR (origin_kind = 'EXPECT_CLOSED' + AND prior_pointer_request_id IS NOT NULL + AND prior_pointer_request_digest IS NOT NULL + AND prior_pointer_audit_event_id IS NOT NULL)))) +); + +CREATE UNIQUE INDEX uq_gs_canonical_initial_admission_pending_realm + ON game_session_canonical_initial_admission_attempt (target_namespace, canonical_tenant_id, realm_id) + WHERE status = 'PENDING'; + +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_event_initial_realm_version + ON gameplay_admission_pointer_event (target_namespace, canonical_tenant_id, realm_id, pointer_version) + WHERE representation_version = 3; + +ALTER TABLE gameplay_admission_pointer + DROP CONSTRAINT chk_gameplay_admission_pointer_representation, + ADD CONSTRAINT chk_gameplay_admission_pointer_representation CHECK ( + (representation_version = 1 + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND admission_state IS NULL + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS NOT NULL + AND requires_character_selection IS NOT NULL + AND state_scope IS NOT NULL + AND character_creation_policy IS NOT NULL + AND last_updated_by IS NOT NULL + AND last_update_reason IS NOT NULL + AND canonical_game_instance_id IS NULL + AND canonical_version_id IS NULL + AND runtime_version_id IS NULL + AND initial_admission_hold_binding_digest IS NULL) + OR (representation_version = 2 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND admission_state IS NOT NULL + AND admission_state = 'CLOSED' + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND pointer_version = 1 + AND catalog_revision = 1 + AND world_display_name IS NULL + AND realm_display_name IS NULL + AND visible IS NULL + AND public_production_realm IS NULL + AND requires_character_selection IS NULL + AND state_scope IS NULL + AND character_creation_policy IS NULL + AND last_updated_by IS NULL + AND last_update_reason IS NULL + AND canonical_game_instance_id IS NULL + AND canonical_version_id IS NULL + AND runtime_version_id IS NULL + AND initial_admission_request_id IS NULL + AND initial_admission_request_digest IS NULL + AND initial_admission_origin_kind IS NULL + AND initial_admission_prior_pointer_version IS NULL + AND initial_admission_active_epoch IS NULL + AND initial_admission_hold_id IS NULL + AND initial_admission_hold_fence IS NULL + AND initial_admission_hold_binding_digest IS NULL) + OR (representation_version = 3 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND admission_state = 'OPEN' + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND pointer_version > 0 + AND catalog_revision > 0 + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS TRUE + AND requires_character_selection IS NULL + AND state_scope = 'SHARED' + AND character_creation_policy IS NOT NULL + AND last_updated_by = 'game-session-canonical-initial-admission' + AND last_update_reason = 'World-held initial admission' + AND canonical_game_instance_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_version_id > 0 + AND initial_admission_request_id IS NOT NULL + AND initial_admission_request_digest IS NOT NULL + AND initial_admission_origin_kind IS NOT NULL + AND initial_admission_active_epoch > 0 + AND initial_admission_hold_id IS NOT NULL + AND initial_admission_hold_fence IS NOT NULL + AND initial_admission_hold_binding_digest IS NOT NULL + AND ((initial_admission_origin_kind = 'NO_PRIOR_POINTER' + AND initial_admission_prior_pointer_version IS NULL + AND pointer_version = 1) + OR (initial_admission_origin_kind = 'EXPECT_CLOSED' + AND initial_admission_prior_pointer_version > 0 + AND pointer_version = initial_admission_prior_pointer_version + 1)))) +; + +ALTER TABLE gameplay_admission_pointer + DROP CONSTRAINT gameplay_admission_pointer_identity_pair_complete, + ADD CONSTRAINT gameplay_admission_pointer_identity_pair_complete CHECK ( + (representation_version = 1 + AND ((realm_id IS NULL) = (playable_state_namespace_id IS NULL))) + OR (representation_version = 2 AND realm_id IS NOT NULL AND playable_state_namespace_id IS NULL) + OR (representation_version = 3 AND realm_id IS NOT NULL AND playable_state_namespace_id IS NOT NULL)); + +ALTER TABLE gameplay_admission_pointer + DROP CONSTRAINT chk_gameplay_admission_pointer_canonical_identity, + ADD CONSTRAINT chk_gameplay_admission_pointer_canonical_identity CHECK ( + representation_version NOT IN (2, 3) + OR (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND (representation_version = 2 + OR (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_version_id > 0 + AND initial_admission_request_digest ~ '^[0-9a-f]{64}$' + AND initial_admission_request_id !~ '[[:cntrl:]]' + AND initial_admission_hold_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND initial_admission_hold_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND initial_admission_hold_binding_digest ~ '^sha256:[0-9a-f]{64}$')))); + +ALTER TABLE gameplay_admission_pointer_event + DROP CONSTRAINT chk_gameplay_admission_pointer_event_representation, + ADD CONSTRAINT chk_gameplay_admission_pointer_event_representation CHECK ( + (representation_version = 1 + AND target_namespace IS NULL + AND canonical_tenant_id IS NULL + AND admission_state IS NULL + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS NOT NULL + AND requires_character_selection IS NOT NULL + AND state_scope IS NOT NULL + AND character_creation_policy IS NOT NULL) + OR (representation_version = 2 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND admission_state = 'CLOSED' + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NULL + AND catalog_revision = 1 + AND tenant_id IS NULL + AND game_instance_id IS NULL + AND pointer_version = 1 + AND world_display_name IS NULL + AND realm_display_name IS NULL + AND visible IS NULL + AND public_production_realm IS NULL + AND requires_character_selection IS NULL + AND state_scope IS NULL + AND character_creation_policy IS NULL + AND prepared_version_upgrade_id IS NULL + AND canonical_game_instance_id IS NULL + AND canonical_version_id IS NULL + AND runtime_version_id IS NULL + AND initial_admission_request_id IS NULL + AND initial_admission_request_digest IS NULL + AND initial_admission_origin_kind IS NULL + AND initial_admission_prior_pointer_version IS NULL + AND initial_admission_active_epoch IS NULL + AND initial_admission_hold_id IS NULL + AND initial_admission_hold_fence IS NULL + AND initial_admission_hold_binding_digest IS NULL) + OR (representation_version = 3 + AND target_namespace IS NOT NULL + AND canonical_tenant_id IS NOT NULL + AND realm_id IS NOT NULL + AND playable_state_namespace_id IS NOT NULL + AND admission_state = 'OPEN' + AND catalog_revision > 0 + AND tenant_id IS NOT NULL + AND game_instance_id IS NOT NULL + AND pointer_version > 0 + AND world_display_name IS NOT NULL + AND realm_display_name IS NOT NULL + AND visible IS NOT NULL + AND public_production_realm IS TRUE + AND requires_character_selection IS NULL + AND state_scope = 'SHARED' + AND character_creation_policy IS NOT NULL + AND prepared_version_upgrade_id IS NULL + AND canonical_game_instance_id IS NOT NULL + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_version_id > 0 + AND initial_admission_request_id IS NOT NULL + AND initial_admission_request_digest IS NOT NULL + AND initial_admission_origin_kind IS NOT NULL + AND initial_admission_active_epoch > 0 + AND initial_admission_hold_id IS NOT NULL + AND initial_admission_hold_fence IS NOT NULL + AND initial_admission_hold_binding_digest IS NOT NULL + AND actor_principal = 'game-session-canonical-initial-admission' + AND reason = 'World-held initial admission' + AND ((initial_admission_origin_kind = 'NO_PRIOR_POINTER' + AND initial_admission_prior_pointer_version IS NULL + AND pointer_version = 1) + OR (initial_admission_origin_kind = 'EXPECT_CLOSED' + AND initial_admission_prior_pointer_version > 0 + AND pointer_version = initial_admission_prior_pointer_version + 1)))) +; + +ALTER TABLE gameplay_admission_pointer_event + DROP CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete, + ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete CHECK ( + (representation_version = 1 + AND ((realm_id IS NULL) = (playable_state_namespace_id IS NULL))) + OR (representation_version = 2 AND realm_id IS NOT NULL AND playable_state_namespace_id IS NULL) + OR (representation_version = 3 AND realm_id IS NOT NULL AND playable_state_namespace_id IS NOT NULL)); + +ALTER TABLE gameplay_admission_pointer_event + DROP CONSTRAINT chk_gameplay_admission_pointer_event_canonical_identity, + ADD CONSTRAINT chk_gameplay_admission_pointer_event_canonical_identity CHECK ( + representation_version NOT IN (2, 3) + OR (octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND (representation_version = 2 + OR (playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_version_id > 0 + AND initial_admission_request_digest ~ '^[0-9a-f]{64}$' + AND initial_admission_request_id !~ '[[:cntrl:]]' + AND initial_admission_hold_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND initial_admission_hold_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND initial_admission_hold_binding_digest ~ '^sha256:[0-9a-f]{64}$')))); + +ALTER TABLE gameplay_admission_pointer + ADD CONSTRAINT fk_gameplay_admission_pointer_initial_request + FOREIGN KEY (target_namespace, initial_admission_request_id) + REFERENCES game_session_canonical_initial_admission_attempt + (target_namespace, initial_admission_request_id) + DEFERRABLE INITIALLY DEFERRED, + ADD CONSTRAINT fk_gameplay_admission_pointer_initial_launch + FOREIGN KEY (target_namespace, canonical_game_instance_id) + REFERENCES game_session_canonical_instance_launch (target_namespace, game_instance_uuid); + +ALTER TABLE gameplay_admission_pointer_event + ADD CONSTRAINT fk_gameplay_admission_event_initial_request + FOREIGN KEY (target_namespace, initial_admission_request_id) + REFERENCES game_session_canonical_initial_admission_attempt + (target_namespace, initial_admission_request_id) + DEFERRABLE INITIALLY DEFERRED, + ADD CONSTRAINT fk_gameplay_admission_event_initial_launch + FOREIGN KEY (target_namespace, canonical_game_instance_id) + REFERENCES game_session_canonical_instance_launch (target_namespace, game_instance_uuid); + +DROP TRIGGER gameplay_admission_pointer_canonical_immutable ON gameplay_admission_pointer; +DROP TRIGGER gameplay_admission_pointer_event_canonical_immutable ON gameplay_admission_pointer_event; +DROP TRIGGER gameplay_admission_pointer_canonical_no_truncate ON gameplay_admission_pointer; +DROP TRIGGER gameplay_admission_pointer_event_canonical_no_truncate ON gameplay_admission_pointer_event; + +CREATE OR REPLACE FUNCTION reject_game_session_canonical_closed_pointer_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'TRUNCATE' THEN + IF TG_TABLE_NAME = 'game_session_canonical_closed_admission_pointer_request' + AND EXISTS (SELECT 1 FROM game_session_canonical_closed_admission_pointer_request) + THEN + RAISE EXCEPTION 'Canonical CLOSED pointer request outcomes are immutable survivor evidence' + USING ERRCODE = '23514'; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer' + AND EXISTS (SELECT 1 FROM gameplay_admission_pointer WHERE representation_version IN (2, 3)) + THEN + RAISE EXCEPTION 'Canonical admission pointers are immutable survivor evidence' + USING ERRCODE = '23514'; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer_event' + AND EXISTS (SELECT 1 FROM gameplay_admission_pointer_event WHERE representation_version IN (2, 3)) + THEN + RAISE EXCEPTION 'Canonical admission pointer events are immutable survivor evidence' + USING ERRCODE = '23514'; + ELSIF TG_TABLE_NAME = 'game_session_canonical_initial_admission_attempt' + AND EXISTS (SELECT 1 FROM game_session_canonical_initial_admission_attempt) + THEN + RAISE EXCEPTION 'Canonical initial-admission outcomes are durable survivor evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; + END IF; + + IF TG_TABLE_NAME = 'game_session_canonical_closed_admission_pointer_request' THEN + RAISE EXCEPTION 'Canonical CLOSED pointer evidence is immutable' + USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'gameplay_admission_pointer_event' THEN + IF OLD.representation_version IN (2, 3) THEN + RAISE EXCEPTION 'Canonical pointer audit events are immutable' + USING ERRCODE = '23514'; + END IF; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer' THEN + IF TG_OP = 'DELETE' AND OLD.representation_version IN (2, 3) THEN + RAISE EXCEPTION 'Canonical admission pointers are immutable survivor evidence' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' AND OLD.representation_version = 2 THEN + IF NEW.representation_version = 3 + AND OLD.id = NEW.id + AND OLD.target_namespace = NEW.target_namespace + AND OLD.canonical_tenant_id = NEW.canonical_tenant_id + AND OLD.realm_id = NEW.realm_id + AND OLD.pointer_version = 1 + AND OLD.admission_state = 'CLOSED' + AND OLD.playable_state_namespace_id IS NULL + AND OLD.tenant_id IS NULL + AND OLD.game_instance_id IS NULL + AND NEW.created_at = OLD.created_at + THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Canonical CLOSED pointer may only enter the fenced first-OPEN operation' + USING ERRCODE = '23514'; + ELSIF TG_OP = 'UPDATE' AND OLD.representation_version = 3 THEN + RAISE EXCEPTION 'Canonical OPEN pointer is immutable outside the initial owner operation' + USING ERRCODE = '23514'; + ELSIF TG_OP = 'UPDATE' AND NEW.representation_version = 2 THEN + RAISE EXCEPTION 'Canonical CLOSED pointer evidence cannot be rewritten' + USING ERRCODE = '23514'; + END IF; + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gameplay_admission_pointer_canonical_immutable +BEFORE UPDATE OR DELETE ON gameplay_admission_pointer +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); +CREATE TRIGGER gameplay_admission_pointer_event_canonical_immutable +BEFORE UPDATE OR DELETE ON gameplay_admission_pointer_event +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); +CREATE TRIGGER gameplay_admission_pointer_canonical_no_truncate +BEFORE TRUNCATE ON gameplay_admission_pointer +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); +CREATE TRIGGER gameplay_admission_pointer_event_canonical_no_truncate +BEFORE TRUNCATE ON gameplay_admission_pointer_event +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE FUNCTION reject_game_session_canonical_initial_admission_attempt_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Canonical initial-admission attempts cannot be deleted' + USING ERRCODE = '23514'; + END IF; + IF OLD.status <> 'PENDING' + OR NEW.status NOT IN ('COMMITTED', 'ABORTED') + OR NEW.target_namespace IS DISTINCT FROM OLD.target_namespace + OR NEW.initial_admission_request_id IS DISTINCT FROM OLD.initial_admission_request_id + OR NEW.request_digest IS DISTINCT FROM OLD.request_digest + OR NEW.canonical_tenant_id IS DISTINCT FROM OLD.canonical_tenant_id + OR NEW.world_slug IS DISTINCT FROM OLD.world_slug + OR NEW.realm_id IS DISTINCT FROM OLD.realm_id + OR NEW.playable_state_namespace_id IS DISTINCT FROM OLD.playable_state_namespace_id + OR NEW.playable_state_scope IS DISTINCT FROM OLD.playable_state_scope + OR NEW.canonical_game_instance_id IS DISTINCT FROM OLD.canonical_game_instance_id + OR NEW.canonical_version_id IS DISTINCT FROM OLD.canonical_version_id + OR NEW.game_session_tenant_id IS DISTINCT FROM OLD.game_session_tenant_id + OR NEW.game_instance_id IS DISTINCT FROM OLD.game_instance_id + OR NEW.runtime_version_id IS DISTINCT FROM OLD.runtime_version_id + OR NEW.expected_catalog_revision IS DISTINCT FROM OLD.expected_catalog_revision + OR NEW.origin_kind IS DISTINCT FROM OLD.origin_kind + OR NEW.expected_prior_pointer_version IS DISTINCT FROM OLD.expected_prior_pointer_version + OR NEW.active_lifecycle_epoch IS DISTINCT FROM OLD.active_lifecycle_epoch + OR NEW.hold_id IS DISTINCT FROM OLD.hold_id + OR NEW.hold_fence IS DISTINCT FROM OLD.hold_fence + OR NEW.hold_binding_digest IS DISTINCT FROM OLD.hold_binding_digest + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.updated_at <= OLD.updated_at + OR NEW.terminal_at IS NULL + THEN + RAISE EXCEPTION 'Canonical initial-admission request identity is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_initial_admission_attempt_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_initial_admission_attempt +FOR EACH ROW EXECUTE FUNCTION reject_game_session_canonical_initial_admission_attempt_mutation(); + +CREATE TRIGGER game_session_canonical_initial_admission_attempt_no_truncate +BEFORE TRUNCATE ON game_session_canonical_initial_admission_attempt +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_closed_pointer_mutation(); + +CREATE FUNCTION require_game_session_canonical_initial_admission_catalog() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.representation_version <> 3 THEN + RETURN NEW; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_realm_catalog catalog + JOIN game_session_canonical_instance_launch launch + ON launch.target_namespace = catalog.target_namespace + AND launch.canonical_tenant_id = catalog.canonical_tenant_id + AND launch.canonical_realm_id = catalog.realm_id + AND launch.world_slug = catalog.world_slug + AND launch.playable_state_namespace_id = catalog.playable_state_namespace_id + AND launch.game_instance_uuid = NEW.canonical_game_instance_id + AND launch.game_session_tenant_id = NEW.tenant_id + AND launch.game_instance_id = NEW.game_instance_id + AND launch.version_id = NEW.runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.canonical_version_id::text + AND launch.playable_state_scope = catalog.state_scope + AND launch.public_production = catalog.public_production + JOIN game_instances current + ON current.tenant_id = launch.game_session_tenant_id + AND current.id = launch.game_instance_id + AND current.game_instance_uuid = launch.game_instance_uuid + AND current.version_id = NEW.runtime_version_id + AND current.status = 'RUNNING' + WHERE catalog.target_namespace = NEW.target_namespace + AND catalog.canonical_tenant_id = NEW.canonical_tenant_id + AND catalog.realm_id = NEW.realm_id + AND catalog.world_slug = NEW.world_slug + AND catalog.realm_slug = NEW.realm_slug + AND catalog.catalog_revision = NEW.catalog_revision + AND catalog.playable_state_namespace_id = NEW.playable_state_namespace_id + AND catalog.state_scope = NEW.state_scope + AND catalog.visible = NEW.visible + AND catalog.public_production = NEW.public_production_realm + AND catalog.character_creation_policy = NEW.character_creation_policy + ) THEN + RAISE EXCEPTION 'Canonical OPEN pointer requires exact catalog and launch owner evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gameplay_admission_pointer_initial_admission_requires_owners +BEFORE INSERT OR UPDATE ON gameplay_admission_pointer +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_catalog(); + +CREATE FUNCTION require_game_session_canonical_initial_admission_atomic_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + selected_namespace character varying(63); + selected_request_id character varying(128); + selected_status character varying(16); +BEGIN + IF TG_TABLE_NAME = 'gameplay_admission_pointer' THEN + IF NEW.representation_version <> 3 THEN + RETURN NULL; + END IF; + selected_namespace := NEW.target_namespace; + selected_request_id := NEW.initial_admission_request_id; + ELSIF TG_TABLE_NAME = 'gameplay_admission_pointer_event' THEN + IF NEW.representation_version <> 3 THEN + RETURN NULL; + END IF; + selected_namespace := NEW.target_namespace; + selected_request_id := NEW.initial_admission_request_id; + ELSE + selected_namespace := NEW.target_namespace; + selected_request_id := NEW.initial_admission_request_id; + END IF; + + SELECT status INTO selected_status + FROM game_session_canonical_initial_admission_attempt + WHERE target_namespace = selected_namespace + AND initial_admission_request_id = selected_request_id; + + IF selected_status = 'PENDING' THEN + IF EXISTS ( + SELECT 1 FROM gameplay_admission_pointer + WHERE representation_version = 3 + AND target_namespace = selected_namespace + AND initial_admission_request_id = selected_request_id + ) OR EXISTS ( + SELECT 1 FROM gameplay_admission_pointer_event + WHERE representation_version = 3 + AND target_namespace = selected_namespace + AND initial_admission_request_id = selected_request_id + ) THEN + RAISE EXCEPTION 'PENDING canonical initial-admission attempt cannot carry pointer evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; + END IF; + + IF selected_status = 'COMMITTED' AND EXISTS ( + SELECT 1 + FROM game_session_canonical_initial_admission_attempt attempt + JOIN gameplay_admission_pointer pointer + ON pointer.id = attempt.pointer_id + AND pointer.representation_version = 3 + AND pointer.target_namespace = attempt.target_namespace + AND pointer.canonical_tenant_id = attempt.canonical_tenant_id + AND pointer.realm_id = attempt.realm_id + AND pointer.world_slug = attempt.world_slug + AND pointer.playable_state_namespace_id = attempt.playable_state_namespace_id + AND pointer.state_scope = attempt.playable_state_scope + AND pointer.canonical_game_instance_id = attempt.canonical_game_instance_id + AND pointer.canonical_version_id = attempt.canonical_version_id + AND pointer.runtime_version_id = attempt.runtime_version_id + AND pointer.tenant_id = attempt.game_session_tenant_id + AND pointer.game_instance_id = attempt.game_instance_id + AND pointer.pointer_version = attempt.pointer_version + AND pointer.catalog_revision = attempt.expected_catalog_revision + AND pointer.initial_admission_request_id = attempt.initial_admission_request_id + AND pointer.initial_admission_request_digest = attempt.request_digest + AND pointer.initial_admission_origin_kind = attempt.origin_kind + AND pointer.initial_admission_prior_pointer_version IS NOT DISTINCT FROM attempt.expected_prior_pointer_version + AND pointer.initial_admission_active_epoch = attempt.active_lifecycle_epoch + AND pointer.initial_admission_hold_id = attempt.hold_id + AND pointer.initial_admission_hold_fence = attempt.hold_fence + AND pointer.initial_admission_hold_binding_digest = attempt.hold_binding_digest + AND pointer.admission_state = 'OPEN' + JOIN gameplay_admission_pointer_event event + ON event.id = attempt.audit_event_id + AND event.representation_version = 3 + AND event.target_namespace = attempt.target_namespace + AND event.canonical_tenant_id = attempt.canonical_tenant_id + AND event.realm_id = attempt.realm_id + AND event.world_slug = attempt.world_slug + AND event.playable_state_namespace_id = attempt.playable_state_namespace_id + AND event.state_scope = attempt.playable_state_scope + AND event.canonical_game_instance_id = attempt.canonical_game_instance_id + AND event.canonical_version_id = attempt.canonical_version_id + AND event.runtime_version_id = attempt.runtime_version_id + AND event.tenant_id = attempt.game_session_tenant_id + AND event.game_instance_id = attempt.game_instance_id + AND event.pointer_version = attempt.pointer_version + AND event.catalog_revision = attempt.expected_catalog_revision + AND event.initial_admission_request_id = attempt.initial_admission_request_id + AND event.control_plane_request_id = attempt.initial_admission_request_id + AND event.initial_admission_request_digest = attempt.request_digest + AND event.initial_admission_origin_kind = attempt.origin_kind + AND event.initial_admission_prior_pointer_version IS NOT DISTINCT FROM attempt.expected_prior_pointer_version + AND event.initial_admission_active_epoch = attempt.active_lifecycle_epoch + AND event.initial_admission_hold_id = attempt.hold_id + AND event.initial_admission_hold_fence = attempt.hold_fence + AND event.initial_admission_hold_binding_digest = attempt.hold_binding_digest + AND event.admission_state = 'OPEN' + AND event.prepared_version_upgrade_id IS NULL + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = attempt.target_namespace + AND catalog.canonical_tenant_id = attempt.canonical_tenant_id + AND catalog.realm_id = attempt.realm_id + AND catalog.world_slug = attempt.world_slug + AND catalog.catalog_revision = attempt.expected_catalog_revision + AND catalog.playable_state_namespace_id = attempt.playable_state_namespace_id + AND catalog.state_scope = attempt.playable_state_scope + AND catalog.visible = pointer.visible + AND catalog.public_production = pointer.public_production_realm + AND catalog.character_creation_policy = pointer.character_creation_policy + JOIN game_session_canonical_instance_launch launch + ON launch.target_namespace = attempt.target_namespace + AND launch.canonical_tenant_id = attempt.canonical_tenant_id + AND launch.canonical_realm_id = attempt.realm_id + AND launch.world_slug = attempt.world_slug + AND launch.playable_state_namespace_id = attempt.playable_state_namespace_id + AND launch.playable_state_scope = attempt.playable_state_scope + AND launch.public_production = TRUE + AND launch.game_instance_uuid = attempt.canonical_game_instance_id + AND launch.game_session_tenant_id = attempt.game_session_tenant_id + AND launch.game_instance_id = attempt.game_instance_id + AND launch.version_id = attempt.runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = attempt.canonical_version_id::text + JOIN game_instances current + ON current.tenant_id = launch.game_session_tenant_id + AND current.id = launch.game_instance_id + AND current.game_instance_uuid = launch.game_instance_uuid + AND current.version_id = attempt.runtime_version_id + AND current.status = 'RUNNING' + WHERE attempt.target_namespace = selected_namespace + AND attempt.initial_admission_request_id = selected_request_id + AND attempt.status = 'COMMITTED' + AND attempt.pointer_version = CASE + WHEN attempt.origin_kind = 'NO_PRIOR_POINTER' THEN 1 + ELSE attempt.expected_prior_pointer_version + 1 END + AND attempt.terminal_at = (pointer.updated_at AT TIME ZONE 'UTC') + AND attempt.terminal_at = (event.occurred_at AT TIME ZONE 'UTC') + AND ((attempt.origin_kind = 'NO_PRIOR_POINTER' + AND attempt.expected_prior_pointer_version IS NULL + AND attempt.prior_pointer_request_id IS NULL + AND attempt.prior_pointer_request_digest IS NULL + AND attempt.prior_pointer_audit_event_id IS NULL + AND NOT EXISTS ( + SELECT 1 FROM game_session_canonical_closed_admission_pointer_request origin + WHERE origin.target_namespace = attempt.target_namespace + AND origin.canonical_tenant_id = attempt.canonical_tenant_id + AND origin.realm_id = attempt.realm_id) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_admission_pointer other_pointer + WHERE other_pointer.id <> pointer.id + AND (other_pointer.realm_id = attempt.realm_id + OR (other_pointer.target_namespace = attempt.target_namespace + AND other_pointer.canonical_tenant_id = attempt.canonical_tenant_id) + OR (other_pointer.world_slug = attempt.world_slug + AND other_pointer.realm_slug = catalog.realm_slug) + OR (other_pointer.tenant_id = attempt.game_session_tenant_id + AND other_pointer.game_instance_id = attempt.game_instance_id))) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_admission_pointer_event other_event + WHERE other_event.id <> event.id + AND (other_event.realm_id = attempt.realm_id + OR (other_event.target_namespace = attempt.target_namespace + AND other_event.canonical_tenant_id = attempt.canonical_tenant_id) + OR (other_event.world_slug = attempt.world_slug + AND other_event.realm_slug = catalog.realm_slug) + OR (other_event.tenant_id = attempt.game_session_tenant_id + AND other_event.game_instance_id = attempt.game_instance_id))) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_initial_admission_bind_catalog legacy_catalog + WHERE legacy_catalog.tenant_id = attempt.game_session_tenant_id + AND (legacy_catalog.realm_id = attempt.realm_id + OR (legacy_catalog.world_slug = attempt.world_slug + AND legacy_catalog.realm_slug = catalog.realm_slug))) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_initial_admission_bind_attempt legacy_attempt + WHERE legacy_attempt.tenant_id = attempt.game_session_tenant_id + AND (legacy_attempt.realm_id = attempt.realm_id + OR legacy_attempt.game_instance_id = attempt.game_instance_id))) + OR (attempt.origin_kind = 'EXPECT_CLOSED' + AND attempt.expected_prior_pointer_version = 1 + AND attempt.prior_pointer_request_id IS NOT NULL + AND attempt.prior_pointer_request_digest IS NOT NULL + AND attempt.prior_pointer_audit_event_id IS NOT NULL + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_closed_admission_pointer_request origin + JOIN gameplay_admission_pointer_event origin_event + ON origin_event.id = origin.audit_event_id + AND origin_event.representation_version = 2 + AND origin_event.admission_state = 'CLOSED' + AND origin_event.pointer_version = 1 + AND origin_event.target_namespace = origin.target_namespace + AND origin_event.canonical_tenant_id = origin.canonical_tenant_id + AND origin_event.realm_id = origin.realm_id + AND origin_event.catalog_revision = origin.catalog_revision + AND origin_event.control_plane_request_id = origin.request_id::text + WHERE origin.target_namespace = attempt.target_namespace + AND origin.request_id = attempt.prior_pointer_request_id + AND origin.canonical_tenant_id = attempt.canonical_tenant_id + AND origin.realm_id = attempt.realm_id + AND origin.request_digest = attempt.prior_pointer_request_digest + AND origin.audit_event_id = attempt.prior_pointer_audit_event_id + AND origin.pointer_version = attempt.expected_prior_pointer_version + AND origin.catalog_revision = attempt.expected_catalog_revision))) + ) THEN + RETURN NULL; + END IF; + + IF selected_status = 'ABORTED' AND EXISTS ( + SELECT 1 + FROM game_session_canonical_initial_admission_attempt attempt + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = attempt.target_namespace + AND catalog.canonical_tenant_id = attempt.canonical_tenant_id + AND catalog.realm_id = attempt.realm_id + AND catalog.world_slug = attempt.world_slug + AND catalog.catalog_revision = attempt.expected_catalog_revision + AND catalog.playable_state_namespace_id = attempt.playable_state_namespace_id + AND catalog.state_scope = attempt.playable_state_scope + WHERE attempt.target_namespace = selected_namespace + AND attempt.initial_admission_request_id = selected_request_id + AND attempt.status = 'ABORTED' + AND attempt.pointer_id IS NULL + AND attempt.audit_event_id IS NULL + AND NOT EXISTS ( + SELECT 1 FROM gameplay_admission_pointer pointer + WHERE pointer.representation_version = 3 + AND pointer.target_namespace = attempt.target_namespace + AND pointer.initial_admission_request_id = attempt.initial_admission_request_id) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_admission_pointer_event event + WHERE event.representation_version = 3 + AND event.target_namespace = attempt.target_namespace + AND event.initial_admission_request_id = attempt.initial_admission_request_id) + AND ((attempt.origin_kind = 'NO_PRIOR_POINTER' + AND NOT EXISTS ( + SELECT 1 FROM gameplay_admission_pointer pointer + WHERE pointer.realm_id = attempt.realm_id + OR (pointer.target_namespace = attempt.target_namespace + AND pointer.canonical_tenant_id = attempt.canonical_tenant_id) + OR (pointer.world_slug = attempt.world_slug + AND pointer.realm_slug = catalog.realm_slug) + OR (pointer.tenant_id = attempt.game_session_tenant_id + AND pointer.game_instance_id = attempt.game_instance_id)) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_admission_pointer_event event + WHERE event.realm_id = attempt.realm_id + OR (event.target_namespace = attempt.target_namespace + AND event.canonical_tenant_id = attempt.canonical_tenant_id) + OR (event.world_slug = attempt.world_slug + AND event.realm_slug = catalog.realm_slug) + OR (event.tenant_id = attempt.game_session_tenant_id + AND event.game_instance_id = attempt.game_instance_id)) + AND NOT EXISTS ( + SELECT 1 FROM game_session_canonical_closed_admission_pointer_request origin + WHERE origin.target_namespace = attempt.target_namespace + AND origin.canonical_tenant_id = attempt.canonical_tenant_id + AND origin.realm_id = attempt.realm_id) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_initial_admission_bind_catalog legacy_catalog + WHERE legacy_catalog.tenant_id = attempt.game_session_tenant_id + AND (legacy_catalog.realm_id = attempt.realm_id + OR (legacy_catalog.world_slug = attempt.world_slug + AND legacy_catalog.realm_slug = catalog.realm_slug))) + AND NOT EXISTS ( + SELECT 1 FROM gameplay_initial_admission_bind_attempt legacy_attempt + WHERE legacy_attempt.tenant_id = attempt.game_session_tenant_id + AND (legacy_attempt.realm_id = attempt.realm_id + OR legacy_attempt.game_instance_id = attempt.game_instance_id))) + OR (attempt.origin_kind = 'EXPECT_CLOSED' + AND attempt.expected_prior_pointer_version = 1 + AND EXISTS ( + SELECT 1 + FROM gameplay_admission_pointer pointer + JOIN game_session_canonical_closed_admission_pointer_request origin + ON origin.target_namespace = attempt.target_namespace + AND origin.request_id = attempt.prior_pointer_request_id + AND origin.canonical_tenant_id = attempt.canonical_tenant_id + AND origin.realm_id = attempt.realm_id + AND origin.request_digest = attempt.prior_pointer_request_digest + AND origin.audit_event_id = attempt.prior_pointer_audit_event_id + JOIN gameplay_admission_pointer_event origin_event + ON origin_event.id = origin.audit_event_id + AND origin_event.representation_version = 2 + AND origin_event.admission_state = 'CLOSED' + AND origin_event.pointer_version = 1 + AND origin_event.target_namespace = origin.target_namespace + AND origin_event.canonical_tenant_id = origin.canonical_tenant_id + AND origin_event.realm_id = origin.realm_id + AND origin_event.catalog_revision = origin.catalog_revision + AND origin_event.control_plane_request_id = origin.request_id::text + WHERE pointer.representation_version = 2 + AND pointer.target_namespace = attempt.target_namespace + AND pointer.canonical_tenant_id = attempt.canonical_tenant_id + AND pointer.realm_id = attempt.realm_id + AND pointer.pointer_version = attempt.expected_prior_pointer_version + AND pointer.catalog_revision = attempt.expected_catalog_revision + AND pointer.admission_state = 'CLOSED' + AND origin.pointer_version = attempt.expected_prior_pointer_version + AND origin.catalog_revision = attempt.expected_catalog_revision))) + ) THEN + RETURN NULL; + END IF; + + RAISE EXCEPTION 'Canonical initial-admission attempt lacks matching atomic pointer/audit or fenced abort evidence' + USING ERRCODE = '23514'; +END; +$$; + +CREATE CONSTRAINT TRIGGER gameplay_admission_pointer_initial_admission_atomic +AFTER INSERT OR UPDATE ON gameplay_admission_pointer +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_atomic_evidence(); +CREATE CONSTRAINT TRIGGER gameplay_admission_pointer_event_initial_admission_atomic +AFTER INSERT ON gameplay_admission_pointer_event +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_atomic_evidence(); +CREATE CONSTRAINT TRIGGER game_session_initial_admission_attempt_atomic +AFTER INSERT OR UPDATE ON game_session_canonical_initial_admission_attempt +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_atomic_evidence(); +-- [jooq ignore stop] + +-- Persist the exact canonical intent before calling World to acquire the initial-admission hold. +-- The terminal pointer/audit outcome remains exclusively owned by the V17 attempt ledger. +CREATE TABLE game_session_canonical_initial_admission_intent ( + target_namespace character varying(63) NOT NULL, + initial_admission_request_id character varying(120) NOT NULL, + request_digest character varying(64) NOT NULL, + canonical_tenant_id uuid NOT NULL, + world_slug character varying(120) NOT NULL, + realm_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + playable_state_scope character varying(16) NOT NULL, + catalog_visible boolean NOT NULL, + catalog_public_production boolean NOT NULL, + catalog_revision bigint NOT NULL, + catalog_creation_request_id uuid NOT NULL, + catalog_request_digest character varying(71) NOT NULL, + catalog_receipt_digest character varying(71) NOT NULL, + tenant_association_operation_id uuid NOT NULL, + game_session_tenant_id bigint NOT NULL, + canonical_game_instance_id uuid NOT NULL, + game_instance_id bigint NOT NULL, + canonical_version_id uuid NOT NULL, + runtime_version_id bigint NOT NULL, + control_plane_request_id character varying(128) NOT NULL, + launch_descriptor_id character varying(255) NOT NULL, + captured_starting_row_version bigint NOT NULL, + current_row_version bigint NOT NULL, + descriptor_request_digest character varying(71) NOT NULL, + descriptor_result_digest character varying(71) NOT NULL, + release_attestation_digest character varying(71) NOT NULL, + canonical_hold_request_bytes bytea NOT NULL, + canonical_lifecycle_request_bytes bytea NOT NULL, + hold_identity_bytes bytea, + state character varying(16) NOT NULL, + created_at timestamp with time zone NOT NULL, + updated_at timestamp with time zone NOT NULL, + terminal_at timestamp with time zone, + CONSTRAINT pk_gs_canonical_initial_admission_intent + PRIMARY KEY (target_namespace, initial_admission_request_id), + CONSTRAINT fk_gs_initial_admission_intent_catalog + FOREIGN KEY (target_namespace, realm_id) + REFERENCES game_session_canonical_realm_catalog (target_namespace, realm_id), + CONSTRAINT fk_gs_initial_admission_intent_launch + FOREIGN KEY (target_namespace, canonical_game_instance_id) + REFERENCES game_session_canonical_instance_launch (target_namespace, game_instance_uuid), + CONSTRAINT chk_gs_initial_admission_intent_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND char_length(initial_admission_request_id) BETWEEN 1 AND 120 + AND initial_admission_request_id !~ '^[[:space:]]*$' + AND initial_admission_request_id !~ '[[:cntrl:]]' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_creation_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_association_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_session_tenant_id > 0 + AND game_instance_id > 0 + AND runtime_version_id > 0 + AND catalog_revision > 0 + AND captured_starting_row_version >= 0 + AND current_row_version >= captured_starting_row_version + AND playable_state_scope = 'SHARED' + AND catalog_visible IS TRUE + AND catalog_public_production IS TRUE), + CONSTRAINT chk_gs_initial_admission_intent_digests CHECK ( + request_digest ~ '^[0-9a-f]{64}$' + AND catalog_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND catalog_receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND descriptor_result_digest ~ '^sha256:[0-9a-f]{64}$' + AND release_attestation_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_initial_admission_intent_request_bytes CHECK ( + octet_length(canonical_hold_request_bytes) BETWEEN 1 AND 16384 + AND octet_length(canonical_lifecycle_request_bytes) BETWEEN 1 AND 16384 + AND (hold_identity_bytes IS NULL + OR octet_length(hold_identity_bytes) BETWEEN 1 AND 65536)), + CONSTRAINT chk_gs_initial_admission_intent_state CHECK ( + (state = 'PENDING_HOLD' + AND hold_identity_bytes IS NULL + AND terminal_at IS NULL) + OR (state = 'HOLD_ATTACHED' + AND hold_identity_bytes IS NOT NULL + AND terminal_at IS NULL) + OR (state = 'TERMINAL' + AND hold_identity_bytes IS NOT NULL + AND terminal_at IS NOT NULL)) +); + +CREATE UNIQUE INDEX uq_gs_canonical_initial_admission_pending_intent_realm + ON game_session_canonical_initial_admission_intent + (target_namespace, canonical_tenant_id, realm_id) + WHERE state IN ('PENDING_HOLD', 'HOLD_ATTACHED'); diff --git a/services/game-session-service/src/main/resources/db/migration/V29__canonical_gameplay_binding_inventory_foundation.sql b/services/game-session-service/src/main/resources/db/migration/V29__canonical_gameplay_binding_inventory_foundation.sql new file mode 100644 index 0000000000..4a5820ac81 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V29__canonical_gameplay_binding_inventory_foundation.sql @@ -0,0 +1,329 @@ +-- Durable preparation evidence for namespace-qualified gameplay bindings. This is a +-- Game Session inventory and obligation ledger, not an admission or controller authority. +-- Existing numeric/instance-scoped rows are intentionally neither relabelled nor backfilled. +CREATE TABLE game_session_canonical_binding_inventory_clock ( + singleton_id smallint NOT NULL, + inventory_revision numeric NOT NULL, + CONSTRAINT pk_gs_canonical_binding_inventory_clock PRIMARY KEY (singleton_id), + CONSTRAINT chk_gs_canonical_binding_inventory_clock_singleton CHECK (singleton_id = 1), + CONSTRAINT chk_gs_canonical_binding_inventory_clock_revision CHECK (inventory_revision >= 0) +); + +INSERT INTO game_session_canonical_binding_inventory_clock (singleton_id, inventory_revision) +VALUES (1, 0); + +CREATE TABLE game_session_canonical_binding_generation ( + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_id uuid NOT NULL, + last_issued_generation numeric NOT NULL, + CONSTRAINT pk_gs_canonical_binding_generation + PRIMARY KEY (tenant_id, playable_state_namespace_id, character_id), + CONSTRAINT chk_gs_canonical_binding_generation_scope CHECK ( + tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND character_id <> '00000000-0000-0000-0000-000000000000'::uuid), + CONSTRAINT chk_gs_canonical_binding_generation_positive CHECK (last_issued_generation >= 0) +); + +CREATE TABLE game_session_canonical_gameplay_binding_inventory ( + binding_ref bytea NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_id uuid NOT NULL, + playable_state_scope character varying(16) NOT NULL, + game_instance_id uuid NOT NULL, + runtime_game_instance_id bigint NOT NULL, + session_id text NOT NULL, + binding_generation numeric NOT NULL, + region_id uuid NOT NULL, + region_epoch numeric NOT NULL, + issuer_id uuid NOT NULL, + issuer_auth_generation numeric NOT NULL, + issuer_index_layout_version numeric NOT NULL, + issuer_index_partition_count numeric NOT NULL, + issuer_index_partition_capacity numeric NOT NULL, + issuer_partition_id numeric NOT NULL, + account_index_fence uuid NOT NULL, + issuer_reservation_id uuid NOT NULL, + transition_id uuid NOT NULL, + lifecycle character varying(24) NOT NULL, + account_index_state character varying(16) NOT NULL, + issuer_index_state character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_gs_canonical_gameplay_binding_inventory_reservation + UNIQUE (issuer_reservation_id), + CONSTRAINT chk_gs_canonical_gameplay_binding_inventory_identity CHECK ( + octet_length(binding_ref) > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND character_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + -- H2's jOOQ DDL parser turns TEXT <> '' into an invalid CLOB(0) cast. The adjacent + -- canonical UUID regex already rejects empty text; PostgreSQL retains this explicit check. + -- [jooq ignore start] + AND session_id <> '' + -- [jooq ignore stop] + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND session_id !~ '^[[:space:]]*$' + AND session_id !~ '[[:cntrl:]]' + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND binding_generation > 0 + AND region_epoch > 0 + AND issuer_auth_generation > 0 + AND issuer_index_layout_version > 0 + AND issuer_index_partition_count > 0 + AND issuer_index_partition_capacity > 0 + AND issuer_partition_id >= 0 + AND issuer_partition_id < issuer_index_partition_count + AND account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND inventory_revision > 0), + CONSTRAINT chk_gs_canonical_gameplay_binding_inventory_state CHECK ( + lifecycle IN ('CANDIDATE_PREPARED', 'PROVISIONAL', 'ACTIVE', 'TERMINAL_UNRESOLVED', 'TERMINAL') + AND account_index_state IN ('REPAIR_REQUIRED', 'ACKNOWLEDGED') + AND issuer_index_state IN ('REPAIR_REQUIRED', 'ACKNOWLEDGED')) +); + +-- H2's jOOQ schema parser maps BYTEA to BLOB and cannot index that type. Keep the +-- PostgreSQL runtime primary key exact while exposing the complete table to generation. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_gameplay_binding_inventory + ADD CONSTRAINT pk_gs_canonical_gameplay_binding_inventory PRIMARY KEY (binding_ref); +-- [jooq ignore stop] + +CREATE UNIQUE INDEX uq_gs_canonical_gameplay_binding_active_controller + ON game_session_canonical_gameplay_binding_inventory + (tenant_id, playable_state_namespace_id, character_id) + WHERE lifecycle = 'ACTIVE'; + +CREATE INDEX ix_gs_canonical_gameplay_binding_inventory_account_revision + ON game_session_canonical_gameplay_binding_inventory (account_id, inventory_revision); + +CREATE INDEX ix_gs_canonical_gameplay_binding_inventory_issuer_revision + ON game_session_canonical_gameplay_binding_inventory (issuer_id, inventory_revision); + +CREATE TABLE game_session_canonical_binding_transition ( + transition_id uuid NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_id uuid NOT NULL, + expected_prior_binding_ref bytea, + expected_prior_binding_generation numeric, + candidate_binding_ref bytea NOT NULL, + candidate_binding_generation numeric NOT NULL, + candidate_account_index_fence uuid NOT NULL, + issuer_reservation_id uuid NOT NULL, + status character varying(24) NOT NULL, + inventory_revision numeric NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_binding_transition PRIMARY KEY (transition_id), + CONSTRAINT chk_gs_canonical_binding_transition_identity CHECK ( + transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND character_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND candidate_binding_generation > 0 + AND candidate_account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND inventory_revision > 0 + AND ((expected_prior_binding_ref IS NULL) = (expected_prior_binding_generation IS NULL)) + AND (expected_prior_binding_generation IS NULL OR expected_prior_binding_generation > 0) + AND status IN ('PREPARED', 'PROVISIONAL', 'COMMITTED', 'ABORTED', 'AMBIGUOUS')) +); + +-- The candidate carrier is byte-exact BYTEA in PostgreSQL; H2's jOOQ parser cannot index or +-- reference its BLOB representation. These constraints remain enforced by the runtime schema. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_binding_transition + ADD CONSTRAINT uq_gs_canonical_binding_transition_candidate UNIQUE (candidate_binding_ref); +ALTER TABLE game_session_canonical_binding_transition + ADD CONSTRAINT fk_gs_canonical_binding_transition_candidate + FOREIGN KEY (candidate_binding_ref) + REFERENCES game_session_canonical_gameplay_binding_inventory (binding_ref); +-- [jooq ignore stop] + +CREATE UNIQUE INDEX uq_gs_canonical_binding_transition_open_controller + ON game_session_canonical_binding_transition + (tenant_id, playable_state_namespace_id, character_id) + WHERE status IN ('PREPARED', 'PROVISIONAL', 'AMBIGUOUS'); + +CREATE TABLE game_session_canonical_binding_account_index_obligation ( + transition_id uuid NOT NULL, + obligation_ordinal integer NOT NULL, + binding_ref bytea NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + action character varying(16) NOT NULL, + binding_generation numeric NOT NULL, + expected_prior_generation numeric, + account_index_fence uuid NOT NULL, + execution_phase character varying(24) NOT NULL, + status character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + CONSTRAINT pk_gs_canonical_binding_account_index_obligation + PRIMARY KEY (transition_id, obligation_ordinal), + CONSTRAINT fk_gs_canonical_binding_account_index_obligation_transition + FOREIGN KEY (transition_id) + REFERENCES game_session_canonical_binding_transition (transition_id), + CONSTRAINT chk_gs_canonical_binding_account_index_obligation CHECK ( + obligation_ordinal >= 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND action IN ('ADD_OR_RETAIN', 'REMOVE') + AND binding_generation > 0 + AND (expected_prior_generation IS NULL OR expected_prior_generation >= 0) + AND account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND execution_phase IN ('BEFORE_FINAL_CAS', 'AFTER_FINAL_CAS') + AND status = 'REQUIRED' + AND inventory_revision > 0) +); + +CREATE TABLE game_session_canonical_issuer_partition_reservation ( + reservation_id uuid NOT NULL, + binding_ref bytea NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + game_instance_id uuid NOT NULL, + runtime_game_instance_id bigint NOT NULL, + session_id text NOT NULL, + binding_generation numeric NOT NULL, + transition_id uuid NOT NULL, + issuer_id uuid NOT NULL, + issuer_auth_generation numeric NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_id uuid NOT NULL, + playable_state_scope character varying(16) NOT NULL, + region_id uuid NOT NULL, + region_epoch numeric NOT NULL, + partition_id numeric NOT NULL, + issuer_index_layout_version numeric NOT NULL, + issuer_index_partition_count numeric NOT NULL, + issuer_index_partition_capacity numeric NOT NULL, + lifecycle character varying(24) NOT NULL, + reservation_fence uuid NOT NULL, + issuer_coverage_operation_id uuid NOT NULL, + issuer_coverage_operation_fence numeric NOT NULL, + coverage_fence numeric NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + inventory_revision numeric NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_issuer_partition_reservation PRIMARY KEY (reservation_id), + CONSTRAINT chk_gs_canonical_issuer_partition_reservation CHECK ( + reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + AND issuer_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND character_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + -- H2's jOOQ DDL parser turns TEXT <> '' into an invalid CLOB(0) cast. The adjacent + -- canonical UUID regex already rejects empty text; PostgreSQL retains this explicit check. + -- [jooq ignore start] + AND session_id <> '' + -- [jooq ignore stop] + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND session_id !~ '^[[:space:]]*$' + AND session_id !~ '[[:cntrl:]]' + AND binding_generation > 0 + AND issuer_auth_generation > 0 + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND region_epoch > 0 + AND partition_id >= 0 + AND issuer_index_layout_version > 0 + AND issuer_index_partition_count > 0 + AND partition_id < issuer_index_partition_count + AND issuer_index_partition_capacity > 0 + AND lifecycle IN ('RESERVED', 'BOUND', 'RELEASE_PENDING', 'RELEASED') + AND reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_coverage_operation_fence > 0 + AND coverage_fence > 0 + AND inventory_snapshot_revision > 0 + AND inventory_revision > 0) +); + +CREATE INDEX ix_gs_canonical_issuer_reservation_partition_revision + ON game_session_canonical_issuer_partition_reservation + (issuer_id, issuer_index_layout_version, partition_id, inventory_revision) + WHERE lifecycle <> 'RELEASED'; + +CREATE TABLE game_session_canonical_binding_issuer_index_obligation ( + transition_id uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + reservation_id uuid NOT NULL, + status character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + CONSTRAINT fk_gs_canonical_binding_issuer_index_obligation_transition + FOREIGN KEY (transition_id) + REFERENCES game_session_canonical_binding_transition (transition_id), + CONSTRAINT fk_gs_canonical_binding_issuer_index_obligation_reservation + FOREIGN KEY (reservation_id) + REFERENCES game_session_canonical_issuer_partition_reservation (reservation_id), + CONSTRAINT chk_gs_canonical_binding_issuer_index_obligation CHECK ( + binding_generation > 0 + AND status = 'REQUIRED' + AND inventory_revision > 0) +); + +-- Preserve the exact composite BYTEA key in PostgreSQL while allowing H2 schema generation. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_binding_issuer_index_obligation + ADD CONSTRAINT pk_gs_canonical_binding_issuer_index_obligation + PRIMARY KEY (transition_id, binding_ref); +-- [jooq ignore stop] + +CREATE TABLE game_session_canonical_binding_region_bridge_obligation ( + transition_id uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + game_instance_id uuid NOT NULL, + runtime_game_instance_id bigint NOT NULL, + session_id text NOT NULL, + region_id uuid NOT NULL, + region_epoch numeric NOT NULL, + status character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + CONSTRAINT pk_gs_canonical_binding_region_bridge_obligation PRIMARY KEY (transition_id), + CONSTRAINT fk_gs_canonical_binding_region_bridge_obligation_transition + FOREIGN KEY (transition_id) + REFERENCES game_session_canonical_binding_transition (transition_id), + CONSTRAINT chk_gs_canonical_binding_region_bridge_obligation CHECK ( + binding_generation > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + -- H2's jOOQ DDL parser turns TEXT <> '' into an invalid CLOB(0) cast. The adjacent + -- canonical UUID regex already rejects empty text; PostgreSQL retains this explicit check. + -- [jooq ignore start] + AND session_id <> '' + -- [jooq ignore stop] + AND session_id ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + AND session_id <> '00000000-0000-0000-0000-000000000000' + AND session_id !~ '^[[:space:]]*$' + AND session_id !~ '[[:cntrl:]]' + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_epoch > 0 + AND status = 'REQUIRED' + AND inventory_revision > 0) +); + +-- No legacy numeric actor ID is joined to a canonical character UUID here. Unmapped legacy +-- evidence remains in its existing owner and admission remains outside this foundation. diff --git a/services/game-session-service/src/main/resources/db/migration/V30__retain_canonical_account_index_projection_readback.sql b/services/game-session-service/src/main/resources/db/migration/V30__retain_canonical_account_index_projection_readback.sql new file mode 100644 index 0000000000..49d401ed3d --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V30__retain_canonical_account_index_projection_readback.sql @@ -0,0 +1,34 @@ +-- Retain exact per-transition Redis projection observations without satisfying the account-index +-- obligation. A v2 accountIndexAcknowledgement still requires the separate account-wide owner +-- operation, complete snapshot, fencing lifecycle, coverage generation, and same-operation proof. +ALTER TABLE game_session_canonical_binding_account_index_obligation + ADD COLUMN projection_state character varying(32) NOT NULL DEFAULT 'REQUIRED', + ADD COLUMN projection_member text, + ADD COLUMN projection_inventory_revision numeric; + +ALTER TABLE game_session_canonical_binding_account_index_obligation + ADD CONSTRAINT chk_gs_canonical_binding_account_index_projection CHECK ( + (projection_state = 'REQUIRED' + AND projection_member IS NULL + AND projection_inventory_revision IS NULL) + OR (projection_state = 'PRESENT_AWAITING_COVERAGE' + AND action = 'ADD_OR_RETAIN' + AND execution_phase = 'BEFORE_FINAL_CAS' + AND status = 'REQUIRED' + AND projection_member IS NOT NULL + AND projection_inventory_revision IS NOT NULL + AND projection_inventory_revision > 0 + AND projection_inventory_revision <= inventory_revision) + OR (projection_state = 'ABSENT_AWAITING_COVERAGE' + AND action = 'REMOVE' + AND execution_phase = 'AFTER_FINAL_CAS' + AND status = 'REQUIRED' + AND projection_member IS NULL + AND projection_inventory_revision IS NOT NULL + AND projection_inventory_revision > 0 + AND projection_inventory_revision <= inventory_revision) + ); + +CREATE INDEX ix_gs_canonical_binding_account_projection_repair + ON game_session_canonical_binding_account_index_obligation + (account_id, projection_state, inventory_revision); diff --git a/services/game-session-service/src/main/resources/db/migration/V31__canonical_account_coverage_fence_snapshot_and_ack.sql b/services/game-session-service/src/main/resources/db/migration/V31__canonical_account_coverage_fence_snapshot_and_ack.sql new file mode 100644 index 0000000000..d13abde71b --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V31__canonical_account_coverage_fence_snapshot_and_ack.sql @@ -0,0 +1,623 @@ +-- Account-wide coverage is a separate durable Game Session owner. Every cohort requires the same +-- complete legacy-index migration receipt; an empty V29 inventory or Redis key is not that receipt. +CREATE TABLE game_session_canonical_binding_legacy_disposition ( + singleton_id smallint NOT NULL, + disposition_state character varying(16) NOT NULL, + cohort_id uuid, + owner_operation_id uuid, + legacy_writer_fence uuid, + source_snapshot_revision numeric, + canonical_inventory_revision numeric, + namespace_index_readback_revision numeric, + evidence_digest character varying(71), + CONSTRAINT pk_gs_canonical_binding_legacy_disposition PRIMARY KEY (singleton_id), + CONSTRAINT chk_gs_canonical_binding_legacy_disposition_singleton CHECK (singleton_id = 1), + CONSTRAINT chk_gs_canonical_binding_legacy_disposition_state CHECK ( + (disposition_state = 'REQUIRED' + AND cohort_id IS NULL + AND owner_operation_id IS NULL + AND legacy_writer_fence IS NULL + AND source_snapshot_revision IS NULL + AND canonical_inventory_revision IS NULL + AND namespace_index_readback_revision IS NULL + AND evidence_digest IS NULL) + OR (disposition_state = 'VERIFIED' + AND cohort_id IS NOT NULL + AND cohort_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND owner_operation_id IS NOT NULL + AND owner_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_writer_fence IS NOT NULL + AND legacy_writer_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_snapshot_revision IS NOT NULL + AND source_snapshot_revision > 0 + AND canonical_inventory_revision IS NOT NULL + AND canonical_inventory_revision > 0 + AND namespace_index_readback_revision IS NOT NULL + AND namespace_index_readback_revision > 0 + AND evidence_digest IS NOT NULL + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$') + ) +); + +INSERT INTO game_session_canonical_binding_legacy_disposition (singleton_id, disposition_state) +VALUES (1, 'REQUIRED'); + +CREATE TABLE game_session_canonical_account_coverage_control ( + account_id uuid NOT NULL, + state character varying(32) NOT NULL, + last_operation_fence numeric NOT NULL, + current_operation_id uuid, + current_operation_fence numeric, + account_admission_fence uuid, + historical_account_admission_fence uuid, + coverage_fence uuid, + inventory_snapshot_revision numeric, + coverage_generation numeric, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_account_coverage_control PRIMARY KEY (account_id), + CONSTRAINT chk_gs_canonical_account_coverage_control_account CHECK ( + account_id <> '00000000-0000-0000-0000-000000000000'::uuid), + CONSTRAINT chk_gs_canonical_account_coverage_control_state CHECK ( + last_operation_fence >= 0 + AND ((state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND current_operation_id IS NULL + AND current_operation_fence IS NULL + AND account_admission_fence IS NULL + AND historical_account_admission_fence IS NULL + AND coverage_fence IS NULL + AND inventory_snapshot_revision IS NULL + AND coverage_generation IS NULL) + OR (state = 'ACTIVE' + AND current_operation_id IS NOT NULL + AND current_operation_fence > 0 + AND current_operation_fence = last_operation_fence + AND account_admission_fence IS NOT NULL + AND account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND historical_account_admission_fence IS NULL + AND coverage_fence IS NOT NULL + AND coverage_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND (inventory_snapshot_revision IS NULL OR inventory_snapshot_revision > 0) + AND coverage_generation IS NULL) + OR (state = 'HISTORICAL' + AND current_operation_id IS NOT NULL + AND current_operation_fence > 0 + AND current_operation_fence = last_operation_fence + AND account_admission_fence IS NULL + AND historical_account_admission_fence IS NOT NULL + AND historical_account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND coverage_fence IS NOT NULL + AND coverage_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND inventory_snapshot_revision > 0 + AND coverage_generation IS NOT NULL + AND coverage_generation > inventory_snapshot_revision)) + ) +); + +CREATE TABLE game_session_canonical_account_coverage_operation ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + account_id uuid NOT NULL, + legacy_cohort_id uuid NOT NULL, + legacy_owner_operation_id uuid NOT NULL, + legacy_writer_fence uuid NOT NULL, + legacy_source_snapshot_revision numeric NOT NULL, + legacy_canonical_inventory_revision numeric NOT NULL, + legacy_namespace_index_readback_revision numeric NOT NULL, + legacy_evidence_digest character varying(71) NOT NULL, + lifecycle character varying(16) NOT NULL, + operation_fence numeric NOT NULL, + coverage_fence uuid NOT NULL, + account_admission_fence uuid, + historical_account_admission_fence uuid, + resolved_scope_kind character varying(24) NOT NULL, + snapshot_state character varying(16) NOT NULL, + blocked_reason character varying(40), + inventory_snapshot_revision numeric, + coverage_generation numeric, + redis_member_count bigint, + redis_member_set_digest character varying(71), + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_account_coverage_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_canonical_account_coverage_request UNIQUE (account_id, request_id), + CONSTRAINT uq_gs_canonical_account_coverage_fence UNIQUE (account_id, operation_fence), + CONSTRAINT fk_gs_canonical_account_coverage_operation_account + FOREIGN KEY (account_id) + REFERENCES game_session_canonical_account_coverage_control (account_id), + CONSTRAINT chk_gs_canonical_account_coverage_operation_identity CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_cohort_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_owner_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_writer_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_source_snapshot_revision > 0 + AND legacy_canonical_inventory_revision > 0 + AND legacy_namespace_index_readback_revision > 0 + AND legacy_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND operation_fence > 0 + AND coverage_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND resolved_scope_kind = 'ACCOUNT_WIDE' + AND ((lifecycle = 'ACTIVE' + AND account_admission_fence IS NOT NULL + AND account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND historical_account_admission_fence IS NULL + AND snapshot_state IN ('COMPLETE', 'BLOCKED') + AND ((snapshot_state = 'COMPLETE' AND blocked_reason IS NULL) + OR (snapshot_state = 'BLOCKED' AND blocked_reason IS NOT NULL)) + AND (inventory_snapshot_revision IS NULL OR inventory_snapshot_revision > 0) + AND coverage_generation IS NULL + AND redis_member_count IS NULL + AND redis_member_set_digest IS NULL) + OR (lifecycle = 'HISTORICAL' + AND account_admission_fence IS NULL + AND historical_account_admission_fence IS NOT NULL + AND historical_account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND snapshot_state = 'COMPLETE' + AND blocked_reason IS NULL + AND inventory_snapshot_revision > 0 + AND coverage_generation IS NOT NULL + AND coverage_generation > inventory_snapshot_revision + AND redis_member_count >= 0 + AND redis_member_set_digest IS NOT NULL + AND redis_member_set_digest ~ '^sha256:[0-9a-f]{64}$')) + ) +); + +ALTER TABLE game_session_canonical_account_coverage_control + ADD CONSTRAINT fk_gs_canonical_account_coverage_control_operation + FOREIGN KEY (current_operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id); + +INSERT INTO game_session_canonical_account_coverage_control ( + account_id, state, last_operation_fence) +SELECT DISTINCT account_id, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0 + FROM game_session_canonical_gameplay_binding_inventory; + +CREATE INDEX ix_gs_canonical_account_coverage_active + ON game_session_canonical_account_coverage_control (state, account_id); + +-- V29/V30 transitions predate this owner and therefore carry the exact typed no-active arm. Future +-- transitions persist the historical account-wide carrier read from the same locked control row. +ALTER TABLE game_session_canonical_binding_transition + ADD COLUMN account_coverage_state character varying(32) NOT NULL + DEFAULT 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', + ADD COLUMN account_coverage_operation_id uuid, + ADD COLUMN account_coverage_lifecycle character varying(16), + ADD COLUMN account_coverage_operation_fence numeric, + ADD COLUMN account_admission_fence_kind character varying(16) NOT NULL + DEFAULT 'NOT_APPLICABLE', + ADD COLUMN account_admission_fence uuid, + ADD COLUMN historical_account_admission_fence_kind character varying(16) NOT NULL + DEFAULT 'NOT_APPLICABLE', + ADD COLUMN historical_account_admission_fence uuid, + ADD COLUMN resolved_scope_kind character varying(24) NOT NULL + DEFAULT 'NOT_APPLICABLE', + ADD COLUMN resolved_scope_account_id uuid, + ADD COLUMN account_coverage_fence uuid, + ADD COLUMN account_coverage_generation numeric, + ADD COLUMN account_inventory_snapshot_revision numeric; + +ALTER TABLE game_session_canonical_binding_transition + ADD CONSTRAINT chk_gs_canonical_binding_transition_account_coverage CHECK ( + (account_coverage_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND account_coverage_operation_id IS NULL + AND account_coverage_lifecycle IS NULL + AND account_coverage_operation_fence IS NULL + AND account_admission_fence_kind = 'NOT_APPLICABLE' + AND account_admission_fence IS NULL + AND historical_account_admission_fence_kind = 'NOT_APPLICABLE' + AND historical_account_admission_fence IS NULL + AND resolved_scope_kind = 'NOT_APPLICABLE' + AND resolved_scope_account_id IS NULL + AND account_coverage_fence IS NULL + AND account_coverage_generation IS NULL + AND account_inventory_snapshot_revision IS NULL) + OR (account_coverage_state = 'HISTORICAL' + AND account_coverage_operation_id IS NOT NULL + AND account_coverage_lifecycle = 'HISTORICAL' + AND account_coverage_operation_fence > 0 + AND account_admission_fence_kind = 'NOT_APPLICABLE' + AND account_admission_fence IS NULL + AND historical_account_admission_fence_kind = 'VALUE' + AND historical_account_admission_fence IS NOT NULL + AND historical_account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND resolved_scope_kind = 'ACCOUNT_WIDE' + AND resolved_scope_account_id IS NOT NULL + AND account_coverage_fence IS NOT NULL + AND account_coverage_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_inventory_snapshot_revision IS NOT NULL + AND account_inventory_snapshot_revision > 0 + AND account_coverage_generation IS NOT NULL + AND account_coverage_generation > account_inventory_snapshot_revision) + ); + +CREATE TABLE game_session_canonical_account_coverage_snapshot_inventory ( + operation_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + binding_ref bytea NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_id uuid NOT NULL, + playable_state_scope character varying(16) NOT NULL, + game_instance_id uuid NOT NULL, + runtime_game_instance_id bigint NOT NULL, + session_id text NOT NULL, + binding_generation numeric NOT NULL, + region_id uuid NOT NULL, + region_epoch numeric NOT NULL, + issuer_id uuid NOT NULL, + issuer_auth_generation numeric NOT NULL, + issuer_index_layout_version numeric NOT NULL, + issuer_index_partition_count numeric NOT NULL, + issuer_index_partition_capacity numeric NOT NULL, + issuer_partition_id numeric NOT NULL, + account_index_fence uuid NOT NULL, + transition_id uuid NOT NULL, + member_transition_id uuid NOT NULL, + lifecycle character varying(24) NOT NULL, + account_index_state character varying(16) NOT NULL, + issuer_index_state character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + action character varying(16) NOT NULL, + exact_member text NOT NULL, + expected_readback_state character varying(16) NOT NULL, + redis_readback_state character varying(16) NOT NULL DEFAULT 'PENDING', + redis_readback_member text, + CONSTRAINT pk_gs_canonical_account_coverage_snapshot_inventory + PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT fk_gs_canonical_account_coverage_snapshot_inventory_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id), + CONSTRAINT chk_gs_canonical_account_coverage_snapshot_inventory CHECK ( + row_ordinal >= 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND character_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_scope IN ('SHARED', 'ISOLATED') + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + AND binding_generation > 0 + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_epoch > 0 + AND issuer_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_auth_generation > 0 + AND issuer_index_layout_version > 0 + AND issuer_index_partition_count > 0 + AND issuer_index_partition_capacity > 0 + AND issuer_partition_id >= 0 + AND issuer_partition_id < issuer_index_partition_count + AND account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND member_transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND inventory_revision > 0 + AND lifecycle IN ( + 'CANDIDATE_PREPARED', 'PROVISIONAL', 'ACTIVE', 'TERMINAL_UNRESOLVED', 'TERMINAL') + AND account_index_state IN ('REPAIR_REQUIRED', 'ACKNOWLEDGED') + AND issuer_index_state IN ('REPAIR_REQUIRED', 'ACKNOWLEDGED') + AND ((action = 'ADD_OR_RETAIN' + AND expected_readback_state = 'PRESENT' + AND ((redis_readback_state = 'PENDING' AND redis_readback_member IS NULL) + OR (redis_readback_state = 'PRESENT' + AND redis_readback_member = exact_member))) + OR (action = 'REMOVE' + AND lifecycle = 'TERMINAL' + AND expected_readback_state = 'ABSENT' + AND ((redis_readback_state = 'PENDING' AND redis_readback_member IS NULL) + OR (redis_readback_state = 'ABSENT' AND redis_readback_member IS NULL))) + OR (action = 'BLOCKED' + AND expected_readback_state = 'BLOCKED' + AND redis_readback_state = 'PENDING' + AND redis_readback_member IS NULL))) +); + +CREATE TABLE game_session_canonical_account_coverage_snapshot_transition ( + operation_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + transition_id uuid NOT NULL, + candidate_binding_ref bytea NOT NULL, + expected_prior_binding_ref bytea, + expected_prior_binding_generation numeric, + candidate_binding_generation numeric NOT NULL, + candidate_account_index_fence uuid NOT NULL, + issuer_reservation_id uuid NOT NULL, + status character varying(24) NOT NULL, + inventory_revision numeric NOT NULL, + candidate_account_id uuid NOT NULL, + candidate_tenant_id uuid NOT NULL, + candidate_namespace_id uuid NOT NULL, + candidate_character_id uuid NOT NULL, + candidate_playable_state_scope character varying(16) NOT NULL, + candidate_game_instance_id uuid NOT NULL, + candidate_runtime_game_instance_id bigint NOT NULL, + candidate_session_id text NOT NULL, + candidate_region_id uuid NOT NULL, + candidate_region_epoch numeric NOT NULL, + candidate_issuer_id uuid NOT NULL, + candidate_issuer_auth_generation numeric NOT NULL, + candidate_issuer_index_layout_version numeric NOT NULL, + candidate_issuer_index_partition_count numeric NOT NULL, + candidate_issuer_index_partition_capacity numeric NOT NULL, + account_coverage_state character varying(32) NOT NULL, + account_coverage_operation_id uuid, + account_coverage_lifecycle character varying(16), + account_coverage_operation_fence numeric, + account_admission_fence_kind character varying(16) NOT NULL, + account_admission_fence uuid, + historical_account_admission_fence_kind character varying(16) NOT NULL, + historical_account_admission_fence uuid, + resolved_scope_kind character varying(24) NOT NULL, + resolved_scope_account_id uuid, + coverage_fence uuid, + coverage_generation numeric, + account_inventory_snapshot_revision numeric, + CONSTRAINT pk_gs_canonical_account_coverage_snapshot_transition + PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT fk_gs_canonical_account_coverage_snapshot_transition_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id), + CONSTRAINT chk_gs_canonical_account_coverage_snapshot_transition CHECK ( + row_ordinal >= 0 + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND candidate_binding_generation > 0 + AND candidate_account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND inventory_revision > 0 + AND ((account_coverage_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND account_coverage_operation_id IS NULL + AND account_coverage_lifecycle IS NULL + AND account_coverage_operation_fence IS NULL + AND account_admission_fence_kind = 'NOT_APPLICABLE' + AND account_admission_fence IS NULL + AND historical_account_admission_fence_kind = 'NOT_APPLICABLE' + AND historical_account_admission_fence IS NULL + AND resolved_scope_kind = 'NOT_APPLICABLE' + AND resolved_scope_account_id IS NULL + AND coverage_fence IS NULL + AND coverage_generation IS NULL + AND account_inventory_snapshot_revision IS NULL) + OR (account_coverage_state = 'HISTORICAL' + AND account_coverage_operation_id IS NOT NULL + AND account_coverage_lifecycle = 'HISTORICAL' + AND account_coverage_operation_fence > 0 + AND account_admission_fence_kind = 'NOT_APPLICABLE' + AND account_admission_fence IS NULL + AND historical_account_admission_fence_kind = 'VALUE' + AND historical_account_admission_fence IS NOT NULL + AND resolved_scope_kind = 'ACCOUNT_WIDE' + AND resolved_scope_account_id IS NOT NULL + AND coverage_fence IS NOT NULL + AND coverage_generation IS NOT NULL + AND coverage_generation > account_inventory_snapshot_revision + AND account_inventory_snapshot_revision IS NOT NULL + AND account_inventory_snapshot_revision > 0)) + ) +); + +CREATE TABLE game_session_canonical_account_coverage_snapshot_obligation ( + operation_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + transition_id uuid NOT NULL, + obligation_ordinal integer NOT NULL, + binding_ref bytea NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + action character varying(16) NOT NULL, + binding_generation numeric NOT NULL, + expected_prior_generation numeric, + account_index_fence uuid NOT NULL, + execution_phase character varying(24) NOT NULL, + status character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + projection_state character varying(32) NOT NULL, + projection_member text, + projection_inventory_revision numeric, + binding_lifecycle character varying(24) NOT NULL, + transition_status character varying(24) NOT NULL, + expected_readback_state character varying(16) NOT NULL, + exact_member text, + redis_readback_state character varying(16) NOT NULL DEFAULT 'PENDING', + redis_readback_member text, + CONSTRAINT pk_gs_canonical_account_coverage_snapshot_obligation + PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT fk_gs_canonical_account_coverage_snapshot_obligation_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id), + CONSTRAINT chk_gs_canonical_account_coverage_snapshot_obligation CHECK ( + row_ordinal >= 0 + AND obligation_ordinal >= 0 + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND binding_generation > 0 + AND account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND status = 'REQUIRED' + AND inventory_revision > 0 + AND expected_readback_state IN ('PRESENT', 'ABSENT', 'BLOCKED') + AND ((redis_readback_state = 'PENDING' AND redis_readback_member IS NULL) + OR (redis_readback_state = 'PRESENT' AND redis_readback_member IS NOT NULL) + OR (redis_readback_state = 'ABSENT' AND redis_readback_member IS NULL))) +); + +CREATE TABLE game_session_canonical_account_coverage_snapshot_reservation ( + operation_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + reservation_id uuid NOT NULL, + binding_ref bytea NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + binding_generation numeric NOT NULL, + transition_id uuid NOT NULL, + issuer_id uuid NOT NULL, + issuer_auth_generation numeric NOT NULL, + playable_state_namespace_id uuid NOT NULL, + character_id uuid NOT NULL, + playable_state_scope character varying(16) NOT NULL, + game_instance_id uuid NOT NULL, + runtime_game_instance_id bigint NOT NULL, + session_id text NOT NULL, + region_id uuid NOT NULL, + region_epoch numeric NOT NULL, + partition_id numeric NOT NULL, + issuer_index_layout_version numeric NOT NULL, + issuer_index_partition_count numeric NOT NULL, + issuer_index_partition_capacity numeric NOT NULL, + lifecycle character varying(24) NOT NULL, + reservation_fence uuid NOT NULL, + issuer_coverage_operation_id uuid NOT NULL, + issuer_coverage_operation_fence numeric NOT NULL, + coverage_fence numeric NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + inventory_revision numeric NOT NULL, + CONSTRAINT pk_gs_canonical_account_coverage_snapshot_reservation + PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT fk_gs_canonical_account_coverage_snapshot_reservation_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id), + CONSTRAINT chk_gs_canonical_account_coverage_snapshot_reservation CHECK ( + row_ordinal >= 0 + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND binding_generation > 0 + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND character_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_auth_generation > 0 + AND region_epoch > 0 + AND partition_id >= 0 + AND partition_id < issuer_index_partition_count + AND issuer_index_layout_version > 0 + AND issuer_index_partition_count > 0 + AND issuer_index_partition_capacity > 0 + AND reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND issuer_coverage_operation_fence > 0 + AND coverage_fence > 0 + AND inventory_snapshot_revision > 0 + AND inventory_revision > 0) +); + +CREATE TABLE game_session_canonical_account_coverage_snapshot_issuer_obligation ( + operation_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + transition_id uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + reservation_id uuid NOT NULL, + status character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + CONSTRAINT pk_gs_canonical_account_coverage_snapshot_issuer_obligation + PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT fk_gs_canonical_account_coverage_snapshot_issuer_obligation_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id), + CONSTRAINT chk_gs_canonical_account_coverage_snapshot_issuer_obligation CHECK ( + row_ordinal >= 0 + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND binding_generation > 0 + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND status = 'REQUIRED' + AND inventory_revision > 0) +); + +CREATE TABLE game_session_canonical_account_coverage_snapshot_region_obligation ( + operation_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + transition_id uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + game_instance_id uuid NOT NULL, + runtime_game_instance_id bigint NOT NULL, + session_id text NOT NULL, + region_id uuid NOT NULL, + region_epoch numeric NOT NULL, + status character varying(16) NOT NULL, + inventory_revision numeric NOT NULL, + CONSTRAINT pk_gs_canonical_account_coverage_snapshot_region_obligation + PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT fk_gs_canonical_account_coverage_snapshot_region_obligation_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id), + CONSTRAINT chk_gs_canonical_account_coverage_snapshot_region_obligation CHECK ( + row_ordinal >= 0 + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND binding_generation > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND runtime_game_instance_id > 0 + AND region_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND region_epoch > 0 + AND status = 'REQUIRED' + AND inventory_revision > 0) +); + +CREATE TABLE game_session_canonical_account_index_acknowledgement ( + operation_id uuid NOT NULL, + member_ordinal bigint NOT NULL, + schema_version integer NOT NULL, + account_coverage_state character varying(32) NOT NULL, + account_coverage_operation_id uuid NOT NULL, + account_coverage_lifecycle character varying(16) NOT NULL, + account_coverage_operation_fence numeric NOT NULL, + account_admission_fence_kind character varying(16) NOT NULL, + account_admission_fence uuid, + historical_account_admission_fence_kind character varying(16) NOT NULL, + historical_account_admission_fence uuid NOT NULL, + resolved_scope_kind character varying(24) NOT NULL, + resolved_scope_account_id uuid NOT NULL, + transition_id uuid NOT NULL, + binding_ref bytea NOT NULL, + account_id uuid NOT NULL, + tenant_id uuid NOT NULL, + binding_generation numeric NOT NULL, + account_index_fence uuid NOT NULL, + operation_fence numeric NOT NULL, + coverage_fence uuid NOT NULL, + coverage_generation numeric NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + action character varying(16) NOT NULL, + readback_state character varying(16) NOT NULL, + readback_member text, + CONSTRAINT pk_gs_canonical_account_index_acknowledgement + PRIMARY KEY (operation_id, member_ordinal), + CONSTRAINT fk_gs_canonical_account_index_acknowledgement_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_account_coverage_operation (operation_id), + CONSTRAINT chk_gs_canonical_account_index_acknowledgement CHECK ( + member_ordinal >= 0 + AND schema_version = 2 + AND account_coverage_state = 'HISTORICAL' + AND account_coverage_operation_id = operation_id + AND account_coverage_lifecycle = 'HISTORICAL' + AND account_coverage_operation_fence = operation_fence + AND account_coverage_operation_fence > 0 + AND account_admission_fence_kind = 'NOT_APPLICABLE' + AND account_admission_fence IS NULL + AND historical_account_admission_fence_kind = 'VALUE' + AND historical_account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND resolved_scope_kind = 'ACCOUNT_WIDE' + AND resolved_scope_account_id = account_id + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND binding_generation > 0 + AND account_index_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND coverage_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND coverage_generation > inventory_snapshot_revision + AND inventory_snapshot_revision > 0 + AND ((action = 'ADD_OR_RETAIN' + AND readback_state = 'PRESENT' + AND readback_member IS NOT NULL) + OR (action = 'REMOVE' + AND readback_state = 'ABSENT' + AND readback_member IS NULL))) +); diff --git a/services/game-session-service/src/main/resources/db/migration/V32__canonical_gameplay_admission_decision.sql b/services/game-session-service/src/main/resources/db/migration/V32__canonical_gameplay_admission_decision.sql new file mode 100644 index 0000000000..b7663d3fbd --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V32__canonical_gameplay_admission_decision.sql @@ -0,0 +1,175 @@ +-- A lease-bound decision is the existing binding transition plus immutable Account lease and +-- point-in-time current route evidence. This is not a second decision ledger or an admission. +ALTER TABLE game_session_canonical_binding_transition + ADD COLUMN admission_request_id uuid, + ADD COLUMN admission_lease_id uuid, + ADD COLUMN admission_lease_fence numeric, + ADD COLUMN admission_lease_kind character varying(16), + ADD COLUMN admission_lease_digest character varying(64), + ADD COLUMN admission_lease_evidence text, + ADD COLUMN admission_resume_episode_id uuid, + ADD COLUMN admission_expected_old_binding_generation numeric, + ADD COLUMN admission_lease_expires_at numeric, + ADD COLUMN admission_target_namespace text, + ADD COLUMN admission_target_tenant_slug text, + ADD COLUMN admission_target_tenant_id uuid, + ADD COLUMN admission_target_world_slug text, + ADD COLUMN admission_target_world_display_name text, + ADD COLUMN admission_target_realm_id uuid, + ADD COLUMN admission_target_realm_slug text, + ADD COLUMN admission_target_realm_display_name text, + ADD COLUMN admission_target_game_session_tenant_id bigint, + ADD COLUMN admission_target_game_instance_id bigint, + ADD COLUMN admission_target_playable_state_namespace_id uuid, + ADD COLUMN admission_target_playable_state_scope character varying(16), + ADD COLUMN admission_target_canonical_game_instance_id uuid, + ADD COLUMN admission_target_canonical_version_id uuid, + ADD COLUMN admission_target_runtime_version_id bigint, + ADD COLUMN admission_target_catalog_revision bigint, + ADD COLUMN admission_target_pointer_version bigint, + ADD COLUMN admission_target_pointer_snapshot_digest character varying(64), + ADD COLUMN admission_target_active_world_epoch bigint, + ADD COLUMN admission_target_initial_admission_request_id text, + ADD COLUMN admission_target_initial_admission_request_digest character varying(64), + ADD COLUMN admission_target_origin_kind character varying(24), + ADD COLUMN admission_target_expected_prior_pointer_version bigint, + ADD COLUMN admission_target_hold_id uuid, + ADD COLUMN admission_target_hold_fence uuid, + ADD COLUMN admission_target_hold_binding_digest character varying(71), + ADD COLUMN admission_target_audit_event_id bigint, + ADD COLUMN admission_target_owner_proof_digest character varying(71), + ADD COLUMN admission_target_owner_proof_outcome character varying(16), + ADD COLUMN admission_target_positive_durable_abort boolean, + ADD COLUMN admission_target_terminal_at timestamp with time zone, + ADD COLUMN admission_target_character_creation_policy text; + +ALTER TABLE game_session_canonical_binding_transition + ADD CONSTRAINT chk_gs_canonical_binding_transition_admission_decision CHECK ( + (admission_request_id IS NULL + AND admission_lease_id IS NULL + AND admission_lease_fence IS NULL + AND admission_lease_kind IS NULL + AND admission_lease_digest IS NULL + AND admission_lease_evidence IS NULL + AND admission_resume_episode_id IS NULL + AND admission_expected_old_binding_generation IS NULL + AND admission_lease_expires_at IS NULL + AND admission_target_namespace IS NULL + AND admission_target_tenant_slug IS NULL + AND admission_target_tenant_id IS NULL + AND admission_target_world_slug IS NULL + AND admission_target_world_display_name IS NULL + AND admission_target_realm_id IS NULL + AND admission_target_realm_slug IS NULL + AND admission_target_realm_display_name IS NULL + AND admission_target_game_session_tenant_id IS NULL + AND admission_target_game_instance_id IS NULL + AND admission_target_playable_state_namespace_id IS NULL + AND admission_target_playable_state_scope IS NULL + AND admission_target_canonical_game_instance_id IS NULL + AND admission_target_canonical_version_id IS NULL + AND admission_target_runtime_version_id IS NULL + AND admission_target_catalog_revision IS NULL + AND admission_target_pointer_version IS NULL + AND admission_target_pointer_snapshot_digest IS NULL + AND admission_target_active_world_epoch IS NULL + AND admission_target_initial_admission_request_id IS NULL + AND admission_target_initial_admission_request_digest IS NULL + AND admission_target_origin_kind IS NULL + AND admission_target_expected_prior_pointer_version IS NULL + AND admission_target_hold_id IS NULL + AND admission_target_hold_fence IS NULL + AND admission_target_hold_binding_digest IS NULL + AND admission_target_audit_event_id IS NULL + AND admission_target_owner_proof_digest IS NULL + AND admission_target_owner_proof_outcome IS NULL + AND admission_target_positive_durable_abort IS NULL + AND admission_target_terminal_at IS NULL + AND admission_target_character_creation_policy IS NULL) + OR (admission_request_id IS NOT NULL + AND admission_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND admission_lease_id IS NOT NULL + AND admission_lease_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND admission_lease_fence IS NOT NULL + AND admission_lease_fence > 0 + AND admission_lease_kind IS NOT NULL + AND admission_lease_kind IN ('NEW_BINDING', 'RESUME') + AND admission_lease_digest IS NOT NULL + AND admission_lease_digest ~ '^[0-9a-f]{64}$' + AND admission_lease_evidence IS NOT NULL + AND octet_length(admission_lease_evidence) <= 65536 + AND admission_lease_expires_at IS NOT NULL + AND admission_lease_expires_at > 0 + AND ((admission_lease_kind = 'RESUME' + AND admission_resume_episode_id IS NOT NULL + AND admission_resume_episode_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND admission_expected_old_binding_generation IS NOT NULL + AND admission_expected_old_binding_generation > 0) + OR (admission_lease_kind = 'NEW_BINDING' + AND admission_resume_episode_id IS NULL + AND (admission_expected_old_binding_generation IS NULL + OR admission_expected_old_binding_generation > 0))) + AND admission_target_namespace IS NOT NULL + AND admission_target_tenant_slug IS NOT NULL + AND admission_target_tenant_id IS NOT NULL + AND admission_target_tenant_id = tenant_id + AND admission_target_world_slug IS NOT NULL + AND admission_target_world_display_name IS NOT NULL + AND admission_target_realm_id IS NOT NULL + AND admission_target_realm_slug IS NOT NULL + AND admission_target_realm_display_name IS NOT NULL + AND admission_target_game_session_tenant_id IS NOT NULL + AND admission_target_game_session_tenant_id > 0 + AND admission_target_game_instance_id IS NOT NULL + AND admission_target_game_instance_id > 0 + AND admission_target_playable_state_namespace_id IS NOT NULL + AND admission_target_playable_state_namespace_id = playable_state_namespace_id + AND admission_target_playable_state_scope IS NOT NULL + AND admission_target_playable_state_scope IN ('SHARED', 'ISOLATED') + AND admission_target_canonical_game_instance_id IS NOT NULL + AND admission_target_canonical_version_id IS NOT NULL + AND admission_target_runtime_version_id IS NOT NULL + AND admission_target_runtime_version_id > 0 + AND admission_target_catalog_revision IS NOT NULL + AND admission_target_catalog_revision > 0 + AND admission_target_pointer_version IS NOT NULL + AND admission_target_pointer_version > 0 + AND admission_target_pointer_snapshot_digest IS NOT NULL + AND admission_target_pointer_snapshot_digest ~ '^[0-9a-f]{64}$' + AND admission_target_active_world_epoch IS NOT NULL + AND admission_target_active_world_epoch > 0 + AND admission_target_initial_admission_request_id IS NOT NULL + AND admission_target_initial_admission_request_digest IS NOT NULL + AND admission_target_initial_admission_request_digest ~ '^[0-9a-f]{64}$' + AND admission_target_origin_kind IS NOT NULL + AND admission_target_origin_kind IN ('NO_PRIOR_POINTER', 'EXPECT_CLOSED') + AND ((admission_target_origin_kind = 'NO_PRIOR_POINTER' + AND admission_target_expected_prior_pointer_version IS NULL) + OR (admission_target_origin_kind = 'EXPECT_CLOSED' + AND admission_target_expected_prior_pointer_version IS NOT NULL + AND admission_target_expected_prior_pointer_version > 0)) + AND admission_target_hold_id IS NOT NULL + AND admission_target_hold_fence IS NOT NULL + AND admission_target_hold_binding_digest IS NOT NULL + AND admission_target_hold_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND admission_target_audit_event_id IS NOT NULL + AND admission_target_audit_event_id > 0 + AND admission_target_owner_proof_digest IS NOT NULL + AND admission_target_owner_proof_digest ~ '^sha256:[0-9a-f]{64}$' + AND admission_target_owner_proof_outcome IS NOT NULL + AND admission_target_owner_proof_outcome = 'COMMITTED' + AND admission_target_positive_durable_abort IS NOT NULL + AND admission_target_positive_durable_abort = FALSE + AND admission_target_terminal_at IS NOT NULL + AND admission_target_character_creation_policy IS NOT NULL + AND length(admission_target_character_creation_policy) > 0 + AND status IN ('PROVISIONAL', 'COMMITTED', 'ABORTED', 'AMBIGUOUS')) + ); + +CREATE UNIQUE INDEX uq_gs_canonical_binding_admission_request + ON game_session_canonical_binding_transition (admission_request_id) + WHERE admission_request_id IS NOT NULL; + +CREATE UNIQUE INDEX uq_gs_canonical_binding_admission_lease + ON game_session_canonical_binding_transition (admission_lease_id) + WHERE admission_lease_id IS NOT NULL; diff --git a/services/game-session-service/src/main/resources/db/migration/V33__canonical_legacy_binding_migration_operation.sql b/services/game-session-service/src/main/resources/db/migration/V33__canonical_legacy_binding_migration_operation.sql new file mode 100644 index 0000000000..86390d3311 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V33__canonical_legacy_binding_migration_operation.sql @@ -0,0 +1,191 @@ +-- Durable, replayable owner-operation state for the legacy controller-index migration. +-- This migration deliberately leaves V31 REQUIRED; only the fenced Game Session owner operation +-- may publish VERIFIED after complete source capture, rebuild, and exact readback. +CREATE SEQUENCE game_session_canonical_legacy_migration_source_revision_seq START WITH 1; +CREATE SEQUENCE game_session_canonical_legacy_migration_readback_revision_seq START WITH 1; + +CREATE TABLE game_session_canonical_legacy_migration_operation ( + operation_id uuid NOT NULL, + cohort_id uuid NOT NULL, + legacy_writer_fence uuid NOT NULL, + state character varying(24) NOT NULL, + kubernetes_cluster_uid text NOT NULL, + kubernetes_namespace_uid text NOT NULL, + producer_pod_uid text NOT NULL, + producer_container_id text NOT NULL, + producer_node_uid text NOT NULL, + postgres_system_identifier numeric(20, 0) NOT NULL, + postgres_database_oid bigint NOT NULL, + postgres_storage_uid text NOT NULL, + redis_run_id text NOT NULL, + redis_storage_uid text NOT NULL, + storage_identity_digest character varying(71) NOT NULL, + source_snapshot_revision numeric, + source_snapshot_digest character varying(71), + source_snapshot_entry_count bigint, + source_snapshot_families jsonb, + canonical_snapshot_revision numeric, + canonical_snapshot_digest character varying(71), + canonical_snapshot jsonb, + rebuild_digest character varying(71), + namespace_index_readback_revision numeric, + namespace_index_readback_digest character varying(71), + publication_inventory_revision numeric, + evidence_digest character varying(71), + blocked_reason character varying(48), + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_legacy_migration_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_canonical_legacy_migration_cohort UNIQUE (cohort_id), + CONSTRAINT chk_gs_canonical_legacy_migration_identity CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND cohort_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND legacy_writer_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND postgres_system_identifier > 0 + AND postgres_database_oid > 0 + AND postgres_database_oid <= 4294967295 + AND length(kubernetes_cluster_uid) > 0 + AND length(kubernetes_namespace_uid) > 0 + AND length(producer_pod_uid) > 0 + AND length(producer_container_id) > 0 + AND length(producer_node_uid) > 0 + AND length(postgres_storage_uid) > 0 + AND length(redis_run_id) > 0 + AND length(redis_storage_uid) > 0 + AND storage_identity_digest ~ '^sha256:[0-9a-f]{64}$'), + CONSTRAINT chk_gs_canonical_legacy_migration_state CHECK ( + (state = 'FENCED' + AND source_snapshot_revision IS NULL + AND source_snapshot_digest IS NULL + AND source_snapshot_entry_count IS NULL + AND source_snapshot_families IS NULL + AND canonical_snapshot_revision IS NULL + AND canonical_snapshot_digest IS NULL + AND canonical_snapshot IS NULL + AND rebuild_digest IS NULL + AND namespace_index_readback_revision IS NULL + AND namespace_index_readback_digest IS NULL + AND publication_inventory_revision IS NULL + AND evidence_digest IS NULL + AND blocked_reason IS NULL) + OR (state = 'SNAPSHOTTED' + AND source_snapshot_revision > 0 + AND source_snapshot_revision IS NOT NULL + AND source_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_snapshot_digest IS NOT NULL + AND source_snapshot_entry_count >= 0 + AND source_snapshot_entry_count IS NOT NULL + AND source_snapshot_families IS NOT NULL + AND jsonb_typeof(source_snapshot_families) = 'array' + AND canonical_snapshot_revision >= 0 + AND canonical_snapshot_revision IS NOT NULL + AND canonical_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND canonical_snapshot_digest IS NOT NULL + AND canonical_snapshot IS NOT NULL + AND rebuild_digest IS NULL + AND namespace_index_readback_revision IS NULL + AND namespace_index_readback_digest IS NULL + AND publication_inventory_revision IS NULL + AND evidence_digest IS NULL + AND blocked_reason IS NULL) + OR (state = 'REBUILT' + AND source_snapshot_revision > 0 + AND source_snapshot_revision IS NOT NULL + AND source_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_snapshot_digest IS NOT NULL + AND source_snapshot_entry_count >= 0 + AND source_snapshot_entry_count IS NOT NULL + AND source_snapshot_families IS NOT NULL + AND jsonb_typeof(source_snapshot_families) = 'array' + AND canonical_snapshot_revision >= 0 + AND canonical_snapshot_revision IS NOT NULL + AND canonical_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND canonical_snapshot_digest IS NOT NULL + AND canonical_snapshot IS NOT NULL + AND rebuild_digest ~ '^sha256:[0-9a-f]{64}$' + AND rebuild_digest IS NOT NULL + AND namespace_index_readback_revision IS NULL + AND namespace_index_readback_digest IS NULL + AND publication_inventory_revision IS NULL + AND evidence_digest IS NULL + AND blocked_reason IS NULL) + OR (state = 'READBACK_VERIFIED' + AND source_snapshot_revision > 0 + AND source_snapshot_revision IS NOT NULL + AND source_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_snapshot_digest IS NOT NULL + AND source_snapshot_entry_count >= 0 + AND source_snapshot_entry_count IS NOT NULL + AND source_snapshot_families IS NOT NULL + AND jsonb_typeof(source_snapshot_families) = 'array' + AND canonical_snapshot_revision >= 0 + AND canonical_snapshot_revision IS NOT NULL + AND canonical_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND canonical_snapshot_digest IS NOT NULL + AND canonical_snapshot IS NOT NULL + AND rebuild_digest ~ '^sha256:[0-9a-f]{64}$' + AND rebuild_digest IS NOT NULL + AND namespace_index_readback_revision > 0 + AND namespace_index_readback_revision IS NOT NULL + AND namespace_index_readback_digest ~ '^sha256:[0-9a-f]{64}$' + AND namespace_index_readback_digest IS NOT NULL + AND publication_inventory_revision IS NULL + AND evidence_digest IS NULL + AND blocked_reason IS NULL) + OR (state = 'VERIFIED' + AND source_snapshot_revision > 0 + AND source_snapshot_revision IS NOT NULL + AND source_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_snapshot_digest IS NOT NULL + AND source_snapshot_entry_count >= 0 + AND source_snapshot_entry_count IS NOT NULL + AND source_snapshot_families IS NOT NULL + AND jsonb_typeof(source_snapshot_families) = 'array' + AND canonical_snapshot_revision >= 0 + AND canonical_snapshot_revision IS NOT NULL + AND canonical_snapshot_digest ~ '^sha256:[0-9a-f]{64}$' + AND canonical_snapshot_digest IS NOT NULL + AND canonical_snapshot IS NOT NULL + AND rebuild_digest ~ '^sha256:[0-9a-f]{64}$' + AND rebuild_digest IS NOT NULL + AND namespace_index_readback_revision > 0 + AND namespace_index_readback_revision IS NOT NULL + AND namespace_index_readback_digest ~ '^sha256:[0-9a-f]{64}$' + AND namespace_index_readback_digest IS NOT NULL + AND publication_inventory_revision > 0 + AND publication_inventory_revision IS NOT NULL + AND evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND evidence_digest IS NOT NULL + AND blocked_reason IS NULL) + OR (state = 'BLOCKED' + AND blocked_reason IS NOT NULL + AND length(blocked_reason) > 0)) +); + +CREATE TABLE game_session_canonical_legacy_migration_source_snapshot_entry ( + operation_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + source_family character varying(40) NOT NULL, + source_key_digest character varying(71) NOT NULL, + disposition character varying(32) NOT NULL, + CONSTRAINT pk_gs_canonical_legacy_migration_source_entry + PRIMARY KEY (operation_id, row_ordinal), + CONSTRAINT uq_gs_canonical_legacy_migration_source_key + UNIQUE (operation_id, source_key_digest), + CONSTRAINT fk_gs_canonical_legacy_migration_source_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_legacy_migration_operation (operation_id), + CONSTRAINT chk_gs_canonical_legacy_migration_source_entry CHECK ( + row_ordinal >= 0 + AND source_family IN ( + 'TENANT_SESSION_CONTEXT', 'SESSION_ALIAS_CONTEXT', + 'GAMEPLAY_IDENTITY_CONTEXT', 'GAMEPLAY_NAME_CONTEXT', + 'MOVEMENT_EFFECT', 'DURABLE_EFFECT', 'UNCLASSIFIED') + AND source_key_digest ~ '^sha256:[0-9a-f]{64}$' + AND disposition IN ('UNMAPPABLE', 'CREDENTIAL_BEARING', 'UNKNOWN')) +); + +CREATE INDEX ix_gs_canonical_legacy_migration_state + ON game_session_canonical_legacy_migration_operation (state, cohort_id); + +-- The V31 singleton remains REQUIRED. No migration, fixture, or empty query seeds VERIFIED. diff --git a/services/game-session-service/src/main/resources/db/migration/V34.1__canonical_gameplay_integrity_guards.sql b/services/game-session-service/src/main/resources/db/migration/V34.1__canonical_gameplay_integrity_guards.sql new file mode 100644 index 0000000000..1094a56972 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V34.1__canonical_gameplay_integrity_guards.sql @@ -0,0 +1,268 @@ +-- Preserve the complete V34 launch/runtime decision fence and also require its exact candidate +-- inventory row to name the same canonical tenant and runtime identity. +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT uq_gs_canonical_realm_catalog_launch_identity + UNIQUE (target_namespace, canonical_tenant_id, realm_id, creation_request_id, catalog_revision, + source_intake_operation_id, source_intake_request_id); + +ALTER TABLE game_session_canonical_launch_preparation + DROP CONSTRAINT fk_gs_canonical_launch_preparation_catalog; + +ALTER TABLE game_session_canonical_launch_preparation + ADD CONSTRAINT fk_gs_canonical_launch_preparation_catalog + FOREIGN KEY (target_namespace, canonical_tenant_id, realm_id, catalog_creation_request_id, + catalog_revision, source_intake_operation_id, source_intake_request_id) + REFERENCES game_session_canonical_realm_catalog + (target_namespace, canonical_tenant_id, realm_id, creation_request_id, catalog_revision, + source_intake_operation_id, source_intake_request_id); + +CREATE INDEX ix_gs_canonical_binding_inventory_runtime_identity + ON game_session_canonical_gameplay_binding_inventory + (tenant_id, runtime_game_instance_id, game_instance_id); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_running_runtime_for_lease_bound_binding_decision() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from an existing PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL THEN + IF NEW.status NOT IN ('PROVISIONAL', 'AMBIGUOUS') + OR (OLD.status = 'AMBIGUOUS' AND NEW.status <> 'AMBIGUOUS') THEN + RAISE EXCEPTION 'A lease-bound runtime fence cannot be released without terminal owner reconciliation' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_terminal_owner_required'; + END IF; + + IF ROW( + NEW.admission_request_id, + NEW.admission_lease_id, + NEW.admission_lease_fence, + NEW.admission_lease_kind, + NEW.admission_lease_digest, + NEW.admission_lease_evidence, + NEW.admission_resume_episode_id, + NEW.admission_expected_old_binding_generation, + NEW.admission_lease_expires_at, + NEW.admission_target_namespace, + NEW.admission_target_tenant_slug, + NEW.admission_target_tenant_id, + NEW.admission_target_world_slug, + NEW.admission_target_world_display_name, + NEW.admission_target_realm_id, + NEW.admission_target_realm_slug, + NEW.admission_target_realm_display_name, + NEW.admission_target_game_session_tenant_id, + NEW.admission_target_game_instance_id, + NEW.admission_target_playable_state_namespace_id, + NEW.admission_target_playable_state_scope, + NEW.admission_target_canonical_game_instance_id, + NEW.admission_target_canonical_version_id, + NEW.admission_target_runtime_version_id, + NEW.admission_target_catalog_revision, + NEW.admission_target_pointer_version, + NEW.admission_target_pointer_snapshot_digest, + NEW.admission_target_active_world_epoch, + NEW.admission_target_initial_admission_request_id, + NEW.admission_target_initial_admission_request_digest, + NEW.admission_target_origin_kind, + NEW.admission_target_expected_prior_pointer_version, + NEW.admission_target_hold_id, + NEW.admission_target_hold_fence, + NEW.admission_target_hold_binding_digest, + NEW.admission_target_audit_event_id, + NEW.admission_target_owner_proof_digest, + NEW.admission_target_owner_proof_outcome, + NEW.admission_target_positive_durable_abort, + NEW.admission_target_terminal_at, + NEW.admission_target_character_creation_policy + ) IS DISTINCT FROM ROW( + OLD.admission_request_id, + OLD.admission_lease_id, + OLD.admission_lease_fence, + OLD.admission_lease_kind, + OLD.admission_lease_digest, + OLD.admission_lease_evidence, + OLD.admission_resume_episode_id, + OLD.admission_expected_old_binding_generation, + OLD.admission_lease_expires_at, + OLD.admission_target_namespace, + OLD.admission_target_tenant_slug, + OLD.admission_target_tenant_id, + OLD.admission_target_world_slug, + OLD.admission_target_world_display_name, + OLD.admission_target_realm_id, + OLD.admission_target_realm_slug, + OLD.admission_target_realm_display_name, + OLD.admission_target_game_session_tenant_id, + OLD.admission_target_game_instance_id, + OLD.admission_target_playable_state_namespace_id, + OLD.admission_target_playable_state_scope, + OLD.admission_target_canonical_game_instance_id, + OLD.admission_target_canonical_version_id, + OLD.admission_target_runtime_version_id, + OLD.admission_target_catalog_revision, + OLD.admission_target_pointer_version, + OLD.admission_target_pointer_snapshot_digest, + OLD.admission_target_active_world_epoch, + OLD.admission_target_initial_admission_request_id, + OLD.admission_target_initial_admission_request_digest, + OLD.admission_target_origin_kind, + OLD.admission_target_expected_prior_pointer_version, + OLD.admission_target_hold_id, + OLD.admission_target_hold_fence, + OLD.admission_target_hold_binding_digest, + OLD.admission_target_audit_event_id, + OLD.admission_target_owner_proof_digest, + OLD.admission_target_owner_proof_outcome, + OLD.admission_target_positive_durable_abort, + OLD.admission_target_terminal_at, + OLD.admission_target_character_creation_policy + ) THEN + RAISE EXCEPTION 'A lease-bound runtime fence decision is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_decision_immutable'; + END IF; + ELSIF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + IF OLD.status <> 'PREPARED' + OR OLD.admission_lease_id IS NOT NULL + OR OLD.admission_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from the exact PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + ELSE + RETURN NEW; + END IF; + + -- This SELECT is in the same transaction as markProvisional's transition UPDATE. Its row + -- lock serializes the decision with stop/replacement/deletion and is retained through commit. + SELECT runtime.* + INTO runtime_row + FROM game_instances runtime + JOIN game_session_canonical_instance_launch launch + ON launch.game_session_tenant_id = runtime.tenant_id + AND launch.game_instance_id = runtime.id + AND launch.game_instance_uuid = runtime.game_instance_uuid + JOIN game_session_canonical_gameplay_binding_inventory candidate + ON candidate.binding_ref = NEW.candidate_binding_ref + AND candidate.tenant_id = launch.canonical_tenant_id + AND candidate.runtime_game_instance_id = runtime.id + AND candidate.game_instance_id = runtime.game_instance_uuid + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = launch.target_namespace + AND catalog.canonical_tenant_id = launch.canonical_tenant_id + AND catalog.realm_id = launch.canonical_realm_id + AND catalog.world_slug = launch.world_slug + AND catalog.playable_state_namespace_id = launch.playable_state_namespace_id + AND catalog.catalog_revision = NEW.admission_target_catalog_revision + WHERE runtime.tenant_id = NEW.admission_target_game_session_tenant_id + AND runtime.id = NEW.admission_target_game_instance_id + AND runtime.status = 'RUNNING' + -- Match the decision's actual World ACTIVE read to the owner-recorded RUNNING row. V10 + -- independently requires the matching recorded PREPARING epoch to be exactly one lower. + AND runtime.run_owned_start_active_epoch = NEW.admission_target_active_world_epoch + AND runtime.game_instance_uuid = NEW.admission_target_canonical_game_instance_id + AND runtime.version_id = NEW.admission_target_runtime_version_id + AND runtime.game_template_id = launch.game_template_id + AND runtime.launch_descriptor_id = launch.launch_descriptor_id + AND runtime.release_bundle_id = launch.release_bundle_id + AND runtime.generation_config_revision = launch.generation_config_revision + AND runtime.version_state_epoch = launch.version_state_epoch + AND runtime.run_owned_start_request_id = launch.control_plane_request_id + AND runtime.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' + AND launch.target_namespace = NEW.admission_target_namespace + AND launch.canonical_tenant_id = NEW.admission_target_tenant_id + AND launch.canonical_realm_id = NEW.admission_target_realm_id + AND catalog.tenant_slug = NEW.admission_target_tenant_slug + AND catalog.world_slug = NEW.admission_target_world_slug + AND catalog.source_world_display_name = NEW.admission_target_world_display_name + AND catalog.realm_slug = NEW.admission_target_realm_slug + AND catalog.realm_display_name = NEW.admission_target_realm_display_name + AND launch.playable_state_namespace_id = NEW.admission_target_playable_state_namespace_id + AND launch.playable_state_scope = NEW.admission_target_playable_state_scope + AND launch.version_id = NEW.admission_target_runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text + AND catalog.visible + AND catalog.public_production + AND catalog.state_scope = 'SHARED' + AND launch.public_production + AND launch.playable_state_scope = 'SHARED' + AND launch.captured_starting_row_version <= runtime.row_version + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'targetNamespace' + = launch.target_namespace + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'controlPlaneRequestId' + = launch.control_plane_request_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'canonicalTenantId' + = launch.canonical_tenant_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'worldSlug' + = launch.world_slug + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'gameTemplateId' + = launch.game_template_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'launchDescriptorId' + = launch.launch_descriptor_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionId' + = launch.version_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'releaseBundleId' + = launch.release_bundle_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'generationConfigRevision' + = launch.generation_config_revision + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionStateEpoch' + = launch.version_state_epoch::text + FOR UPDATE OF runtime; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Lease-bound binding decision requires the exact current RUNNING launch row and candidate identity' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_exact_running_launch_required'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION reject_game_session_retained_tenant_payload_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session retained tenant payload expiry cannot be bypassed with TRUNCATE' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER game_session_retained_tenant_payload_no_truncate + BEFORE TRUNCATE ON game_session_retained_tenant_association_payload + FOR EACH STATEMENT + EXECUTE FUNCTION reject_game_session_retained_tenant_payload_truncate(); + +CREATE FUNCTION reject_game_session_retained_tenant_hold_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Game Session tenant legal hold audit cannot be bypassed with TRUNCATE' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER game_session_retained_tenant_hold_no_truncate + BEFORE TRUNCATE ON game_session_retained_tenant_association_legal_hold + FOR EACH STATEMENT + EXECUTE FUNCTION reject_game_session_retained_tenant_hold_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V34.2__canonical_gameplay_runtime_update_and_identifier_guards.sql b/services/game-session-service/src/main/resources/db/migration/V34.2__canonical_gameplay_runtime_update_and_identifier_guards.sql new file mode 100644 index 0000000000..f1baa890e5 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V34.2__canonical_gameplay_runtime_update_and_identifier_guards.sql @@ -0,0 +1,95 @@ +-- PostgreSQL truncates these V31 identifiers at 63 bytes. Rename the existing relations and +-- foreign keys through their published names so PostgreSQL and DDL-based jOOQ generation converge +-- on the same canonical identifiers without changing the V31 checksum. +ALTER TABLE game_session_canonical_account_coverage_snapshot_issuer_obligation + RENAME TO gs_canonical_account_coverage_snapshot_issuer_obligation; + +ALTER TABLE gs_canonical_account_coverage_snapshot_issuer_obligation + RENAME CONSTRAINT fk_gs_canonical_account_coverage_snapshot_issuer_obligation_operation + TO fk_gs_account_coverage_snapshot_issuer_operation; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_region_obligation + RENAME TO gs_canonical_account_coverage_snapshot_region_obligation; + +ALTER TABLE gs_canonical_account_coverage_snapshot_region_obligation + RENAME CONSTRAINT fk_gs_canonical_account_coverage_snapshot_region_obligation_operation + TO fk_gs_account_coverage_snapshot_region_operation; + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION reject_runtime_row_mutation_during_lease_bound_binding() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + locked_transition RECORD; +BEGIN + -- Keep the V34 lock order: candidate transition rows, including PREPARED rows, serialize + -- mutation against decision acquisition. A waiting runtime write rechecks the committed + -- transition state before applying this row-level guard. + FOR locked_transition IN + SELECT transition.status, transition.admission_lease_id + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_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_session_tenant_id = OLD.tenant_id + AND launch.game_instance_id = OLD.id + AND launch.game_instance_uuid = OLD.game_instance_uuid + WHERE candidate.tenant_id = launch.canonical_tenant_id + AND candidate.runtime_game_instance_id = OLD.id + AND candidate.game_instance_id = OLD.game_instance_uuid + ORDER BY transition.transition_id + FOR UPDATE OF transition + LOOP + IF locked_transition.admission_lease_id IS NOT NULL + AND locked_transition.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Game Instance runtime row is fenced by an unresolved lease-bound binding decision' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_row_mutation_fenced'; + END IF; + IF ROW( + NEW.tenant_id, + NEW.id, + NEW.game_instance_uuid, + NEW.status, + NEW.run_owned_start_active_epoch, + NEW.version_id, + NEW.game_template_id, + NEW.launch_descriptor_id, + NEW.release_bundle_id, + NEW.generation_config_revision, + NEW.version_state_epoch, + NEW.run_owned_start_request_id, + NEW.run_owned_start_published_release_bundle_ref + ) IS DISTINCT FROM ROW( + OLD.tenant_id, + OLD.id, + OLD.game_instance_uuid, + OLD.status, + OLD.run_owned_start_active_epoch, + OLD.version_id, + OLD.game_template_id, + OLD.launch_descriptor_id, + OLD.release_bundle_id, + OLD.generation_config_revision, + OLD.version_state_epoch, + OLD.run_owned_start_request_id, + OLD.run_owned_start_published_release_bundle_ref + ) + OR NEW.row_version IS NULL + OR NEW.row_version < OLD.row_version THEN + RAISE EXCEPTION 'Game Instance runtime row is fenced by an unresolved lease-bound binding decision' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_row_mutation_fenced'; + END IF; + END IF; + END LOOP; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V34.3__canonical_initial_admission_intent_request_id_width.sql b/services/game-session-service/src/main/resources/db/migration/V34.3__canonical_initial_admission_intent_request_id_width.sql new file mode 100644 index 0000000000..e088450d87 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V34.3__canonical_initial_admission_intent_request_id_width.sql @@ -0,0 +1,31 @@ +-- Keep the immutable intent ledger aligned with the 128-character request identity accepted by +-- the V28 game_session_canonical_initial_admission_attempt ledger and pointer ledgers. +ALTER TABLE game_session_canonical_initial_admission_intent + ALTER COLUMN initial_admission_request_id TYPE character varying(128); + +ALTER TABLE game_session_canonical_initial_admission_intent + DROP CONSTRAINT chk_gs_initial_admission_intent_identity; + +ALTER TABLE game_session_canonical_initial_admission_intent + ADD CONSTRAINT chk_gs_initial_admission_intent_identity CHECK ( + octet_length(target_namespace) BETWEEN 1 AND 63 + AND target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND char_length(initial_admission_request_id) BETWEEN 1 AND 128 + AND initial_admission_request_id !~ '^[[:space:]]*$' + AND initial_admission_request_id !~ '[[:cntrl:]]' + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND realm_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND catalog_creation_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_association_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND game_session_tenant_id > 0 + AND game_instance_id > 0 + AND runtime_version_id > 0 + AND catalog_revision > 0 + AND captured_starting_row_version >= 0 + AND current_row_version >= captured_starting_row_version + AND playable_state_scope = 'SHARED' + AND catalog_visible IS TRUE + AND catalog_public_production IS TRUE); diff --git a/services/game-session-service/src/main/resources/db/migration/V34__canonical_gameplay_decision_runtime_fence.sql b/services/game-session-service/src/main/resources/db/migration/V34__canonical_gameplay_decision_runtime_fence.sql new file mode 100644 index 0000000000..dc8c14d1bd --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V34__canonical_gameplay_decision_runtime_fence.sql @@ -0,0 +1,347 @@ +-- A lease-bound PROVISIONAL binding decision pins its exact current Game Instance row until a +-- terminal owner operation is implemented. The decision remains the existing transition row; +-- this migration adds no hold/receipt ledger and never infers release from lease expiry. +-- [jooq ignore start] +CREATE FUNCTION require_running_runtime_for_lease_bound_binding_decision() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime_row game_instances%ROWTYPE; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from an existing PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + RETURN NEW; + END IF; + + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL THEN + IF NEW.status NOT IN ('PROVISIONAL', 'AMBIGUOUS') + OR (OLD.status = 'AMBIGUOUS' AND NEW.status <> 'AMBIGUOUS') THEN + RAISE EXCEPTION 'A lease-bound runtime fence cannot be released without terminal owner reconciliation' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_terminal_owner_required'; + END IF; + + IF ROW( + NEW.admission_request_id, + NEW.admission_lease_id, + NEW.admission_lease_fence, + NEW.admission_lease_kind, + NEW.admission_lease_digest, + NEW.admission_lease_evidence, + NEW.admission_resume_episode_id, + NEW.admission_expected_old_binding_generation, + NEW.admission_lease_expires_at, + NEW.admission_target_namespace, + NEW.admission_target_tenant_slug, + NEW.admission_target_tenant_id, + NEW.admission_target_world_slug, + NEW.admission_target_world_display_name, + NEW.admission_target_realm_id, + NEW.admission_target_realm_slug, + NEW.admission_target_realm_display_name, + NEW.admission_target_game_session_tenant_id, + NEW.admission_target_game_instance_id, + NEW.admission_target_playable_state_namespace_id, + NEW.admission_target_playable_state_scope, + NEW.admission_target_canonical_game_instance_id, + NEW.admission_target_canonical_version_id, + NEW.admission_target_runtime_version_id, + NEW.admission_target_catalog_revision, + NEW.admission_target_pointer_version, + NEW.admission_target_pointer_snapshot_digest, + NEW.admission_target_active_world_epoch, + NEW.admission_target_initial_admission_request_id, + NEW.admission_target_initial_admission_request_digest, + NEW.admission_target_origin_kind, + NEW.admission_target_expected_prior_pointer_version, + NEW.admission_target_hold_id, + NEW.admission_target_hold_fence, + NEW.admission_target_hold_binding_digest, + NEW.admission_target_audit_event_id, + NEW.admission_target_owner_proof_digest, + NEW.admission_target_owner_proof_outcome, + NEW.admission_target_positive_durable_abort, + NEW.admission_target_terminal_at, + NEW.admission_target_character_creation_policy + ) IS DISTINCT FROM ROW( + OLD.admission_request_id, + OLD.admission_lease_id, + OLD.admission_lease_fence, + OLD.admission_lease_kind, + OLD.admission_lease_digest, + OLD.admission_lease_evidence, + OLD.admission_resume_episode_id, + OLD.admission_expected_old_binding_generation, + OLD.admission_lease_expires_at, + OLD.admission_target_namespace, + OLD.admission_target_tenant_slug, + OLD.admission_target_tenant_id, + OLD.admission_target_world_slug, + OLD.admission_target_world_display_name, + OLD.admission_target_realm_id, + OLD.admission_target_realm_slug, + OLD.admission_target_realm_display_name, + OLD.admission_target_game_session_tenant_id, + OLD.admission_target_game_instance_id, + OLD.admission_target_playable_state_namespace_id, + OLD.admission_target_playable_state_scope, + OLD.admission_target_canonical_game_instance_id, + OLD.admission_target_canonical_version_id, + OLD.admission_target_runtime_version_id, + OLD.admission_target_catalog_revision, + OLD.admission_target_pointer_version, + OLD.admission_target_pointer_snapshot_digest, + OLD.admission_target_active_world_epoch, + OLD.admission_target_initial_admission_request_id, + OLD.admission_target_initial_admission_request_digest, + OLD.admission_target_origin_kind, + OLD.admission_target_expected_prior_pointer_version, + OLD.admission_target_hold_id, + OLD.admission_target_hold_fence, + OLD.admission_target_hold_binding_digest, + OLD.admission_target_audit_event_id, + OLD.admission_target_owner_proof_digest, + OLD.admission_target_owner_proof_outcome, + OLD.admission_target_positive_durable_abort, + OLD.admission_target_terminal_at, + OLD.admission_target_character_creation_policy + ) THEN + RAISE EXCEPTION 'A lease-bound runtime fence decision is immutable' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_decision_immutable'; + END IF; + ELSIF NEW.admission_lease_id IS NOT NULL + AND NEW.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + IF OLD.status <> 'PREPARED' + OR OLD.admission_lease_id IS NOT NULL + OR OLD.admission_request_id IS NOT NULL THEN + RAISE EXCEPTION 'Lease-bound runtime fence must be acquired from the exact PREPARED transition' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_requires_prepared_transition'; + END IF; + ELSE + RETURN NEW; + END IF; + + -- This SELECT is in the same transaction as markProvisional's transition UPDATE. Its row + -- lock serializes the decision with stop/replacement/deletion and is retained through commit. + SELECT runtime.* + INTO runtime_row + FROM game_instances runtime + JOIN game_session_canonical_instance_launch launch + ON launch.game_session_tenant_id = runtime.tenant_id + AND launch.game_instance_id = runtime.id + AND launch.game_instance_uuid = runtime.game_instance_uuid + JOIN game_session_canonical_realm_catalog catalog + ON catalog.target_namespace = launch.target_namespace + AND catalog.canonical_tenant_id = launch.canonical_tenant_id + AND catalog.realm_id = launch.canonical_realm_id + AND catalog.world_slug = launch.world_slug + AND catalog.playable_state_namespace_id = launch.playable_state_namespace_id + AND catalog.catalog_revision = NEW.admission_target_catalog_revision + WHERE runtime.tenant_id = NEW.admission_target_game_session_tenant_id + AND runtime.id = NEW.admission_target_game_instance_id + AND runtime.status = 'RUNNING' + -- Match the decision's actual World ACTIVE read to the owner-recorded RUNNING row. V10 + -- independently requires the matching recorded PREPARING epoch to be exactly one lower. + AND runtime.run_owned_start_active_epoch = NEW.admission_target_active_world_epoch + AND runtime.game_instance_uuid = NEW.admission_target_canonical_game_instance_id + AND runtime.version_id = NEW.admission_target_runtime_version_id + AND runtime.game_template_id = launch.game_template_id + AND runtime.launch_descriptor_id = launch.launch_descriptor_id + AND runtime.release_bundle_id = launch.release_bundle_id + AND runtime.generation_config_revision = launch.generation_config_revision + AND runtime.version_state_epoch = launch.version_state_epoch + AND runtime.run_owned_start_request_id = launch.control_plane_request_id + AND runtime.run_owned_start_published_release_bundle_ref = + launch.complete_launch_binding_evidence -> 'descriptor' ->> 'publishedReleaseBundleRef' + AND launch.target_namespace = NEW.admission_target_namespace + AND launch.canonical_tenant_id = NEW.admission_target_tenant_id + AND launch.canonical_realm_id = NEW.admission_target_realm_id + AND catalog.tenant_slug = NEW.admission_target_tenant_slug + AND catalog.world_slug = NEW.admission_target_world_slug + AND catalog.source_world_display_name = NEW.admission_target_world_display_name + AND catalog.realm_slug = NEW.admission_target_realm_slug + AND catalog.realm_display_name = NEW.admission_target_realm_display_name + AND launch.playable_state_namespace_id = NEW.admission_target_playable_state_namespace_id + AND launch.playable_state_scope = NEW.admission_target_playable_state_scope + AND launch.version_id = NEW.admission_target_runtime_version_id + AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.admission_target_canonical_version_id::text + AND catalog.visible + AND catalog.public_production + AND catalog.state_scope = 'SHARED' + AND launch.public_production + AND launch.playable_state_scope = 'SHARED' + AND launch.captured_starting_row_version <= runtime.row_version + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'targetNamespace' + = launch.target_namespace + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'controlPlaneRequestId' + = launch.control_plane_request_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'canonicalTenantId' + = launch.canonical_tenant_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'worldSlug' + = launch.world_slug + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'gameTemplateId' + = launch.game_template_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'launchDescriptorId' + = launch.launch_descriptor_id + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionId' + = launch.version_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'releaseBundleId' + = launch.release_bundle_id::text + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'generationConfigRevision' + = launch.generation_config_revision + AND launch.complete_launch_binding_evidence -> 'descriptor' ->> 'versionStateEpoch' + = launch.version_state_epoch::text + FOR UPDATE OF runtime; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Lease-bound binding decision requires the exact current RUNNING launch row' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_exact_running_launch_required'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_binding_runtime_fence + BEFORE INSERT OR UPDATE ON game_session_canonical_binding_transition + FOR EACH ROW + EXECUTE FUNCTION require_running_runtime_for_lease_bound_binding_decision(); + +CREATE FUNCTION reject_runtime_row_mutation_during_lease_bound_binding() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + locked_transition RECORD; +BEGIN + -- Lock every candidate transition for this runtime identity, including PREPARED rows. The + -- target columns are populated only as the decision is acquired, so matching only those + -- columns would miss a command whose snapshot predates that commit. The candidate identity is + -- already durable before this point and is unchanged by PREPARED -> PROVISIONAL. SELECT FOR + -- UPDATE waits/rechecks the current transition tuple; opposing runtime/transition lock order + -- may deadlock, but either transaction aborts rather than allowing STOPPED + PROVISIONAL. + FOR locked_transition IN + SELECT transition.status, transition.admission_lease_id + FROM game_session_canonical_binding_transition transition + JOIN game_session_canonical_gameplay_binding_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_session_tenant_id = OLD.tenant_id + AND launch.game_instance_id = OLD.id + AND launch.game_instance_uuid = OLD.game_instance_uuid + WHERE candidate.tenant_id = launch.canonical_tenant_id + AND candidate.runtime_game_instance_id = OLD.id + AND candidate.game_instance_id = OLD.game_instance_uuid + ORDER BY transition.transition_id + FOR UPDATE OF transition + LOOP + IF locked_transition.admission_lease_id IS NOT NULL + AND locked_transition.status IN ('PROVISIONAL', 'AMBIGUOUS') THEN + RAISE EXCEPTION 'Game Instance runtime row is fenced by an unresolved lease-bound binding decision' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_row_mutation_fenced'; + END IF; + END LOOP; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_instances_lease_bound_binding_runtime_fence + BEFORE UPDATE OR DELETE ON game_instances + FOR EACH ROW + EXECUTE FUNCTION reject_runtime_row_mutation_during_lease_bound_binding(); + +CREATE FUNCTION reject_truncate_during_lease_bound_binding() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + WHERE transition.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND transition.admission_lease_id IS NOT NULL + ) THEN + RAISE EXCEPTION 'TRUNCATE cannot remove rows protected by an unresolved lease-bound binding decision' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_truncate_fenced'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER game_instances_lease_bound_binding_no_truncate + BEFORE TRUNCATE ON game_instances + FOR EACH STATEMENT + EXECUTE FUNCTION reject_truncate_during_lease_bound_binding(); + +CREATE FUNCTION reject_unowned_lease_bound_binding_release() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL THEN + RAISE EXCEPTION 'An unresolved lease-bound binding decision cannot be deleted' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_delete_owner_required'; + END IF; + RETURN OLD; + END IF; + + IF OLD.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND OLD.admission_lease_id IS NOT NULL + AND (NEW.status NOT IN ('PROVISIONAL', 'AMBIGUOUS') + OR (OLD.status = 'AMBIGUOUS' AND NEW.status <> 'AMBIGUOUS')) THEN + RAISE EXCEPTION 'An unresolved lease-bound binding decision requires terminal owner reconciliation' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_terminal_owner_required'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_binding_runtime_fence_release_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_binding_transition + FOR EACH ROW + EXECUTE FUNCTION reject_unowned_lease_bound_binding_release(); + +CREATE FUNCTION reject_truncate_unresolved_lease_bound_binding() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_binding_transition transition + WHERE transition.status IN ('PROVISIONAL', 'AMBIGUOUS') + AND transition.admission_lease_id IS NOT NULL + ) THEN + RAISE EXCEPTION 'TRUNCATE cannot discard unresolved lease-bound binding decisions' + USING ERRCODE = '23514', + CONSTRAINT = 'gs_binding_runtime_fence_transition_truncate_guard'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER game_session_canonical_binding_runtime_fence_no_truncate + BEFORE TRUNCATE ON game_session_canonical_binding_transition + FOR EACH STATEMENT + EXECUTE FUNCTION reject_truncate_unresolved_lease_bound_binding(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index a509b220a7..d6f66337f3 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -22,6 +22,7 @@ import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -264,6 +265,32 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc + "] - online in Demo World / Live Realm (idle)")); } + @Test + void freshGameplayBaselineRestoresAlwaysEnabledLaunchTruncateGuard() throws Exception { + ensureTestServicesStarted(); + prepareGameInstance(); + JdbcTemplate jdbc = STACK.jdbc(); + String originalState = launchGuardState(jdbc); + assertThat(originalState).isIn("O", "A"); + + try { + jdbc.execute( + "ALTER TABLE game_session_canonical_instance_launch ENABLE ALWAYS TRIGGER " + + "game_session_canonical_instance_launch_no_truncate"); + assertThat(launchGuardState(jdbc)).isEqualTo("A"); + + prepareGameInstance(); + + assertThat(launchGuardState(jdbc)).isEqualTo("A"); + } finally { + String enableMode = "A".equals(originalState) ? "ENABLE ALWAYS" : "ENABLE"; + jdbc.execute( + "ALTER TABLE game_session_canonical_instance_launch " + + enableMode + + " TRIGGER game_session_canonical_instance_launch_no_truncate"); + } + } + @Test void websocketFriendsMutationFlowUsesCanonicalRosterSurface() throws Exception { ensureTestServicesStarted(); @@ -891,6 +918,14 @@ private long prepareGameInstance() { Long.parseLong(ChatTestFixtures.PLAYER_NYX)); } + private static String launchGuardState(JdbcTemplate jdbc) { + return jdbc.queryForObject( + "SELECT tgenabled::text FROM pg_trigger WHERE tgrelid = " + + "'game_session_canonical_instance_launch'::regclass AND tgname = " + + "'game_session_canonical_instance_launch_no_truncate' AND NOT tgisinternal", + String.class); + } + private void seedLiveTargetSession() { STACK.seedLiveSession( 90210L, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java new file mode 100644 index 0000000000..08f582ae5f --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java @@ -0,0 +1,940 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayBindingInventoryRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CHARACTER_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID INSTANCE_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final long RUNTIME_GAME_INSTANCE_ID = 23L; + private static final UUID REGION_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID ISSUER_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID TRANSITION_ID = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID ACCOUNT_INDEX_FENCE = + UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID RESERVATION_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID RESERVATION_FENCE = + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID ISSUER_COVERAGE_OPERATION_ID = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID PRIOR_RESERVATION_ID = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID PRIOR_RESERVATION_FENCE = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID PRIOR_TRANSITION_ID = + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void failsClosedWhenInventoryAbsenceCannotProveLegacyControllerAbsence() { + String schema = "gs_binding_inventory_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = dslForSchema(dataSource, schema); + CanonicalGameplayBindingInventoryRepository repository = + new CanonicalGameplayBindingInventoryRepository(dsl); + assertThatThrownBy(() -> repository.prepare(request(candidateSession(1)))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("legacy-index migration fence"); + + var inventory = repository.readSnapshot(); + assertThat(inventory.inventoryRevision()).isZero(); + assertThat(inventory.bindings()).isEmpty(); + assertThat(inventory.transitions()).isEmpty(); + assertThat(inventory.reservations()).isEmpty(); + var generationCount = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS row_count FROM game_session_canonical_binding_generation"), + "binding generation count row"); + assertThat(generationCount.get("row_count", Long.class)).isZero(); + } finally { + dropSchema(schema); + } + } + + @Test + void preparesFirstBindingOnlyBehindVerifiedDispositionAndRetainsNoPriorShape() { + String schema = "gs_binding_first_inventory_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = dslForSchema(dataSource, schema); + seedSyntheticVerifiedLegacyDisposition(dsl); + CanonicalGameplayBindingInventoryRepository repository = + new CanonicalGameplayBindingInventoryRepository(dsl); + + var prepared = repository.prepare(request(candidateSession(1))); + var evidence = repository.readProvisionalCasEvidence(TRANSITION_ID); + + assertThat(prepared.bindingGeneration()).isEqualTo(BigInteger.ONE); + assertThat(prepared.expectedPriorBindingRef()).isNull(); + assertThat(prepared.expectedPriorBindingGeneration()).isNull(); + assertThat(evidence.expectedPrior()).isNull(); + assertThat(evidence.expectedPriorReservation()).isNull(); + assertThat(evidence.initialBindingMigrationDisposition()).isNotNull(); + + // This synthetic migration fixture exercises the repository guard, not live migration proof. + var beforeLeaseFreeAttempt = repository.readSnapshot(); + assertThatThrownBy(() -> repository.markProvisional(evidence)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("requires the exact Account lease decision"); + var afterLeaseFreeAttempt = repository.readSnapshot(); + assertThat(afterLeaseFreeAttempt.inventoryRevision()) + .isEqualTo(beforeLeaseFreeAttempt.inventoryRevision()); + assertThat(afterLeaseFreeAttempt.bindings()) + .singleElement() + .satisfies( + candidate -> + assertThat(candidate.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle + .CANDIDATE_PREPARED)); + var storedDecision = + dsl.fetchOne( + "SELECT admission_request_id, admission_lease_id" + + " FROM game_session_canonical_binding_transition WHERE transition_id = ?", + TRANSITION_ID); + assertThat(storedDecision).isNotNull(); + assertThat(storedDecision.get("admission_request_id", UUID.class)).isNull(); + assertThat(storedDecision.get("admission_lease_id", UUID.class)).isNull(); + + assertThat(repository.readSnapshot().accountIndexObligations()) + .singleElement() + .satisfies(obligation -> assertThat(obligation.expectedPriorGeneration()).isNull()); + assertThat(repository.readSnapshot().bindings()) + .singleElement() + .satisfies( + candidate -> + assertThat(candidate.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle + .CANDIDATE_PREPARED)); + } finally { + dropSchema(schema); + } + } + + @Test + void persistsFirstBindingAccountIndexReadbackWithoutPriorObligation() { + TestSchema testSchema = newTestSchema("gs_binding_first_projection_"); + try { + LeaseBoundFirstBinding fixture = prepareLeaseBoundFirstBinding(testSchema.dsl()); + assertThat(fixture.evidence().expectedPrior()).isNull(); + String member = + CanonicalGameplayAccountIndexMember.of(fixture.evidence().candidate()).value(); + + var receipt = + fixture.repository().markCandidateAccountIndexPresent(fixture.evidence(), member); + + assertThat(receipt.obligationOrdinal()).isZero(); + assertThat(receipt.member()).isEqualTo(member); + assertThat(receipt.state()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexProjectionReceipt.State + .PRESENT_AWAITING_COVERAGE); + assertThat(fixture.repository().readSnapshot().accountIndexObligations()) + .singleElement() + .satisfies( + obligation -> + assertThat(obligation.projectionState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE)); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void readsLeaseBoundAdmissionDecisionInReadOnlyTransaction() { + TestSchema testSchema = newTestSchema("gs_binding_readonly_decision_"); + try { + LeaseBoundFirstBinding fixture = prepareLeaseBoundFirstBinding(testSchema.dsl()); + + var decision = + fixture.repository().readAdmissionDecision(TRANSITION_ID, fixture.leaseEvidence()); + + assertThat(decision.bindingDecisionId()).isEqualTo(TRANSITION_ID); + assertThat(decision.leaseEvidence().hasSameIdentity(fixture.leaseEvidence())).isTrue(); + assertThat(decision.candidate()).isEqualTo(fixture.evidence().candidate().identity()); + assertThat(decision.expectedOldBindingGeneration()).isNull(); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void persistsLeaseBoundAdmissionTerminalTimestampAsPostgresTimestamptz() { + TestSchema testSchema = newTestSchema("gs_binding_terminal_timestamp_"); + try { + LeaseBoundFirstBinding fixture = prepareLeaseBoundFirstBinding(testSchema.dsl()); + + var decision = + fixture.repository().readAdmissionDecision(TRANSITION_ID, fixture.leaseEvidence()); + var storedTarget = + testSchema + .dsl() + .fetchOne( + "SELECT admission_target_terminal_at," + + " pg_typeof(admission_target_terminal_at) AS terminal_at_type" + + " FROM game_session_canonical_binding_transition WHERE transition_id = ?", + TRANSITION_ID); + + assertThat(storedTarget).isNotNull(); + assertThat(storedTarget.get("terminal_at_type", String.class)) + .isEqualTo("timestamp with time zone"); + assertThat(storedTarget.get("admission_target_terminal_at", OffsetDateTime.class).toInstant()) + .isEqualTo(decision.targetEvidence().ownerProofTerminalAt()); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void leaseBoundDecisionAndRuntimeMutationAcquireLocksInOneOrder() throws Exception { + String applicationName = + "gs_binding_runtime_lock_order_" + UUID.randomUUID().toString().replace("-", ""); + TestSchema testSchema = newTestSchema("gs_binding_runtime_lock_order_", applicationName); + CountDownLatch runtimeRowLocked = new CountDownLatch(1); + CountDownLatch allowRuntimeMutation = new CountDownLatch(1); + try { + PreparedLeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBindingDecision(testSchema.dsl()); + CanonicalPlayableTarget target = fixture.runtimeTarget().playableTarget(); + long initialRowVersion = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT row_version FROM game_instances WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .get("row_version", Long.class); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + try { + Future runtimeMutation = + executor.submit( + () -> + testSchema + .dsl() + .transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + var runtime = + transaction.fetchOne( + "SELECT id FROM game_instances" + + " WHERE tenant_id = ? AND id = ? FOR UPDATE", + target.gameSessionTenantId(), + target.gameInstanceId()); + if (runtime == null) { + throw new IllegalStateException("Expected current runtime row"); + } + runtimeRowLocked.countDown(); + awaitLatch(allowRuntimeMutation); + return transaction.execute( + "UPDATE game_instances SET row_version = row_version + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + })); + + assertThat(runtimeRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future decisionAcquisition = + executor.submit( + () -> + fixture.repository().markProvisional(fixture.evidence(), fixture.decision())); + + awaitBindingLockWait(testSchema.dsl(), applicationName); + allowRuntimeMutation.countDown(); + + assertThat(runtimeMutation.get(10, TimeUnit.SECONDS)).isEqualTo(1); + assertThat(decisionAcquisition.get(10, TimeUnit.SECONDS).status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL); + assertThat( + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT row_version FROM game_instances WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .get("row_version", Long.class)) + .isEqualTo(initialRowVersion + 1); + + CountDownLatch projectionRuntimeRowLocked = new CountDownLatch(1); + CountDownLatch allowFencedRuntimeMutation = new CountDownLatch(1); + Future fencedRuntimeMutation = + executor.submit( + () -> + testSchema + .dsl() + .transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + var runtime = + transaction.fetchOne( + "SELECT id FROM game_instances" + + " WHERE tenant_id = ? AND id = ? FOR UPDATE", + target.gameSessionTenantId(), + target.gameInstanceId()); + if (runtime == null) { + throw new IllegalStateException("Expected current runtime row"); + } + projectionRuntimeRowLocked.countDown(); + awaitLatch(allowFencedRuntimeMutation); + return transaction.execute( + "UPDATE game_instances SET status = 'STOPPED'," + + " row_version = row_version + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + })); + Future accountIndexReadback; + try { + assertThat(projectionRuntimeRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); + CanonicalGameplayBindingProvisionalCasEvidence provisionalEvidence = + fixture.repository().readProvisionalCasEvidence(TRANSITION_ID); + String member = + CanonicalGameplayAccountIndexMember.of(provisionalEvidence.candidate()).value(); + accountIndexReadback = + executor.submit( + () -> + fixture + .repository() + .markCandidateAccountIndexPresent(provisionalEvidence, member)); + awaitBindingLockWait(testSchema.dsl(), applicationName); + } finally { + allowFencedRuntimeMutation.countDown(); + } + + assertThatThrownBy(() -> fencedRuntimeMutation.get(10, TimeUnit.SECONDS)) + .hasStackTraceContaining("runtime row is fenced"); + assertThat(accountIndexReadback.get(10, TimeUnit.SECONDS)).isNotNull(); + assertThat( + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT row_version FROM game_instances WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .get("row_version", Long.class)) + .isEqualTo(initialRowVersion + 1); + } finally { + allowRuntimeMutation.countDown(); + } + } + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void unresolvedPreparedTransitionFencesASecondTransitionForTheSameController() { + String schema = "gs_binding_pending_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = dslForSchema(dataSource, schema); + CanonicalGameplayBindingInventoryRepository repository = + new CanonicalGameplayBindingInventoryRepository(dsl); + CanonicalGameplayBindingIdentity prior = identity(sourceSession()); + seedActiveSource(dsl, prior); + repository.prepare(transferRequest(candidateSession(1), prior)); + + CanonicalGameplayBindingTransitionRequest otherOperation = + new CanonicalGameplayBindingTransitionRequest( + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + identity(candidateSession(2)), + new CanonicalIssuerReservationFenceEvidence( + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + UUID.fromString("acacacac-acac-4cac-8cac-acacacacacac"), + ISSUER_COVERAGE_OPERATION_ID, + BigInteger.valueOf(13), + BigInteger.valueOf(17), + BigInteger.valueOf(41)), + prior.bindingRef(), + BigInteger.valueOf(5)); + assertThatThrownBy(() -> repository.prepare(otherOperation)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessage( + "An unresolved candidate or repair obligation already fences this controller"); + assertThat(repository.readSnapshot().inventoryRevision()).isEqualTo(BigInteger.valueOf(9)); + } finally { + dropSchema(schema); + } + } + + @Test + void advancesGenerationAtomicallyAndKeepsPriorControllerActiveUntilExternalCas() { + String schema = "gs_binding_generation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = dslForSchema(dataSource, schema); + CanonicalGameplayBindingIdentity prior = identity(sourceSession()); + seedActiveSource(dsl, prior); + + var prepared = + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepare( + new CanonicalGameplayBindingTransitionRequest( + TRANSITION_ID, + ACCOUNT_INDEX_FENCE, + identity(candidateSession(2)), + reservation(RESERVATION_FENCE), + prior.bindingRef(), + BigInteger.valueOf(5))); + + CanonicalGameplayBindingTransitionRequest changedRetry = + new CanonicalGameplayBindingTransitionRequest( + TRANSITION_ID, + UUID.fromString("abababab-abab-4bab-8bab-abababababab"), + identity(candidateSession(2)), + reservation(RESERVATION_FENCE), + prior.bindingRef(), + BigInteger.valueOf(5)); + assertThatThrownBy( + () -> new CanonicalGameplayBindingInventoryRepository(dsl).prepare(changedRetry)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat( + new CanonicalGameplayBindingInventoryRepository(dsl) + .readSnapshot() + .inventoryRevision()) + .isEqualTo(BigInteger.valueOf(9)); + + assertThat(prepared.bindingGeneration()).isEqualTo(BigInteger.valueOf(6)); + assertThat(prepared.inventoryRevision()).isEqualTo(BigInteger.valueOf(9)); + var snapshot = new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); + assertThat(snapshot.bindings()).hasSize(2); + assertThat(snapshot.bindings()) + .anySatisfy( + row -> + assertThat(row.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE)); + assertThat(snapshot.bindings()) + .anySatisfy( + row -> + assertThat(row.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle + .CANDIDATE_PREPARED)); + assertThat(snapshot.accountIndexObligations()).hasSize(2); + assertThat(snapshot.accountIndexObligations().get(0).expectedPriorGeneration()) + .isEqualTo(BigInteger.valueOf(5)); + assertThat(snapshot.accountIndexObligations().get(1).executionPhase()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.AFTER_FINAL_CAS); + } finally { + dropSchema(schema); + } + } + + private static CanonicalGameplayBindingTransitionRequest request(String sessionId) { + return new CanonicalGameplayBindingTransitionRequest( + TRANSITION_ID, + ACCOUNT_INDEX_FENCE, + identity(sessionId), + reservation(RESERVATION_FENCE), + null, + null); + } + + private static LeaseBoundFirstBinding prepareLeaseBoundFirstBinding(DSLContext dsl) { + PreparedLeaseBoundFirstBinding prepared = prepareLeaseBoundFirstBindingDecision(dsl); + prepared.repository().markProvisional(prepared.evidence(), prepared.decision()); + return new LeaseBoundFirstBinding( + prepared.repository(), + prepared.leaseEvidence(), + prepared.repository().readProvisionalCasEvidence(TRANSITION_ID)); + } + + private static PreparedLeaseBoundFirstBinding prepareLeaseBoundFirstBindingDecision( + DSLContext dsl) { + var runtimeTarget = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + dsl, TENANT_ID, 1L, RUNTIME_GAME_INSTANCE_ID, INSTANCE_ID, NAMESPACE_ID); + // This synthetic disposition opens the repository branch for proof; it is not real migration + // or bootstrap authorization. + seedSyntheticVerifiedLegacyDisposition(dsl); + CanonicalGameplayBindingInventoryRepository repository = + new CanonicalGameplayBindingInventoryRepository(dsl); + CanonicalGameplayBindingTransitionRequest request = request(candidateSession(1)); + repository.prepare(request); + CanonicalGameplayBindingProvisionalCasEvidence preparedEvidence = + repository.readProvisionalCasEvidence(TRANSITION_ID); + var candidate = preparedEvidence.candidate().identity(); + CanonicalPlayableTarget target = runtimeTarget.playableTarget(); + AccountGameplayAdmissionLeaseEvidence leaseEvidence = + leaseEvidence(candidate, preparedEvidence.transition().bindingGeneration(), target); + CanonicalGameplayAdmissionDecision decision = + new CanonicalGameplayAdmissionDecision( + TRANSITION_ID, + leaseEvidence, + candidate, + preparedEvidence.transition().bindingGeneration(), + null, + target); + return new PreparedLeaseBoundFirstBinding( + repository, leaseEvidence, preparedEvidence, decision, runtimeTarget); + } + + private static AccountGameplayAdmissionLeaseEvidence leaseEvidence( + CanonicalGameplayBindingIdentity candidate, + BigInteger bindingGeneration, + CanonicalPlayableTarget target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", "10101010-1010-4010-8010-101010101010"); + carrier.put("leaseId", "20202020-2020-4020-8020-202020202020"); + carrier.put("leaseFence", "1"); + + Map scope = new LinkedHashMap<>(); + scope.put("accountId", candidate.accountId().toString()); + scope.put("tenantId", candidate.tenantId().toString()); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", candidate.characterId().toString()); + scope.put("sessionId", candidate.sessionId()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", candidate.regionId().toString()); + scope.put("regionEpoch", candidate.regionEpoch().toString()); + carrier.put("bindingScope", scope); + + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", candidate.issuerAuthGeneration().toString()); + authority.put("accountAuthorityGeneration", "1"); + authority.put("tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("privateRealmGrantVersions", List.of()); + carrier.put("authorityTuple", authority); + carrier.put("issuanceFence", "1"); + + Map membershipVersions = + new LinkedHashMap<>(Map.of(candidate.tenantId().toString(), "1")); + carrier.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + membershipVersions, + "membershipAuthorityGeneration", + "1"))); + + String prefix = "account:auth-authority:v1:"; + List> checkpoints = new ArrayList<>(); + for (String stream : + List.of( + "account/" + candidate.accountId(), + "issuer/firemud-account-service", + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), + "tenant/" + candidate.tenantId())) { + checkpoints.add( + new LinkedHashMap<>( + Map.of( + "outboxStreamKey", + prefix + stream, + "outboxSequence", + stream.startsWith("membership/") || stream.startsWith("tenant/") ? "1" : "0"))); + } + carrier.put("outboxCheckpoints", checkpoints); + + Map tokenIdentity = new LinkedHashMap<>(); + tokenIdentity.put("accountId", candidate.accountId().toString()); + tokenIdentity.put("operationId", "40404040-4040-4040-8040-404040404040"); + tokenIdentity.put("issuanceRequestId", "50505050-5050-4050-8050-505050505050"); + tokenIdentity.put("tokenJti", "60606060-6060-4060-8060-606060606060"); + tokenIdentity.put("tokenSHA256", "a".repeat(64)); + tokenIdentity.put("tokenProfile", "game-session-account-delegation"); + tokenIdentity.put("tokenGeneration", "1"); + tokenIdentity.put("issuanceFence", "1"); + tokenIdentity.put("tokenIdentityFence", "1"); + tokenIdentity.put("issuedAt", nowSeconds); + tokenIdentity.put("notBefore", nowSeconds); + tokenIdentity.put("expiresAt", Long.toString(now / 1000L + 60L)); + carrier.put("tokenIdentityEvidence", tokenIdentity); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static TestSchema newTestSchema(String prefix) { + return newTestSchema(prefix, null); + } + + private static TestSchema newTestSchema(String prefix, String applicationName) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema, applicationName); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + return new TestSchema(schema, dslForSchema(dataSource, schema)); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for the lock-order test gate"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for the lock-order test gate", interrupted); + } + } + + private static void awaitBindingLockWait(DSLContext observer, String applicationName) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + Boolean waiting = + Objects.requireNonNull( + observer.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE pid <> pg_backend_pid() AND state = 'active'" + + " AND application_name = ?" + + " AND wait_event_type = 'Lock'" + + " AND (query ILIKE '%game_instances%FOR UPDATE%'" + + " OR query ILIKE '%UPDATE game_session_canonical_binding_transition%'))", + applicationName)) + .get(0, Boolean.class); + if (Boolean.TRUE.equals(waiting)) { + return; + } + Thread.sleep(10); + } + throw new AssertionError("Lease-bound decision did not wait on the held runtime row"); + } + + private record LeaseBoundFirstBinding( + CanonicalGameplayBindingInventoryRepository repository, + AccountGameplayAdmissionLeaseEvidence leaseEvidence, + CanonicalGameplayBindingProvisionalCasEvidence evidence) {} + + private record PreparedLeaseBoundFirstBinding( + CanonicalGameplayBindingInventoryRepository repository, + AccountGameplayAdmissionLeaseEvidence leaseEvidence, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayAdmissionDecision decision, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget) {} + + private record TestSchema(String schema, DSLContext dsl) {} + + private static CanonicalGameplayBindingTransitionRequest transferRequest( + String candidateSessionId, CanonicalGameplayBindingIdentity prior) { + return new CanonicalGameplayBindingTransitionRequest( + TRANSITION_ID, + ACCOUNT_INDEX_FENCE, + identity(candidateSessionId), + reservation(RESERVATION_FENCE), + prior.bindingRef(), + BigInteger.valueOf(5)); + } + + static CanonicalGameplayBindingIdentity identity(String sessionId) { + return new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + "SHARED", + INSTANCE_ID, + RUNTIME_GAME_INSTANCE_ID, + sessionId, + REGION_ID, + BigInteger.valueOf(12), + ISSUER_ID, + BigInteger.valueOf(7), + BigInteger.valueOf(3), + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + } + + private static String sourceSession() { + return "dddddddd-dddd-4ddd-8ddd-dddddddddddd"; + } + + private static String candidateSession(int number) { + return number == 1 + ? "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1" + : "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2"; + } + + static void seedActiveSource(DSLContext dsl, CanonicalGameplayBindingIdentity prior) { + byte[] priorRef = prior.bindingRef().bytes(); + BigInteger priorPartition = prior.bindingRef().partitionId(prior.issuerIndexPartitionCount()); + UUID priorAccountFence = UUID.fromString("12121212-1212-4212-8212-121212121212"); + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock SET inventory_revision = 8" + + " WHERE singleton_id = 1"); + dsl.execute( + "INSERT INTO game_session_canonical_binding_generation" + + " (tenant_id, playable_state_namespace_id, character_id, last_issued_generation)" + + " VALUES (?, ?, ?, 5)", + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID); + dsl.execute( + "INSERT INTO game_session_canonical_gameplay_binding_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 (?, ?, ?, ?, ?, ?, ?, ?, ?, 5, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'ACTIVE', 'ACKNOWLEDGED', 'ACKNOWLEDGED', 8)", + priorRef, + prior.accountId(), + prior.tenantId(), + prior.playableStateNamespaceId(), + prior.characterId(), + prior.playableStateScope(), + prior.gameInstanceId(), + prior.runtimeGameInstanceId(), + prior.sessionId(), + prior.regionId(), + BigInteger.valueOf(12), + prior.issuerId(), + BigInteger.valueOf(7), + BigInteger.valueOf(3), + BigInteger.valueOf(16), + BigInteger.valueOf(32), + priorPartition, + priorAccountFence, + PRIOR_RESERVATION_ID, + PRIOR_TRANSITION_ID); + dsl.execute( + "INSERT INTO game_session_canonical_issuer_partition_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, playable_state_namespace_id, character_id," + + " playable_state_scope, region_id, region_epoch, partition_id," + + " 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 (?, ?, ?, ?, ?, ?, ?, 5, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'BOUND', ?, ?, 1, 1, 7, 8)", + PRIOR_RESERVATION_ID, + priorRef, + prior.accountId(), + prior.tenantId(), + prior.gameInstanceId(), + prior.runtimeGameInstanceId(), + prior.sessionId(), + PRIOR_TRANSITION_ID, + prior.issuerId(), + BigInteger.valueOf(7), + prior.playableStateNamespaceId(), + prior.characterId(), + prior.playableStateScope(), + prior.regionId(), + BigInteger.valueOf(12), + priorPartition, + BigInteger.valueOf(3), + BigInteger.valueOf(16), + BigInteger.valueOf(32), + PRIOR_RESERVATION_FENCE, + ISSUER_COVERAGE_OPERATION_ID); + dsl.execute( + "INSERT INTO game_session_canonical_binding_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)" + + " VALUES (?, ?, ?, ?, NULL, NULL, ?, 5, ?, ?, 'COMMITTED', 8)", + PRIOR_TRANSITION_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + priorRef, + priorAccountFence, + PRIOR_RESERVATION_ID); + } + + /** + * Synthetic storage fixture for branch mechanics only; it is not evidence that the real legacy + * index was fenced, inventoried, rebuilt, or read back. + */ + static void seedSyntheticVerifiedLegacyDisposition(DSLContext dsl) { + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = 1 WHERE singleton_id = 1"); + dsl.execute( + "UPDATE game_session_canonical_binding_legacy_disposition" + + " SET disposition_state = 'VERIFIED'," + + " cohort_id = '10101010-1010-4010-8010-101010101010'," + + " owner_operation_id = '20202020-2020-4020-8020-202020202020'," + + " legacy_writer_fence = '30303030-3030-4030-8030-303030303030'," + + " source_snapshot_revision = 1, canonical_inventory_revision = 1," + + " namespace_index_readback_revision = 1," + + " evidence_digest = 'sha256:" + + "0000000000000000000000000000000000000000000000000000000000000000'" + + " WHERE singleton_id = 1"); + } + + private static CanonicalIssuerReservationFenceEvidence reservation(UUID reservationFence) { + return new CanonicalIssuerReservationFenceEvidence( + RESERVATION_ID, + reservationFence, + ISSUER_COVERAGE_OPERATION_ID, + BigInteger.valueOf(13), + BigInteger.valueOf(17), + BigInteger.valueOf(41)); + } + + private static DriverManagerDataSource dataSource(String schema) { + return dataSource(schema, null); + } + + private static DriverManagerDataSource dataSource(String schema, String applicationName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + // Testcontainers already appends loggerLevel=OFF to the JDBC URL, so add currentSchema with + // '&' to keep both parameters and bind later repository connections to Flyway's schema. + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + String applicationNameParameter = + applicationName == null ? "" : "&ApplicationName=" + applicationName; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema + applicationNameParameter); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static DSLContext dslForSchema(DriverManagerDataSource dataSource, String schema) { + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var schemaReadback = dsl.fetchOne("SELECT current_schema() AS actual_schema"); + assertThat(schemaReadback.get("actual_schema", String.class)).isEqualTo(schema); + var clockReadback = + dsl.fetchOne( + "SELECT to_regclass('game_session_canonical_binding_inventory_clock')::text" + + " AS relation_name"); + assertThat(clockReadback.get("relation_name", String.class)) + .isEqualTo("game_session_canonical_binding_inventory_clock"); + return dsl; + } + + private static void dropSchema(String schema) { + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Failed to dispose canonical binding test schema", failure); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java new file mode 100644 index 0000000000..a071511286 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -0,0 +1,410 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; + +/** Shared PostgreSQL fixtures for lease-bound binding tests that require a real launch target. */ +public final class CanonicalGameplayBindingRuntimeTestFixtures { + private static final String SHA256 = "sha256:" + "a".repeat(64); + private static final String RAW_SHA256 = "a".repeat(64); + + private CanonicalGameplayBindingRuntimeTestFixtures() {} + + public static RuntimeTarget seedRunningLaunch(DSLContext dsl) { + return seedRunningLaunch(dsl, UUID.randomUUID(), 1L, 23L, UUID.randomUUID()); + } + + /** + * Seeds a fully linked fresh tenant, catalog, launch, and RUNNING runtime for the supplied + * candidate identity. All deferred constraints and normal owner triggers remain enabled. + */ + public static RuntimeTarget seedRunningLaunch( + DSLContext dsl, + UUID canonicalTenantId, + long gameSessionTenantId, + long gameInstanceId, + UUID gameInstanceUuid) { + return seedRunningLaunch( + dsl, + canonicalTenantId, + gameSessionTenantId, + gameInstanceId, + gameInstanceUuid, + UUID.randomUUID()); + } + + public static RuntimeTarget seedRunningLaunch( + DSLContext dsl, + UUID canonicalTenantId, + long gameSessionTenantId, + long gameInstanceId, + UUID gameInstanceUuid, + UUID playableStateNamespaceId) { + if (gameSessionTenantId <= 0 || gameInstanceId <= 0) { + throw new IllegalArgumentException("Runtime identifiers must be positive"); + } + if (canonicalTenantId == null + || gameInstanceUuid == null + || playableStateNamespaceId == null + || new UUID(0L, 0L).equals(canonicalTenantId) + || new UUID(0L, 0L).equals(gameInstanceUuid) + || new UUID(0L, 0L).equals(playableStateNamespaceId)) { + throw new IllegalArgumentException("Canonical runtime identities must be non-nil"); + } + + RuntimeTarget target = + RuntimeTarget.create( + canonicalTenantId, + gameSessionTenantId, + gameInstanceId, + gameInstanceUuid, + playableStateNamespaceId); + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + seedSourceAndCatalog(tx, target); + seedFreshTenantAssociation(tx, target); + seedStartingRuntimeAndLaunch(tx, target); + tx.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + }); + return target; + } + + private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { + tx.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding" + + " (target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id," + + " source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW')", + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.sourceGameRowId(), + target.sourceGameTenantKey()); + + tx.execute( + "INSERT INTO game_session_authored_world_source_intake" + + " (operation_id, schema_version, target_namespace, intake_request_id, request_digest," + + " source_schema_version, source_registration_request_id, source_operation_id," + + " source_request_digest, canonical_tenant_id, tenant_slug, world_slug," + + " world_display_name, source_game_row_id, source_game_tenant_key," + + " source_provenance_kind, source_evidence_digest, receipt_digest)" + + " VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?, ?)", + target.sourceIntakeOperationId(), + target.targetNamespace(), + target.sourceIntakeRequestId(), + SHA256, + target.sourceRegistrationRequestId(), + target.sourceOperationId(), + SHA256, + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.worldDisplayName(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + SHA256, + SHA256); + + tx.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace" + + " (tenant_id, playable_state_namespace_id, canonical_tenant_id, target_namespace," + + " source_intake_operation_id, source_intake_schema_version, source_intake_request_id," + + " source_intake_request_digest, source_intake_receipt_digest, source_schema_version," + + " source_registration_request_id, source_operation_id, source_request_digest," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind," + + " source_evidence_digest)" + + " VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)", + target.playableStateNamespaceId(), + target.canonicalTenantId(), + target.targetNamespace(), + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId(), + SHA256, + SHA256, + target.sourceRegistrationRequestId(), + target.sourceOperationId(), + SHA256, + target.sourceGameRowId(), + target.sourceGameTenantKey(), + SHA256); + + tx.execute( + "INSERT INTO game_session_canonical_realm_catalog" + + " (target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id," + + " realm_slug, realm_display_name, visible, public_production, state_scope," + + " playable_state_namespace_id, character_creation_policy, catalog_revision," + + " creation_request_id, request_digest, receipt_digest, source_intake_operation_id," + + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," + + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," + + " source_operation_id, source_request_digest, source_world_display_name," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, 'PLAYER_CHOICE', 1, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)", + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.realmDisplayName(), + target.playableStateNamespaceId(), + target.catalogCreationRequestId(), + SHA256, + SHA256, + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId(), + SHA256, + SHA256, + target.sourceRegistrationRequestId(), + target.sourceOperationId(), + SHA256, + target.worldDisplayName(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + SHA256); + } + + private static void seedFreshTenantAssociation(DSLContext tx, RuntimeTarget target) { + tx.execute( + "INSERT INTO game_session_tenant_scope_reservation" + + " (game_session_tenant_id, reservation_kind) VALUES (?, 'FRESH_SOURCE_BOUND')", + target.gameSessionTenantId()); + tx.execute( + "INSERT INTO game_session_tenant_canonical_claim" + + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, reservation_kind, association_operation_id, association_request_id)" + + " VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", + target.targetNamespace(), + target.canonicalTenantId(), + target.gameSessionTenantId(), + target.tenantAssociationOperationId(), + target.tenantAssociationRequestId()); + tx.execute( + "INSERT INTO game_session_fresh_tenant_association" + + " (association_operation_id, target_namespace, association_request_id," + + " source_schema_version, source_target_namespace, source_request_id," + + " source_canonical_tenant_id, canonical_tenant_id, legacy_game_session_tenant_id," + + " source_game_row_id, source_game_tenant_key, provenance_kind, association_kind)" + + " VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND')", + target.tenantAssociationOperationId(), + target.targetNamespace(), + target.tenantAssociationRequestId(), + target.targetNamespace(), + target.tenantAssociationRequestId(), + target.canonicalTenantId(), + target.canonicalTenantId(), + target.gameSessionTenantId(), + target.sourceGameRowId(), + target.sourceGameTenantKey()); + } + + private static void seedStartingRuntimeAndLaunch(DSLContext tx, RuntimeTarget target) { + tx.execute( + "INSERT INTO game_instances" + + " (id, tenant_id, runtime_version, owner_account_id, status, row_version," + + " game_instance_uuid, game_template_id, launch_descriptor_id, version_id," + + " release_bundle_id, generation_config_revision, version_state_epoch," + + " run_owned_start_request_id, run_owned_start_request_digest," + + " run_owned_start_published_release_bundle_ref, run_owned_start_preparing_epoch," + + " run_owned_start_active_epoch)" + + " VALUES (?, ?, 'fixture-runtime', 99, 'STARTING', 1, ?, 1, ?, 1, 1, ?, 1, ?, ?, ?, 1, 2)", + target.gameInstanceId(), + target.gameSessionTenantId(), + target.gameInstanceUuid(), + target.launchDescriptorId(), + target.generationConfigRevision(), + target.controlPlaneRequestId(), + RAW_SHA256, + target.publishedReleaseBundleRef()); + + tx.execute( + "INSERT INTO game_session_canonical_instance_launch" + + " (target_namespace, control_plane_request_id, game_session_tenant_id," + + " canonical_tenant_id, tenant_association_operation_id, tenant_association_request_id," + + " tenant_source_schema_version, tenant_source_target_namespace, tenant_source_request_id," + + " tenant_source_canonical_tenant_id, tenant_source_game_row_id," + + " tenant_source_game_tenant_key, tenant_source_provenance_kind, tenant_association_kind," + + " game_instance_id, game_instance_uuid, canonical_realm_id, world_slug," + + " playable_state_namespace_id, playable_state_scope, public_production," + + " captured_starting_row_version, game_template_id, launch_descriptor_id, version_id," + + " release_bundle_id, generation_config_revision, version_state_epoch," + + " complete_launch_binding_evidence)" + + " VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND'," + + " ?, ?, ?, ?, ?, 'SHARED', TRUE, 1, 1, ?, 1, 1, ?, 1," + + " jsonb_build_object('descriptor', jsonb_build_object('targetNamespace', ?," + + " 'controlPlaneRequestId', ?, 'canonicalTenantId', ?, 'worldSlug', ?," + + " 'gameTemplateId', '1', 'launchDescriptorId', ?, 'versionId', '1'," + + " 'releaseBundleId', '1', 'generationConfigRevision', ?, 'versionStateEpoch', '1'," + + " 'publishedReleaseBundleRef', ?), 'releaseAttestation'," + + " jsonb_build_object('canonicalVersionId', ?)))", + target.targetNamespace(), + target.controlPlaneRequestId(), + target.gameSessionTenantId(), + target.canonicalTenantId(), + target.tenantAssociationOperationId(), + target.tenantAssociationRequestId(), + target.targetNamespace(), + target.tenantAssociationRequestId(), + target.canonicalTenantId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.gameInstanceId(), + target.gameInstanceUuid(), + target.realmId(), + target.worldSlug(), + target.playableStateNamespaceId(), + target.launchDescriptorId(), + target.generationConfigRevision(), + target.targetNamespace(), + target.controlPlaneRequestId(), + target.canonicalTenantId().toString(), + target.worldSlug(), + target.launchDescriptorId(), + target.generationConfigRevision(), + target.publishedReleaseBundleRef(), + target.canonicalVersionId().toString()); + } + + public record RuntimeTarget( + 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 gameInstanceUuid, + UUID canonicalVersionId, + long runtimeVersionId, + long catalogRevision, + long pointerVersion, + String pointerSnapshotDigest, + long activeWorldEpoch, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + UUID holdId, + UUID holdFence, + String holdBindingDigest, + long auditEventId, + String ownerProofDigest, + Instant ownerProofTerminalAt, + String characterCreationPolicy, + long sourceGameRowId, + String sourceGameTenantKey, + UUID sourceIntakeOperationId, + UUID sourceIntakeRequestId, + UUID sourceRegistrationRequestId, + UUID sourceOperationId, + UUID tenantAssociationOperationId, + UUID tenantAssociationRequestId, + UUID catalogCreationRequestId, + String launchDescriptorId, + String generationConfigRevision, + String controlPlaneRequestId, + String publishedReleaseBundleRef) { + public CanonicalPlayableTarget playableTarget() { + return new CanonicalPlayableTarget( + targetNamespace, + tenantSlug, + canonicalTenantId, + worldSlug, + worldDisplayName, + realmId, + realmSlug, + realmDisplayName, + gameSessionTenantId, + gameInstanceId, + playableStateNamespaceId, + playableStateScope, + gameInstanceUuid, + canonicalVersionId, + runtimeVersionId, + catalogRevision, + pointerVersion, + pointerSnapshotDigest, + activeWorldEpoch, + initialAdmissionRequestId, + initialAdmissionRequestDigest, + OriginKind.NO_PRIOR_POINTER, + null, + holdId, + holdFence, + holdBindingDigest, + auditEventId, + ownerProofDigest, + Outcome.COMMITTED, + false, + ownerProofTerminalAt, + characterCreationPolicy); + } + + public CanonicalPlayableTarget admissionTarget() { + return playableTarget(); + } + + private static RuntimeTarget create( + UUID canonicalTenantId, + long gameSessionTenantId, + long gameInstanceId, + UUID gameInstanceUuid, + UUID playableStateNamespaceId) { + String token = UUID.randomUUID().toString().replace("-", ""); + String shortToken = token.substring(0, 10); + Instant terminalAt = Instant.now(); + return new RuntimeTarget( + "fixture-" + shortToken, + "tenant-" + shortToken, + canonicalTenantId, + "world-" + shortToken, + "Fixture World " + shortToken, + UUID.randomUUID(), + "main", + "Main Realm", + gameSessionTenantId, + gameInstanceId, + playableStateNamespaceId, + "SHARED", + gameInstanceUuid, + UUID.randomUUID(), + 1L, + 1L, + 1L, + RAW_SHA256, + 2L, + "initial-" + shortToken, + RAW_SHA256, + UUID.randomUUID(), + UUID.randomUUID(), + SHA256, + 1L, + SHA256, + terminalAt, + "PLAYER_CHOICE", + gameInstanceId + 50_000L, + "source-" + shortToken, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "descriptor-" + shortToken, + "generation-" + shortToken, + "launch-" + token, + "published-release-" + shortToken); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java new file mode 100644 index 0000000000..0491d686bf --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java @@ -0,0 +1,686 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.DriverManager; +import java.sql.Timestamp; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for V34.2 canonical gameplay integrity and runtime fence behavior. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayDecisionRuntimeFenceIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String RAW_SHA256 = "a".repeat(64); + private static final long LEGACY_TENANT_ID = 41L; + private static final long LEGACY_INSTANCE_ID = 7L; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void legacyRuntimeMutationAndDeletionEvaluateTheTypedCanonicalTenantFence() { + String schema = "gs_runtime_fence_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var schemaReadback = dsl.fetchOne("SELECT current_schema() AS actual_schema"); + assertThat(schemaReadback.get("actual_schema", String.class)).isEqualTo(schema); + assertSnapshotObligationIdentifiersCanonicalized(dsl, schema); + var triggerReadback = + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_trigger trigger_row" + + " JOIN pg_class relation ON relation.oid = trigger_row.tgrelid" + + " JOIN pg_namespace trigger_schema ON trigger_schema.oid = relation.relnamespace" + + " WHERE trigger_schema.nspname = ? AND relation.relname = ?" + + " AND trigger_row.tgname = ?) AS trigger_exists", + schema, + "game_instances", + "game_instances_lease_bound_binding_runtime_fence"); + assertThat(triggerReadback.get("trigger_exists", Boolean.class)).isTrue(); + + // This historical numeric-tenant row has no canonical launch association or candidate. + // V34 must still evaluate its candidate query without comparing UUID tenant IDs to bigint. + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id," + + " status, row_version, game_instance_uuid)" + + " VALUES (?, ?, 'legacy-runtime', 99, 'RUNNING', 0, ?)", + LEGACY_INSTANCE_ID, + LEGACY_TENANT_ID, + UUID.randomUUID()); + + assertThat( + dsl.execute( + "UPDATE game_instances SET status = 'STOPPED'" + + " WHERE tenant_id = ? AND id = ?", + LEGACY_TENANT_ID, + LEGACY_INSTANCE_ID)) + .isEqualTo(1); + var statusReadback = + dsl.fetchOne( + "SELECT status AS actual_status FROM game_instances" + + " WHERE tenant_id = ? AND id = ?", + LEGACY_TENANT_ID, + LEGACY_INSTANCE_ID); + assertThat(statusReadback.get("actual_status", String.class)).isEqualTo("STOPPED"); + assertThat( + dsl.execute( + "DELETE FROM game_instances WHERE tenant_id = ? AND id = ?", + LEGACY_TENANT_ID, + LEGACY_INSTANCE_ID)) + .isEqualTo(1); + } finally { + dropSchema(schema); + } + } + + @Test + void exactLeaseBoundCandidatePinsRuntimeAndRejectsTerminalTransition() { + String schema = "gs_runtime_fence_exact_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); + + markProvisional(dsl, target, candidateRef); + + assertThat( + dsl.execute( + "UPDATE game_instances SET runtime_version = 'unrelated-runtime-update'," + + " row_version = row_version + 1 WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .isEqualTo(1); + var unrelatedUpdateReadback = + dsl.fetchOne( + "SELECT runtime_version, row_version FROM game_instances" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + assertThat(unrelatedUpdateReadback.get("runtime_version", String.class)) + .isEqualTo("unrelated-runtime-update"); + assertThat(unrelatedUpdateReadback.get("row_version", Long.class)).isEqualTo(2L); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET status = 'STOPPED'" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining("runtime row is fenced"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET version_id = version_id + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining("runtime row is fenced"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET run_owned_start_request_id = 'replacement-start'" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining("runtime row is fenced"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET run_owned_start_published_release_bundle_ref =" + + " 'replacement-release-ref' WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining("runtime row is fenced"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET run_owned_start_active_epoch =" + + " run_owned_start_active_epoch + 1 WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining("runtime row is fenced"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_instances SET row_version = row_version - 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining("runtime row is fenced"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM game_instances WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .hasMessageContaining("runtime row is fenced"); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_binding_transition" + + " SET status = 'ABORTED' WHERE transition_id = (" + + " SELECT transition_id FROM game_session_canonical_binding_transition" + + " WHERE candidate_binding_ref = ?)", + candidateRef)) + .hasMessageContaining("terminal owner reconciliation"); + + assertThat( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM game_instances WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()), + "runtime row") + .get("status", String.class)) + .isEqualTo("RUNNING"); + assertThat( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE candidate_binding_ref = ?", + candidateRef), + "binding transition row") + .get("status", String.class)) + .isEqualTo("PROVISIONAL"); + } finally { + dropSchema(schema); + } + } + + @Test + void stoppedRuntimeCannotAcquireLeaseBoundBindingFence() { + String schema = "gs_runtime_fence_stopped_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); + assertThat( + dsl.execute( + "UPDATE game_instances SET status = 'STOPPED'" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) + .isEqualTo(1); + + assertThatThrownBy(() -> markProvisional(dsl, target, candidateRef)) + .hasMessageContaining("exact current RUNNING launch row and candidate identity"); + assertThat( + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE candidate_binding_ref = ?", + candidateRef), + "binding transition row") + .get("status", String.class)) + .isEqualTo("PREPARED"); + } finally { + dropSchema(schema); + } + } + + @Test + void mismatchedCandidateTenantRuntimeOrCanonicalInstanceCannotAcquireFence() { + String schema = "gs_runtime_fence_candidate_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + + for (CandidateMismatch mismatch : CandidateMismatch.values()) { + if (mismatch == CandidateMismatch.NONE) { + continue; + } + byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, mismatch); + assertThatThrownBy(() -> markProvisional(dsl, target, candidateRef)) + .as("candidate mismatch %s", mismatch) + .hasMessageContaining("exact current RUNNING launch row and candidate identity"); + } + } finally { + dropSchema(schema); + } + } + + @Test + void retainedTenantPayloadAndHoldCannotBeTruncatedAroundTheirRowGuards() { + String schema = "gs_retained_truncate_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + + assertThatThrownBy( + () -> dsl.execute("TRUNCATE game_session_retained_tenant_association_payload")) + .hasMessageContaining("expiry cannot be bypassed"); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE game_session_retained_tenant_association_legal_hold")) + .hasMessageContaining("audit cannot be bypassed"); + } finally { + dropSchema(schema); + } + } + + @Test + void launchPreparationMustReferenceTheFullImmutableCatalogIdentity() { + String schema = "gs_launch_prep_identity_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget otherSourceIntakeOwner = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + dsl, UUID.randomUUID(), 2L, 24L, UUID.randomUUID()); + + assertThat( + insertLaunchPreparation( + dsl, + target, + target.realmId(), + target.catalogCreationRequestId(), + target.catalogRevision(), + target.canonicalTenantId(), + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId())) + .isEqualTo(1); + assertLaunchPreparationCatalogMismatchRejected( + dsl, + target, + target.realmId(), + UUID.randomUUID(), + target.catalogRevision(), + target.canonicalTenantId(), + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId()); + assertLaunchPreparationCatalogMismatchRejected( + dsl, + target, + target.realmId(), + target.catalogCreationRequestId(), + target.catalogRevision() + 1, + target.canonicalTenantId(), + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId()); + assertLaunchPreparationCatalogMismatchRejected( + dsl, + target, + target.realmId(), + target.catalogCreationRequestId(), + target.catalogRevision(), + UUID.randomUUID(), + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId()); + assertLaunchPreparationCatalogMismatchRejected( + dsl, + target, + target.realmId(), + target.catalogCreationRequestId(), + target.catalogRevision(), + target.canonicalTenantId(), + otherSourceIntakeOwner.sourceIntakeOperationId(), + target.sourceIntakeRequestId()); + assertLaunchPreparationCatalogMismatchRejected( + dsl, + target, + target.realmId(), + target.catalogCreationRequestId(), + target.catalogRevision(), + target.canonicalTenantId(), + target.sourceIntakeOperationId(), + UUID.randomUUID()); + assertLaunchPreparationCatalogMismatchRejected( + dsl, + target, + UUID.randomUUID(), + target.catalogCreationRequestId(), + target.catalogRevision(), + target.canonicalTenantId(), + target.sourceIntakeOperationId(), + target.sourceIntakeRequestId()); + } finally { + dropSchema(schema); + } + } + + private static void migrate(String schema, DriverManagerDataSource dataSource) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private static void assertSnapshotObligationIdentifiersCanonicalized( + DSLContext dsl, String schema) { + var canonicalTables = + dsl.fetchOne( + "SELECT count(*) AS actual_count FROM pg_class relation" + + " JOIN pg_namespace relation_schema ON relation_schema.oid = relation.relnamespace" + + " WHERE relation_schema.nspname = ? AND relation.relkind = 'r'" + + " AND relation.relname IN (?, ?)", + schema, + "gs_canonical_account_coverage_snapshot_issuer_obligation", + "gs_canonical_account_coverage_snapshot_region_obligation"); + assertThat(canonicalTables.get("actual_count", Long.class)).isEqualTo(2L); + + var canonicalForeignKeys = + dsl.fetchOne( + "SELECT count(*) AS actual_count FROM pg_constraint constraint_row" + + " JOIN pg_class relation ON relation.oid = constraint_row.conrelid" + + " JOIN pg_namespace relation_schema ON relation_schema.oid = relation.relnamespace" + + " JOIN pg_class referenced_relation ON referenced_relation.oid = constraint_row.confrelid" + + " JOIN pg_namespace referenced_schema" + + " ON referenced_schema.oid = referenced_relation.relnamespace" + + " JOIN pg_attribute source_column ON source_column.attrelid = relation.oid" + + " AND source_column.attnum = constraint_row.conkey[1]" + + " AND source_column.attname = 'operation_id'" + + " JOIN pg_attribute referenced_column" + + " ON referenced_column.attrelid = referenced_relation.oid" + + " AND referenced_column.attnum = constraint_row.confkey[1]" + + " AND referenced_column.attname = 'operation_id'" + + " WHERE constraint_row.contype = 'f' AND relation_schema.nspname = ?" + + " AND referenced_schema.nspname = ?" + + " AND array_length(constraint_row.conkey, 1) = 1" + + " AND array_length(constraint_row.confkey, 1) = 1" + + " AND referenced_relation.relname =" + + " 'game_session_canonical_account_coverage_operation'" + + " AND ((relation.relname = ? AND constraint_row.conname = ?)" + + " OR (relation.relname = ? AND constraint_row.conname = ?))", + schema, + schema, + "gs_canonical_account_coverage_snapshot_issuer_obligation", + "fk_gs_account_coverage_snapshot_issuer_operation", + "gs_canonical_account_coverage_snapshot_region_obligation", + "fk_gs_account_coverage_snapshot_region_operation"); + assertThat(canonicalForeignKeys.get("actual_count", Long.class)).isEqualTo(2L); + + var legacyTables = + dsl.fetchOne( + "SELECT count(*) AS actual_count FROM pg_class relation" + + " JOIN pg_namespace relation_schema ON relation_schema.oid = relation.relnamespace" + + " WHERE relation_schema.nspname = ? AND relation.relkind = 'r'" + + " AND relation.relname IN (?, ?)", + schema, + "game_session_canonical_account_coverage_snapshot_issuer_obligat", + "game_session_canonical_account_coverage_snapshot_region_obligat"); + assertThat(legacyTables.get("actual_count", Long.class)).isZero(); + + var legacyForeignKeys = + dsl.fetchOne( + "SELECT count(*) AS actual_count FROM pg_constraint constraint_row" + + " JOIN pg_class relation ON relation.oid = constraint_row.conrelid" + + " JOIN pg_namespace relation_schema ON relation_schema.oid = relation.relnamespace" + + " WHERE relation_schema.nspname = ? AND constraint_row.contype = 'f'" + + " AND constraint_row.conname IN (?, ?)", + schema, + "fk_gs_canonical_account_coverage_snapshot_issuer_obligation_ope", + "fk_gs_canonical_account_coverage_snapshot_region_obligation_ope"); + assertThat(legacyForeignKeys.get("actual_count", Long.class)).isZero(); + } + + private static byte[] seedCandidateAndPreparedTransition( + DSLContext dsl, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, + CandidateMismatch mismatch) { + CanonicalPlayableTarget playableTarget = target.playableTarget(); + UUID candidateTenant = + mismatch == CandidateMismatch.TENANT ? UUID.randomUUID() : target.canonicalTenantId(); + long candidateRuntimeId = + mismatch == CandidateMismatch.RUNTIME_GAME_INSTANCE_ID + ? target.gameInstanceId() + 1 + : target.gameInstanceId(); + UUID candidateGameInstanceUuid = + mismatch == CandidateMismatch.CANONICAL_GAME_INSTANCE_UUID + ? UUID.randomUUID() + : target.gameInstanceUuid(); + UUID transitionId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + UUID issuerId = UUID.randomUUID(); + UUID accountIndexFence = UUID.randomUUID(); + UUID issuerReservationId = UUID.randomUUID(); + byte[] candidateRef = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8); + + dsl.execute( + "INSERT INTO game_session_canonical_gameplay_binding_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 (?, ?, ?, ?, ?, 'SHARED', ?, ?, ?, 1, ?, 12, ?, 1, 1, 1, 1, 0, ?, ?, ?," + + " 'CANDIDATE_PREPARED', 'REPAIR_REQUIRED', 'REPAIR_REQUIRED', 1)", + candidateRef, + accountId, + candidateTenant, + playableTarget.playableStateNamespaceId(), + characterId, + candidateGameInstanceUuid, + candidateRuntimeId, + UUID.randomUUID().toString(), + regionId, + issuerId, + accountIndexFence, + issuerReservationId, + transitionId); + dsl.execute( + "INSERT INTO game_session_canonical_binding_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)" + + " VALUES (?, ?, ?, ?, NULL, NULL, ?, 1, ?, ?, 'PREPARED', 1)", + transitionId, + target.canonicalTenantId(), + playableTarget.playableStateNamespaceId(), + characterId, + candidateRef, + accountIndexFence, + issuerReservationId); + return candidateRef; + } + + private static void markProvisional( + DSLContext dsl, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget, + byte[] candidateRef) { + CanonicalPlayableTarget target = runtimeTarget.playableTarget(); + dsl.execute( + "UPDATE game_session_canonical_binding_transition SET" + + " status = 'PROVISIONAL', admission_request_id = ?, admission_lease_id = ?," + + " admission_lease_fence = 1, admission_lease_kind = 'NEW_BINDING'," + + " admission_lease_digest = ?, admission_lease_evidence = '{}'," + + " admission_lease_expires_at = 9999999999999," + + " 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 = 'NO_PRIOR_POINTER'," + + " 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 = 'COMMITTED'," + + " admission_target_positive_durable_abort = FALSE, admission_target_terminal_at = ?," + + " admission_target_character_creation_policy = ?" + + " WHERE candidate_binding_ref = ?", + UUID.randomUUID(), + UUID.randomUUID(), + RAW_SHA256, + target.targetNamespace(), + target.tenantSlug(), + target.canonicalTenantId(), + target.worldSlug(), + target.worldDisplayName(), + target.realmId(), + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.runtimeVersionId(), + target.catalogRevision(), + target.pointerVersion(), + target.admissionPointerSnapshotDigest(), + target.activeWorldEpoch(), + target.initialAdmissionRequestId(), + target.initialAdmissionRequestDigest(), + target.holdId(), + target.holdFence(), + target.holdBindingDigest(), + target.auditEventId(), + target.ownerProofDigest(), + Timestamp.from(target.ownerProofTerminalAt()), + target.characterCreationPolicy(), + candidateRef); + } + + private static void assertLaunchPreparationCatalogMismatchRejected( + DSLContext dsl, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + UUID sourceIntakeRequestId) { + assertThatThrownBy( + () -> + insertLaunchPreparation( + dsl, + target, + realmId, + catalogCreationRequestId, + catalogRevision, + canonicalTenantId, + sourceIntakeOperationId, + sourceIntakeRequestId)) + .hasMessageContaining("fk_gs_canonical_launch_preparation_catalog"); + } + + private static int insertLaunchPreparation( + DSLContext dsl, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + UUID sourceIntakeRequestId) { + return dsl.execute( + "INSERT INTO game_session_canonical_launch_preparation" + + " (target_namespace, control_plane_request_id, operation_id," + + " acting_account_uuid, canonical_tenant_id, realm_id," + + " catalog_creation_request_id, catalog_revision," + + " source_intake_operation_id, source_intake_request_id," + + " source_registration_request_id, source_operation_id," + + " catalog_request_digest, catalog_receipt_digest," + + " source_intake_request_digest, source_intake_receipt_digest," + + " source_evidence_digest, descriptor_request_digest," + + " descriptor_result_digest, request_digest, receipt_digest," + + " request_evidence_json, catalog_evidence_json," + + " source_intake_evidence_json, launch_descriptor_evidence_json)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " '{}'::jsonb, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb)", + target.targetNamespace(), + "preparation-" + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + canonicalTenantId, + realmId, + catalogCreationRequestId, + catalogRevision, + sourceIntakeOperationId, + sourceIntakeRequestId, + target.sourceRegistrationRequestId(), + target.sourceOperationId(), + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256, + "sha256:" + RAW_SHA256); + } + + private enum CandidateMismatch { + NONE, + TENANT, + RUNTIME_GAME_INSTANCE_ID, + CANONICAL_GAME_INSTANCE_UUID + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void dropSchema(String schema) { + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Failed to dispose runtime-fence test schema", failure); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java new file mode 100644 index 0000000000..efc760bdd8 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java @@ -0,0 +1,142 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.UUID; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for the V34.3 initial-admission intent request identity width. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String RAW_SHA256 = "a".repeat(64); + private static final String SHA256 = "sha256:" + RAW_SHA256; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void intentLedgerAcceptsAttemptWidthAndRejectsAnIdentityBeyond128Characters() { + String schema = "gs_intent_width_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var schemaReadback = dsl.fetchOne("SELECT current_schema() AS actual_schema"); + assertThat(schemaReadback.get("actual_schema", String.class)).isEqualTo(schema); + + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget length121 = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + dsl, UUID.randomUUID(), 2L, 24L, UUID.randomUUID()); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget length128 = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + dsl, UUID.randomUUID(), 3L, 25L, UUID.randomUUID()); + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget length129 = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + dsl, UUID.randomUUID(), 4L, 26L, UUID.randomUUID()); + + assertThat(insertIntent(dsl, length121, "r".repeat(121))).isEqualTo(1); + assertThat(insertIntent(dsl, length128, "r".repeat(128))).isEqualTo(1); + assertThatThrownBy(() -> insertIntent(dsl, length129, "r".repeat(129))) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> assertThat(exception.sqlState()).isEqualTo("22001")); + } finally { + dropSchema(schema); + } + } + + private static int insertIntent( + DSLContext dsl, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, + String requestId) { + return dsl.execute( + "INSERT INTO game_session_canonical_initial_admission_intent" + + " (target_namespace, initial_admission_request_id, request_digest," + + " canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id," + + " playable_state_scope, catalog_visible, catalog_public_production," + + " catalog_revision, catalog_creation_request_id, catalog_request_digest," + + " catalog_receipt_digest, tenant_association_operation_id, game_session_tenant_id," + + " canonical_game_instance_id, game_instance_id, canonical_version_id," + + " runtime_version_id, control_plane_request_id, launch_descriptor_id," + + " captured_starting_row_version, current_row_version, descriptor_request_digest," + + " descriptor_result_digest, release_attestation_digest, canonical_hold_request_bytes," + + " canonical_lifecycle_request_bytes, hold_identity_bytes, state, created_at," + + " updated_at, terminal_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 0, 1, ?, ?, ?, decode('01', 'hex'), decode('02', 'hex'), NULL, 'PENDING_HOLD'," + + " now(), now(), NULL)", + target.targetNamespace(), + requestId, + RAW_SHA256, + target.canonicalTenantId(), + target.worldSlug(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.catalogRevision(), + target.catalogCreationRequestId(), + SHA256, + SHA256, + target.tenantAssociationOperationId(), + target.gameSessionTenantId(), + target.gameInstanceUuid(), + target.gameInstanceId(), + target.canonicalVersionId(), + target.runtimeVersionId(), + target.controlPlaneRequestId(), + target.launchDescriptorId(), + SHA256, + SHA256, + SHA256); + } + + private static void migrate(String schema, DriverManagerDataSource dataSource) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static void dropSchema(String schema) { + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Failed to dispose intent-width test schema", failure); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..3d2d976ef8 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java @@ -0,0 +1,406 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayLegacyMigrationRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void durableFenceAndPhysicalIdentityDoNotPublishV31BeforeReadback() { + String schema = "gs_legacy_migration_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = dslForSchema(dataSource, schema); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var repository = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var identity = identity(); + var operation = repository.begin(cohortId, writerFence, identity); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return identity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + assertThat(expectedIdentity).isEqualTo(identity); + } + }; + + assertThat(operation.state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.FENCED); + var initialDisposition = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition" + + " WHERE singleton_id = 1"), + "initial legacy disposition row"); + assertThat(initialDisposition.get("disposition_state", String.class)).isEqualTo("REQUIRED"); + assertThatThrownBy(() -> repository.publishVerified(operation.operationId(), fencedCohort)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Only exact complete readback"); + assertThat(repository.read(operation.operationId()).state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.FENCED); + var retainedDisposition = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition" + + " WHERE singleton_id = 1"), + "retained legacy disposition row"); + assertThat(retainedDisposition.get("disposition_state", String.class)).isEqualTo("REQUIRED"); + } finally { + dropSchema(schema); + } + } + + @Test + void futureRevisionRowsBlockInsteadOfDisappearingFromTheCanonicalSnapshot() { + String schema = "gs_legacy_future_revision_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = dslForSchema(dataSource, schema); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest.seedActiveSource( + dsl, + CanonicalGameplayBindingInventoryRepositoryIntegrationTest.identity( + "dddddddd-dddd-4ddd-8ddd-dddddddddddd")); + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = 7 WHERE singleton_id = 1"); + + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var repository = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + var operation = repository.begin(UUID.randomUUID(), UUID.randomUUID(), identity()); + var canonical = inventory.readSnapshot(); + assertThat(canonical.inventoryRevision()).isEqualTo(java.math.BigInteger.valueOf(7)); + assertThat(canonical.bindings()).isEmpty(); + + assertThatThrownBy( + () -> + repository.captureSnapshots( + operation.operationId(), emptyLegacySnapshot(), canonical)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("rows beyond the inventory clock"); + assertThat(repository.read(operation.operationId()).state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.FENCED); + var inventoryRowCount = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) AS row_count FROM game_session_canonical_gameplay_binding_inventory"), + "canonical inventory row count"); + assertThat(inventoryRowCount.get("row_count", Long.class)).isEqualTo(1L); + } finally { + dropSchema(schema); + } + } + + @Test + void nonemptyLegacyInventoryBlocksBeforeAnyIndexRebuildOrSourceDeletion() { + String schema = "gs_legacy_nonempty_source_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = dslForSchema(dataSource, schema); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var repository = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + var cohortId = UUID.randomUUID(); + var writerFence = UUID.randomUUID(); + var identity = identity(); + var cohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return identity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + assertThat(expectedIdentity).isEqualTo(identity); + } + }; + var retainedSourceRows = new ArrayList<>(List.of("sessionctx:tenant:retained")); + var rebuildCalls = new AtomicInteger(); + var owner = + new CanonicalGameplayLegacyMigrationOwner( + repository, + inventory, + () -> cohort, + ignored -> + new CanonicalGameplayLegacyMigrationSourceSnapshot( + completeLegacyFamilies(), + List.of( + new CanonicalGameplayLegacyMigrationSourceSnapshot.Entry( + CanonicalGameplayLegacyMigrationSourceSnapshot.Family + .TENANT_SESSION_CONTEXT, + "sha256:" + "a".repeat(64), + CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition + .UNMAPPABLE))), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + CanonicalGameplayLegacyMigrationSourceSnapshot legacySnapshot, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonicalSnapshot) { + rebuildCalls.incrementAndGet(); + retainedSourceRows.clear(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonicalSnapshot) { + throw new AssertionError("readback must not run for a blocked retained source"); + } + }); + + var operation = owner.migrate(); + + assertThat(operation.state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.BLOCKED); + assertThat(operation.blockedReason()).isEqualTo("UNMAPPABLE_SOURCE_RECORD"); + assertThat(rebuildCalls.get()).isZero(); + assertThat(retainedSourceRows).containsExactly("sessionctx:tenant:retained"); + var blockedDisposition = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition" + + " WHERE singleton_id = 1"), + "blocked legacy disposition row"); + assertThat(blockedDisposition.get("disposition_state", String.class)).isEqualTo("REQUIRED"); + } finally { + dropSchema(schema); + } + } + + @Test + void ownerRetainsOriginalAdapterFailureAndSuppressedBlockPersistenceFailure() { + String schema = "gs_legacy_owner_failure_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + migrate(schema, dataSource); + DSLContext dsl = dslForSchema(dataSource, schema); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var repository = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var identity = identity(); + IllegalStateException originalFailure = + new IllegalStateException("source snapshot adapter failed after cohort fencing"); + var cohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return identity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + assertThat(expectedIdentity).isEqualTo(identity); + } + }; + var owner = + new CanonicalGameplayLegacyMigrationOwner( + repository, + inventory, + () -> { + // This test-only constraint forces owner.block() to fail after the adapter error. + dsl.execute( + "ALTER TABLE game_session_canonical_legacy_migration_operation" + + " ADD CONSTRAINT reject_owner_block_for_test" + + " CHECK (state <> 'BLOCKED') NOT VALID"); + return cohort; + }, + ignored -> { + throw originalFailure; + }, + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + CanonicalGameplayLegacyMigrationSourceSnapshot legacySnapshot, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonicalSnapshot) { + throw new AssertionError("rebuild must not run after source capture fails"); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonicalSnapshot) { + throw new AssertionError("readback must not run after source capture fails"); + } + }); + + assertThatThrownBy(owner::migrate) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()).isSameAs(originalFailure); + assertThat(originalFailure.getSuppressed()).hasSize(1); + assertThat(originalFailure.getSuppressed()[0]) + .hasMessageContaining("reject_owner_block_for_test"); + }); + UUID operationId = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "SELECT operation_id FROM game_session_canonical_legacy_migration_operation" + + " WHERE cohort_id = ?", + cohortId), + "migration operation row") + .get("operation_id", UUID.class); + assertThat(repository.read(operationId).state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.FENCED); + } finally { + dropSchema(schema); + } + } + + private static CanonicalGameplayLegacyMigrationStorageIdentity identity() { + return new CanonicalGameplayLegacyMigrationStorageIdentity( + "cluster-uid", + "namespace-uid", + "producer-pod-uid", + "container-id", + "node-uid", + "987654321", + 42L, + "postgres-volume-uid", + "redis-run-id", + "redis-volume-uid"); + } + + private static CanonicalGameplayLegacyMigrationSourceSnapshot emptyLegacySnapshot() { + return new CanonicalGameplayLegacyMigrationSourceSnapshot(completeLegacyFamilies(), List.of()); + } + + private static EnumSet + completeLegacyFamilies() { + return EnumSet.of( + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.TENANT_SESSION_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.SESSION_ALIAS_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_IDENTITY_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_NAME_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.MOVEMENT_EFFECT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.DURABLE_EFFECT); + } + + private static void migrate(String schema, DriverManagerDataSource dataSource) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + } + + private static DriverManagerDataSource dataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + // Testcontainers already appends loggerLevel=OFF to the JDBC URL, so add currentSchema with + // '&' to keep both parameters and bind later repository connections to Flyway's schema. + String jdbcUrl = postgres.getJdbcUrl(); + String separator = jdbcUrl.contains("?") ? "&" : "?"; + dataSource.setUrl(jdbcUrl + separator + "currentSchema=" + schema); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static DSLContext dslForSchema(DriverManagerDataSource dataSource, String schema) { + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + var schemaReadback = dsl.fetchOne("SELECT current_schema() AS actual_schema"); + assertThat(schemaReadback.get("actual_schema", String.class)).isEqualTo(schema); + var operationReadback = + dsl.fetchOne( + "SELECT to_regclass('game_session_canonical_legacy_migration_operation')::text" + + " AS relation_name"); + assertThat(operationReadback.get("relation_name", String.class)) + .isEqualTo("game_session_canonical_legacy_migration_operation"); + return dsl; + } + + private static void dropSchema(String schema) { + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Failed to dispose legacy migration test schema", failure); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java index 2852f723e7..a3541a69fe 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java @@ -65,7 +65,10 @@ void setUpRepository() { @BeforeEach void cleanTables() { - dsl.execute("TRUNCATE TABLE script_pin_operation, game_instances CASCADE"); + // These are this fixture's only test-owned rows. Use bounded row deletes instead of + // TRUNCATE: V26 protects immutable launch evidence and runtime history from truncation. + dsl.execute("DELETE FROM script_pin_operation WHERE tenant_id = 1 AND game_instance_id = 7"); + dsl.execute("DELETE FROM game_instances WHERE tenant_id = 1 AND id = 7"); dsl.insertInto(GAME_INSTANCES) .set(GAME_INSTANCES.ID, 7L) .set(GAME_INSTANCES.TENANT_ID, 1L) diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java new file mode 100644 index 0000000000..c39adcca1c --- /dev/null +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java @@ -0,0 +1,72 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.slf4j.LoggerFactory; + +class CanonicalGameplayMigrationDriverStdoutTest { + private static final String DIAGNOSTIC_MARKER = "migration-driver-diagnostic-probe"; + private static final String PROTOCOL_FRAME = "{\"protocol\":\"ready\"}"; + + @Test + void slf4jDiagnosticsUseStderrAndProtocolFramesKeepOriginalStdout(@TempDir Path tempDir) + throws Exception { + String classpath = System.getProperty("firemud.migration-driver-test-classpath"); + assertThat(classpath).isNotBlank(); + String javaExecutable = + System.getProperty("os.name").toLowerCase().contains("windows") ? "java.exe" : "java"; + Path java = Path.of(System.getProperty("java.home"), "bin", javaExecutable); + Path argumentFile = tempDir.resolve("migration-driver.args"); + Files.writeString( + argumentFile, + javaArgument("-cp") + + System.lineSeparator() + + javaArgument(classpath) + + System.lineSeparator() + + javaArgument(LoggingProbe.class.getName()) + + System.lineSeparator(), + StandardCharsets.UTF_8); + Path stdoutFile = tempDir.resolve("child.stdout"); + Path stderrFile = tempDir.resolve("child.stderr"); + Process process = + new ProcessBuilder(java.toString(), "@" + argumentFile) + .redirectOutput(stdoutFile.toFile()) + .redirectError(stderrFile.toFile()) + .start(); + + boolean exited = process.waitFor(Duration.ofSeconds(30).toMillis(), TimeUnit.MILLISECONDS); + if (!exited) { + process.destroyForcibly(); + process.waitFor(); + } + byte[] stdout = Files.readAllBytes(stdoutFile); + byte[] stderr = Files.readAllBytes(stderrFile); + + assertThat(exited).isTrue(); + assertThat(process.exitValue()).isZero(); + assertThat(new String(stdout, StandardCharsets.UTF_8)).isEqualTo(PROTOCOL_FRAME + "\n"); + assertThat(new String(stderr, StandardCharsets.UTF_8)).contains(DIAGNOSTIC_MARKER); + } + + private static String javaArgument(String argument) { + return "\"" + argument.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; + } + + public static final class LoggingProbe { + private LoggingProbe() {} + + public static void main(String[] args) { + var protocolOutput = + CanonicalGameplayMigrationDriverLauncher.preserveProtocolOutputAndRedirectDiagnostics(); + LoggerFactory.getLogger(LoggingProbe.class).warn(DIAGNOSTIC_MARKER); + protocolOutput.println(PROTOCOL_FRAME); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIdentityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIdentityTest.java new file mode 100644 index 0000000000..ccfd820329 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingIdentityTest.java @@ -0,0 +1,52 @@ +package unit.net.firedevops.firemud.gamesession.binding; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayBindingIdentityTest { + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID NAMESPACE_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CHARACTER_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID GAME_INSTANCE_ID = + UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID REGION_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID ISSUER_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + + @Test + void acceptsCanonicalNonNilSessionUuid() { + assertThatCode(() -> identity("88888888-8888-4888-8888-888888888888")) + .doesNotThrowAnyException(); + } + + @Test + void rejectsNilSessionUuidConsistentWithV29StorageConstraint() { + assertThatThrownBy(() -> identity("00000000-0000-0000-0000-000000000000")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sessionId must use canonical UUID text"); + } + + private static CanonicalGameplayBindingIdentity identity(String sessionId) { + return new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + "SHARED", + GAME_INSTANCE_ID, + 1L, + sessionId, + REGION_ID, + BigInteger.ONE, + ISSUER_ID, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java new file mode 100644 index 0000000000..87790d4fc6 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java @@ -0,0 +1,68 @@ +package net.firedevops.firemud.gamesession.dto; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class CanonicalInitialAdmissionRequestTest { + @Test + void initialAdmissionRequestIdMatches128CharacterOwnerAndIntentBounds() { + for (int length : new int[] {120, 121, 128}) { + request("r".repeat(length)); + } + + assertThatThrownBy(() -> request("r".repeat(129))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("initialAdmissionRequestId must contain 1..128 characters"); + } + + private static CanonicalInitialAdmissionRequest request(String requestId) { + String targetNamespace = "firemud-prod"; + UUID tenantId = UUID.randomUUID(); + String worldSlug = "world"; + UUID realmId = UUID.randomUUID(); + UUID playableStateNamespaceId = UUID.randomUUID(); + String playableStateScope = "SHARED"; + UUID gameInstanceId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + long lifecycleEpoch = 1L; + long catalogRevision = 1L; + CanonicalInitialAdmissionRequest.OriginKind originKind = + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER; + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + targetNamespace, + tenantId, + worldSlug, + realmId, + playableStateNamespaceId, + playableStateScope, + gameInstanceId, + versionId, + lifecycleEpoch, + catalogRevision, + originKind, + null, + requestId); + + return new CanonicalInitialAdmissionRequest( + targetNamespace, + tenantId, + worldSlug, + realmId, + playableStateNamespaceId, + playableStateScope, + gameInstanceId, + versionId, + lifecycleEpoch, + catalogRevision, + originKind, + null, + requestId, + requestDigest, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventorySqlTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventorySqlTest.java new file mode 100644 index 0000000000..98a3a354a7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventorySqlTest.java @@ -0,0 +1,336 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.mockito.invocation.Invocation; + +class CanonicalGameplayBindingInventorySqlTest { + private static final Pattern INSERT = + Pattern.compile( + "(?is)INSERT\\s+INTO\\s+([a-z0-9_]+)\\s*\\((.*?)\\)\\s*VALUES\\s*\\((.*?)\\)"); + private static final long RUNTIME_GAME_INSTANCE_ID = 918273645L; + private static final BigInteger REGION_EPOCH = new BigInteger("76543210987654321"); + + @Test + void everyInventoryInsertHelperKeepsColumnsValuesAndBindingsAligned() throws Exception { + DSLContext dsl = mock(DSLContext.class); + Fixture fixture = fixture(); + + Record coverageControl = mock(Record.class); + Mockito.when(coverageControl.get("state", String.class)) + .thenReturn("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + Mockito.doReturn(coverageControl) + .when(dsl) + .fetchOne(Mockito.anyString(), Mockito.any(Object[].class)); + + invoke("ensureGenerationRow", dsl, fixture.request().candidate()); + invoke("lockAccountCoverageEvidence", dsl, fixture.request().candidate().accountId()); + invoke("insertCandidate", dsl, fixture.request(), fixture.prepared(), fixture.partitionId()); + invoke("insertTransition", dsl, fixture.request(), fixture.prepared(), null); + invoke("insertAccountObligations", dsl, fixture.request(), fixture.prepared(), null, null); + + Record activeBinding = mock(Record.class); + UUID priorAccountId = UUID.fromString("814f3be2-c891-4a67-bdd1-d73a5c72d43e"); + UUID priorTenantId = UUID.fromString("245f3e61-b457-4ce2-b634-1d97a45fb37a"); + UUID priorFence = UUID.fromString("3c5b9d6f-0504-42f1-8d2c-f55d84a1bd33"); + Mockito.when(activeBinding.get("binding_ref", byte[].class)).thenReturn(new byte[] {4, 2, 7}); + Mockito.when(activeBinding.get("account_id", UUID.class)).thenReturn(priorAccountId); + Mockito.when(activeBinding.get("tenant_id", UUID.class)).thenReturn(priorTenantId); + Mockito.when(activeBinding.get("binding_generation", BigDecimal.class)) + .thenReturn(new BigDecimal("314159")); + Mockito.when(activeBinding.get("account_index_fence", UUID.class)).thenReturn(priorFence); + invoke( + "insertAccountObligations", + dsl, + fixture.request(), + fixture.prepared(), + activeBinding, + null); + + invoke( + "insertReservation", + dsl, + fixture.request(), + fixture.prepared(), + fixture.partitionId(), + fixture.prepared().inventoryRevision()); + invoke("insertIssuerObligation", dsl, fixture.prepared()); + invoke("insertRegionObligation", dsl, fixture.prepared()); + + List inserts = capturedInserts(dsl); + assertEquals(10, inserts.size(), "all nine INSERT constructions and the repeated ADD branch"); + Map> byTable = new HashMap<>(); + for (InsertCall insert : inserts) { + BoundInsert bound = validateShapeAndBind(insert); + byTable.computeIfAbsent(bound.table(), ignored -> new ArrayList<>()).add(bound); + } + + assertEquals(1, byTable.get("game_session_canonical_binding_generation").size()); + assertEquals(1, byTable.get("game_session_canonical_account_coverage_control").size()); + assertEquals(1, byTable.get("game_session_canonical_gameplay_binding_inventory").size()); + assertEquals(1, byTable.get("game_session_canonical_binding_transition").size()); + List accountObligations = + byTable.get("game_session_canonical_binding_account_index_obligation"); + assertEquals(3, accountObligations.size()); + assertEquals("ADD_OR_RETAIN", accountObligations.get(0).literal("action")); + assertEquals("ADD_OR_RETAIN", accountObligations.get(1).literal("action")); + assertEquals("REMOVE", accountObligations.get(2).literal("action")); + assertEquals( + accountObligations.get(0).value("transition_id"), + accountObligations.get(1).value("transition_id")); + assertArrayEquals( + (byte[]) accountObligations.get(0).value("binding_ref"), + (byte[]) accountObligations.get(1).value("binding_ref")); + assertEquals( + accountObligations.get(0).value("account_id"), + accountObligations.get(1).value("account_id")); + assertEquals( + accountObligations.get(0).value("tenant_id"), accountObligations.get(1).value("tenant_id")); + assertEquals( + accountObligations.get(0).value("binding_generation"), + accountObligations.get(1).value("binding_generation")); + assertEquals( + accountObligations.get(0).value("account_index_fence"), + accountObligations.get(1).value("account_index_fence")); + assertEquals( + accountObligations.get(0).value("inventory_revision"), + accountObligations.get(1).value("inventory_revision")); + assertTrue(accountObligations.get(0).isBoundNull("expected_prior_generation")); + assertTrue(accountObligations.get(1).isBoundNull("expected_prior_generation")); + BoundInsert removeObligation = accountObligations.get(2); + assertEquals(priorAccountId, removeObligation.value("account_id")); + assertEquals(priorTenantId, removeObligation.value("tenant_id")); + assertArrayEquals(new byte[] {4, 2, 7}, (byte[]) removeObligation.value("binding_ref")); + assertEquals(new BigDecimal("314159"), removeObligation.value("binding_generation")); + assertEquals(new BigDecimal("314159"), removeObligation.value("expected_prior_generation")); + assertEquals(priorFence, removeObligation.value("account_index_fence")); + assertEquals(1, byTable.get("game_session_canonical_issuer_partition_reservation").size()); + assertEquals(1, byTable.get("game_session_canonical_binding_issuer_index_obligation").size()); + assertEquals(1, byTable.get("game_session_canonical_binding_region_bridge_obligation").size()); + + BoundInsert candidate = byTable.get("game_session_canonical_gameplay_binding_inventory").get(0); + assertEquals(RUNTIME_GAME_INSTANCE_ID, candidate.value("runtime_game_instance_id")); + assertEquals(new BigDecimal(REGION_EPOCH), candidate.value("region_epoch")); + assertEquals("CANDIDATE_PREPARED", candidate.literal("lifecycle")); + + BoundInsert reservation = + byTable.get("game_session_canonical_issuer_partition_reservation").get(0); + assertEquals(RUNTIME_GAME_INSTANCE_ID, reservation.value("runtime_game_instance_id")); + assertEquals(new BigDecimal(REGION_EPOCH), reservation.value("region_epoch")); + assertEquals("RESERVED", reservation.literal("lifecycle")); + + BoundInsert regionObligation = + byTable.get("game_session_canonical_binding_region_bridge_obligation").get(0); + assertEquals(RUNTIME_GAME_INSTANCE_ID, regionObligation.value("runtime_game_instance_id")); + assertEquals(new BigDecimal(REGION_EPOCH), regionObligation.value("region_epoch")); + assertEquals("REQUIRED", regionObligation.literal("status")); + } + + private static void invoke(String methodName, Object... arguments) throws Exception { + Method method = + Arrays.stream(CanonicalGameplayBindingInventoryRepository.class.getDeclaredMethods()) + .filter(candidate -> candidate.getName().equals(methodName)) + .filter(candidate -> candidate.getParameterCount() == arguments.length) + .findFirst() + .orElseThrow(() -> new AssertionError("Missing helper " + methodName)); + method.setAccessible(true); + try { + method.invoke(null, arguments); + } catch (InvocationTargetException failure) { + Throwable cause = failure.getCause(); + if (cause instanceof Exception exception) { + throw exception; + } + throw failure; + } + } + + private static List capturedInserts(DSLContext dsl) { + List inserts = new ArrayList<>(); + for (Invocation invocation : Mockito.mockingDetails(dsl).getInvocations()) { + if (!invocation.getMethod().getName().equals("execute")) { + continue; + } + Object[] arguments = invocation.getRawArguments(); + if (arguments.length == 2 && arguments[0] instanceof String sql) { + Object[] bindings = (Object[]) arguments[1]; + inserts.add(new InsertCall(sql, bindings)); + } + } + return inserts; + } + + private static BoundInsert validateShapeAndBind(InsertCall call) { + Matcher matcher = INSERT.matcher(call.sql()); + assertTrue(matcher.find(), () -> "not a captured INSERT statement: " + call.sql()); + List columns = splitSqlList(matcher.group(2)); + List expressions = splitSqlList(matcher.group(3)); + assertEquals(columns.size(), expressions.size(), "column/value arity: " + call.sql()); + + List bindings = Arrays.asList(call.bindings()); + Map boundValues = new HashMap<>(); + Map literals = new HashMap<>(); + int bindIndex = 0; + for (int index = 0; index < columns.size(); index++) { + String expression = expressions.get(index).strip(); + String column = columns.get(index).strip(); + if (expression.equals("?")) { + assertTrue(bindIndex < bindings.size(), "missing bound argument for " + column); + boundValues.put(column, bindings.get(bindIndex++)); + } else { + literals.put(column, expression.replaceAll("^'|'$", "")); + } + } + assertEquals(bindings.size(), bindIndex, "placeholder/binding arity: " + call.sql()); + long placeholders = countPlaceholders(matcher.group(3)); + assertEquals(placeholders, bindings.size(), "SQL placeholder count: " + call.sql()); + return new BoundInsert(matcher.group(1), boundValues, literals); + } + + private static List splitSqlList(String sql) { + List values = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + boolean inString = false; + for (int index = 0; index < sql.length(); index++) { + char character = sql.charAt(index); + if (character == '\'' && (index + 1 >= sql.length() || sql.charAt(index + 1) != '\'')) { + inString = !inString; + } else if (character == '\'' && inString && index + 1 < sql.length()) { + current.append(character).append(sql.charAt(++index)); + continue; + } + if (character == ',' && !inString) { + values.add(current.toString().strip()); + current.setLength(0); + } else { + current.append(character); + } + } + values.add(current.toString().strip()); + return values; + } + + private static long countPlaceholders(String sql) { + boolean inString = false; + long count = 0; + for (int index = 0; index < sql.length(); index++) { + char character = sql.charAt(index); + if (character == '\'' && (index + 1 >= sql.length() || sql.charAt(index + 1) != '\'')) { + inString = !inString; + } else if (character == '\'' && inString && index + 1 < sql.length()) { + index++; + } else if (character == '?' && !inString) { + count++; + } + } + return count; + } + + private static Fixture fixture() { + UUID accountId = UUID.fromString("0c3c3b79-a20c-4e16-9e46-33e366dca0a1"); + UUID tenantId = UUID.fromString("d0fe2aae-67ef-4cdf-b6d9-9be8f61ba6c3"); + UUID namespaceId = UUID.fromString("1ad8832a-b20f-4b0e-a2ec-8b1d7bfa6c9b"); + UUID gameInstanceId = UUID.fromString("a12c284b-808b-4e32-b9ee-7680c677c7f3"); + UUID transitionId = UUID.fromString("17803a16-4182-4f41-99c2-69e7e540836b"); + UUID reservationId = UUID.fromString("73e51bc6-a34a-47d4-8778-8755346145d2"); + UUID reservationFence = UUID.fromString("e5a00f67-0048-49e6-9138-b96260947a64"); + UUID accountFence = UUID.fromString("fca5bb6b-cebe-4dc3-b28e-4176b5e630d0"); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + tenantId, + namespaceId, + UUID.fromString("d2b930f4-2124-4d0a-a7cb-f468ebc101b9"), + "SHARED", + gameInstanceId, + RUNTIME_GAME_INSTANCE_ID, + "f0f46b01-57f6-47e8-a714-9fbcefe49b56", + UUID.fromString("e375e81b-9c7a-40e5-b361-0f39bd06f4c1"), + REGION_EPOCH, + UUID.fromString("b8c9ff0c-48a3-4388-ae0a-03f4f5a3e721"), + BigInteger.valueOf(43), + BigInteger.valueOf(47), + BigInteger.valueOf(53), + BigInteger.valueOf(59)); + CanonicalIssuerReservationFenceEvidence reservationEvidence = + new CanonicalIssuerReservationFenceEvidence( + reservationId, + reservationFence, + UUID.fromString("14a57b1d-1179-4d6f-908d-67105b0564d3"), + BigInteger.valueOf(61), + BigInteger.valueOf(67), + BigInteger.valueOf(71)); + CanonicalGameplayBindingTransitionRequest request = + new CanonicalGameplayBindingTransitionRequest( + transitionId, accountFence, identity, reservationEvidence, null, null); + BigInteger bindingGeneration = BigInteger.valueOf(73); + BigInteger inventoryRevision = BigInteger.valueOf(79); + CanonicalGameplayBindingTransitionSnapshot prepared = + new CanonicalGameplayBindingTransitionSnapshot( + transitionId, + identity, + bindingGeneration, + identity.bindingRef(), + inventoryRevision, + reservationId, + reservationFence, + accountFence, + null, + null, + CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED, + CanonicalGameplayAccountCoverageEvidence.noActiveFlow()); + return new Fixture( + request, prepared, identity.bindingRef().partitionId(identity.issuerIndexPartitionCount())); + } + + private record Fixture( + CanonicalGameplayBindingTransitionRequest request, + CanonicalGameplayBindingTransitionSnapshot prepared, + BigInteger partitionId) {} + + private record InsertCall(String sql, Object[] bindings) {} + + private record BoundInsert( + String table, Map values, Map literals) { + Object value(String column) { + Object result = values.get(column); + assertNotNull(result, "missing bound column " + column + " in " + table); + return result; + } + + String literal(String column) { + String result = literals.get(column); + assertNotNull(result, "missing literal column " + column + " in " + table); + return result; + } + + boolean isBoundNull(String column) { + return values.containsKey(column) && values.get(column) == null; + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconcilerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconcilerTest.java new file mode 100644 index 0000000000..d9e47a8860 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconcilerTest.java @@ -0,0 +1,804 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; +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.CanonicalGameplayBindingRegionBridgeObligation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisClusterConnection; +import org.springframework.data.redis.connection.RedisClusterServerCommands; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisServerCommands; +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; + +/** Mock-cursor contract tests only; none of these fixtures proves physical Redis coverage. */ +class CanonicalGameplayFreshNamespaceRedisReconcilerTest { + private static final String LEGACY_CONTEXT = "sessionctx:17:29:context"; + private static final String TARGET_KEY = "session:game:unexpected:retained"; + + @Test + void fullyScannedEmptyPhysicalDoubleSucceedsOnlyWithStableFencedEmptyInventory() { + RedisFixture fixture = redisFixtureWithScans(emptyScans(8)); + StringRedisTemplate redis = fixture.redis(); + TestCohort cohort = new TestCohort(0); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + + reconciler.rebuildExact(cohort, emptyLegacySnapshot(), emptyCanonicalSnapshot(41)); + CanonicalGameplayLegacyMigrationReadback readback = + reconciler.readBackExact(cohort, emptyCanonicalSnapshot(41)); + + assertThat(readback.sessionRecords()).isEmpty(); + assertThat(readback.characterIndexRecords()).isEmpty(); + assertThat(readback.remainingLegacySourceKeyDigests()).isEmpty(); + assertThat(readback.unexpectedNamespaceKeyDigests()).isEmpty(); + assertThat(cohort.fenceChecks.get()).isPositive(); + verifySuccessfulReadOnlyCapture(fixture, 8, 10); + } + + @Test + void canonicalPendingActiveRowsAndEveryObligationFamilyAreRejectedBeforeRedisAccess() { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + + for (CanonicalGameplayBindingInventorySnapshot snapshot : nonemptyCanonicalSnapshots()) { + assertThatThrownBy(() -> reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), snapshot)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Nonempty canonical gameplay inventory"); + } + + verify(redis, never()).execute(any(RedisCallback.class)); + } + + @Test + void retainedLegacySourceRemainsUnchangedAndBlocksReconciliation() { + StringRedisTemplate redis = + redisWithScans(List.of(List.of(LEGACY_CONTEXT), List.of(LEGACY_CONTEXT))); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + + assertThatThrownBy( + () -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Complete empty legacy source inventory"); + + verify(redis, times(3)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void retainedTargetOrUnknownNamespaceKeyRemainsUnchangedAndBlocksReconciliation() { + StringRedisTemplate redis = + redisWithScans(scans(List.of(), List.of(), List.of(TARGET_KEY), List.of(TARGET_KEY))); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + + assertThatThrownBy( + () -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("session or index family is retained or unknown"); + + verify(redis, times(5)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void onlyCanonicalNonNilIssuerProjectionIsExcludedAndPreservedWithoutReadingValue() { + String issuerProjection = "session:game:auth:issuer-generation:v1:" + UUID.randomUUID(); + RedisFixture fixture = + redisFixtureWithScans( + scans( + List.of(), + List.of(), + List.of(issuerProjection, issuerProjection), + List.of(issuerProjection, issuerProjection), + List.of(), + List.of(), + List.of(issuerProjection, issuerProjection), + List.of(issuerProjection, issuerProjection))); + StringRedisTemplate redis = fixture.redis(); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + TestCohort cohort = cohort(); + CanonicalGameplayBindingInventorySnapshot canonical = emptyCanonicalSnapshot(3); + + reconciler.rebuildExact(cohort, emptyLegacySnapshot(), canonical); + CanonicalGameplayLegacyMigrationReadback readback = reconciler.readBackExact(cohort, canonical); + + assertThat(readback.sessionRecords()).isEmpty(); + assertThat(readback.characterIndexRecords()).isEmpty(); + verifySuccessfulReadOnlyCapture(fixture, 8, 10); + } + + @Test + void malformedIssuerProjectionKeyIsDeniedWithoutMutation() { + for (String issuerId : List.of("not-a-uuid", "00000000-0000-0000-0000-000000000000")) { + String malformed = "session:game:auth:issuer-generation:v1:" + issuerId; + StringRedisTemplate redis = redisWithScans(scans(List.of(), List.of(), List.of(malformed))); + + assertThatThrownBy( + () -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(2))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("malformed issuer projection key"); + + verify(redis, times(4)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + } + + @Test + void repeatedCanonicalIssuerVisitsAreDeduplicatedButRemainVisitBounded() { + String issuerProjection = "session:game:auth:issuer-generation:v1:" + UUID.randomUUID(); + StringRedisTemplate redis = + redisWithScans( + scans( + List.of(), + List.of(), + List.of(issuerProjection, issuerProjection, issuerProjection))); + var visitLimit = + new CanonicalGameplayFreshNamespaceRedisReconciler.ScanLimits( + 2, 1, 2, 256, Duration.ofSeconds(5)); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = + new CanonicalGameplayFreshNamespaceRedisReconciler(redis, visitLimit); + + assertThatThrownBy( + () -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(2))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("duplicate-safe visit bound"); + + verify(redis, times(4)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void nonterminalCursorAndCursorFailureFailClosed() { + StringRedisTemplate nonterminal = + redisWithResults( + List.of(ScanResult.empty(), ScanResult.empty(), ScanResult.withCursor(List.of(), 19L))); + assertThatThrownBy( + () -> + reconciler(nonterminal) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("terminal cursor identity"); + + StringRedisTemplate failed = + redisWithResults( + List.of(ScanResult.empty(), ScanResult.empty(), ScanResult.failedCursor())); + assertThatThrownBy( + () -> + reconciler(failed) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("cursor failed before complete exhaustion"); + verifyNoRedisMutationOrValueRead(nonterminal); + verifyNoRedisMutationOrValueRead(failed); + } + + @Test + void clusterConnectionIsRefusedBeforeLegacyScan() { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisClusterConnection connection = mock(RedisClusterConnection.class); + RedisClusterServerCommands serverCommands = mock(RedisClusterServerCommands.class); + Properties clusterInformation = new Properties(); + clusterInformation.setProperty("cluster_enabled", "0"); + when(serverCommands.info("cluster")).thenReturn(clusterInformation); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + + assertThatThrownBy( + () -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining( + "Legacy Redis cluster scan cannot prove complete cluster-wide inventory"); + + verify(connection, never()).scan(any(ScanOptions.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void standaloneWrapperReportingClusterEnabledIsRefusedBeforeAnyNamespaceScan() { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisConnection connection = mock(RedisConnection.class); + RedisServerCommands serverCommands = serverCommandsWithTopology("1"); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + + assertThatThrownBy( + () -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("standalone topology could not be proven"); + + verify(connection, never()).scan(any(ScanOptions.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void unavailableTopologyObservationIsRefusedBeforeAnyNamespaceScan() { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisConnection connection = mock(RedisConnection.class); + RedisServerCommands serverCommands = mock(RedisServerCommands.class); + when(serverCommands.info("cluster")).thenThrow(new IllegalStateException("INFO unavailable")); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + + assertThatThrownBy( + () -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("standalone topology could not be proven"); + + verify(connection, never()).scan(any(ScanOptions.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void firstAndSecondTargetInventoriesMustBeIdentical() { + StringRedisTemplate redis = + redisWithScans(scans(List.of(), List.of(), List.of(), List.of(TARGET_KEY))); + + assertThatThrownBy( + () -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("changed between complete fenced scans"); + + verify(redis, times(5)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void fenceDriftDuringTargetScanPreventsFurtherInventoryOrReadback() { + StringRedisTemplate redis = redisWithScans(emptyScans(8)); + TestCohort driftingCohort = new TestCohort(11); + + assertThatThrownBy( + () -> + reconciler(redis) + .rebuildExact(driftingCohort, emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("changed during reconciliation"); + + verify(redis, times(4)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void readbackRechecksRedisAndRejectsAKeyThatAppearsAfterTheNoOpRebuild() { + StringRedisTemplate redis = + redisWithScans( + scans( + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(TARGET_KEY))); + TestCohort cohort = cohort(); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + CanonicalGameplayBindingInventorySnapshot canonical = emptyCanonicalSnapshot(5); + reconciler.rebuildExact(cohort, emptyLegacySnapshot(), canonical); + + assertThatThrownBy(() -> reconciler.readBackExact(cohort, canonical)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("changed between complete fenced scans"); + + verify(redis, times(10)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void readbackRechecksLegacyFamiliesInsteadOfTrustingTheEarlierEmptySnapshot() { + StringRedisTemplate redis = + redisWithScans( + scans( + List.of(), + List.of(), + List.of(), + List.of(), + List.of(LEGACY_CONTEXT), + List.of(LEGACY_CONTEXT))); + TestCohort cohort = cohort(); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); + CanonicalGameplayBindingInventorySnapshot canonical = emptyCanonicalSnapshot(5); + reconciler.rebuildExact(cohort, emptyLegacySnapshot(), canonical); + + assertThatThrownBy(() -> reconciler.readBackExact(cohort, canonical)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Complete empty legacy source inventory"); + + verify(redis, times(8)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void scanBoundsFailClosedBeforeACompleteNamespaceClaim() { + StringRedisTemplate redis = + redisWithScans( + scans(List.of(), List.of(), List.of("session:game:first", "session:game:second"))); + var tightLimits = + new CanonicalGameplayFreshNamespaceRedisReconciler.ScanLimits( + 2, 1, 2, 256, Duration.ofSeconds(5)); + CanonicalGameplayFreshNamespaceRedisReconciler reconciler = + new CanonicalGameplayFreshNamespaceRedisReconciler(redis, tightLimits); + + assertThatThrownBy( + () -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("unique-key bound"); + + verifyNoRedisMutationOrValueRead(redis); + } + + @Test + void keyLengthAndElapsedTimeBoundsFailClosed() { + StringRedisTemplate longKeyRedis = + redisWithScans(scans(List.of(), List.of(), List.of("session:game:" + "x".repeat(300)))); + assertThatThrownBy( + () -> + reconciler(longKeyRedis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("exceeds its byte bound"); + + StringRedisTemplate timedRedis = mock(StringRedisTemplate.class); + var immediateDeadline = + new CanonicalGameplayFreshNamespaceRedisReconciler.ScanLimits( + 2, 20, 40, 256, Duration.ofNanos(1)); + var timedReconciler = + new CanonicalGameplayFreshNamespaceRedisReconciler(timedRedis, immediateDeadline); + assertThatThrownBy( + () -> + timedReconciler.rebuildExact( + cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("time bound"); + verify(timedRedis, never()).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(longKeyRedis); + verifyNoRedisMutationOrValueRead(timedRedis); + } + + private static CanonicalGameplayFreshNamespaceRedisReconciler reconciler( + StringRedisTemplate redis) { + return new CanonicalGameplayFreshNamespaceRedisReconciler(redis, limits()); + } + + private static CanonicalGameplayFreshNamespaceRedisReconciler.ScanLimits limits() { + return new CanonicalGameplayFreshNamespaceRedisReconciler.ScanLimits( + 2, 20, 40, 256, Duration.ofSeconds(5)); + } + + private static List> emptyScans(int count) { + List> scans = new ArrayList<>(); + for (int index = 0; index < count; index++) { + scans.add(List.of()); + } + return scans; + } + + @SafeVarargs + private static List> scans(List... scans) { + return List.of(scans); + } + + private static StringRedisTemplate redisWithScans(List> scans) { + return redisWithResults(scans.stream().map(ScanResult::withKeys).toList()); + } + + private static StringRedisTemplate redisWithResults(List scans) { + return redisFixtureWithResults(scans).redis(); + } + + private static RedisFixture redisFixtureWithScans(List> scans) { + return redisFixtureWithResults(scans.stream().map(ScanResult::withKeys).toList()); + } + + private static RedisFixture redisFixtureWithResults(List scans) { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisConnection connection = mock(RedisConnection.class); + AtomicInteger scanIndex = new AtomicInteger(); + when(connection.scan(any(ScanOptions.class))) + .thenAnswer( + ignored -> { + int index = scanIndex.getAndIncrement(); + if (index >= scans.size()) { + throw new AssertionError("unexpected additional Redis scan"); + } + return cursor(scans.get(index)); + }); + RedisServerCommands serverCommands = serverCommandsWithTopology("0"); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + return new RedisFixture(redis, connection, serverCommands); + } + + private static void verifySuccessfulReadOnlyCapture( + RedisFixture fixture, int scans, int callbacks) { + verify(fixture.redis(), times(callbacks)).execute(any(RedisCallback.class)); + verifyNoRedisMutationOrValueRead(fixture.redis()); + verifyNoMoreInteractions(fixture.redis()); + verify(fixture.connection(), times(scans)).scan(any(ScanOptions.class)); + verify(fixture.connection(), times(callbacks)).serverCommands(); + verify(fixture.serverCommands(), times(callbacks)).info("cluster"); + verifyNoMoreInteractions(fixture.connection(), fixture.serverCommands()); + } + + private record RedisFixture( + StringRedisTemplate redis, RedisConnection connection, RedisServerCommands serverCommands) {} + + private static RedisServerCommands serverCommandsWithTopology(String clusterEnabled) { + RedisServerCommands serverCommands = mock(RedisServerCommands.class); + Properties clusterInformation = new Properties(); + clusterInformation.setProperty("cluster_enabled", clusterEnabled); + when(serverCommands.info("cluster")).thenReturn(clusterInformation); + return serverCommands; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void invokeThroughRedisCallback( + StringRedisTemplate redis, RedisConnection connection) { + doAnswer( + invocation -> { + RedisCallback callback = invocation.getArgument(0); + return callback.doInRedis(connection); + }) + .when(redis) + .execute(any(RedisCallback.class)); + } + + @SuppressWarnings("unchecked") + private static Cursor cursor(ScanResult result) { + Cursor cursor = mock(Cursor.class); + AtomicInteger index = new AtomicInteger(); + if (result.failCursor()) { + when(cursor.hasNext()).thenThrow(new IllegalStateException("cursor unavailable")); + } else { + when(cursor.hasNext()).thenAnswer(ignored -> index.get() < result.keys().size()); + when(cursor.next()) + .thenAnswer( + ignored -> + result.keys().get(index.getAndIncrement()).getBytes(StandardCharsets.UTF_8)); + when(cursor.getCursorId()).thenReturn(result.terminalCursorId()); + } + return cursor; + } + + private static CanonicalGameplayLegacyMigrationSourceSnapshot emptyLegacySnapshot() { + return new CanonicalGameplayLegacyMigrationSourceSnapshot( + EnumSet.of( + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.TENANT_SESSION_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.SESSION_ALIAS_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_IDENTITY_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.GAMEPLAY_NAME_CONTEXT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.MOVEMENT_EFFECT, + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.DURABLE_EFFECT), + List.of()); + } + + private static CanonicalGameplayBindingInventorySnapshot emptyCanonicalSnapshot(long revision) { + return new CanonicalGameplayBindingInventorySnapshot( + BigInteger.valueOf(revision), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of()); + } + + private static List nonemptyCanonicalSnapshots() { + CanonicalRows rows = canonicalRows(); + return List.of( + canonicalSnapshot( + List.of(rows.activeBinding()), List.of(), List.of(), List.of(), List.of(), List.of()), + canonicalSnapshot( + List.of(rows.pendingBinding()), List.of(), List.of(), List.of(), List.of(), List.of()), + canonicalSnapshot( + List.of(), List.of(rows.transition()), List.of(), List.of(), List.of(), List.of()), + canonicalSnapshot( + List.of(), List.of(), List.of(rows.reservation()), List.of(), List.of(), List.of()), + canonicalSnapshot( + List.of(), + List.of(), + List.of(), + List.of(rows.accountObligation()), + List.of(), + List.of()), + canonicalSnapshot( + List.of(), + List.of(), + List.of(), + List.of(), + List.of(rows.issuerObligation()), + List.of()), + canonicalSnapshot( + List.of(), + List.of(), + List.of(), + List.of(), + List.of(), + List.of(rows.regionObligation()))); + } + + private static CanonicalGameplayBindingInventorySnapshot canonicalSnapshot( + List bindings, + List transitions, + List reservations, + List accountObligations, + List issuerObligations, + List regionObligations) { + return new CanonicalGameplayBindingInventorySnapshot( + BigInteger.valueOf(7), + bindings, + transitions, + reservations, + accountObligations, + issuerObligations, + regionObligations); + } + + private static CanonicalRows canonicalRows() { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + UUID gameInstanceId = UUID.randomUUID(); + UUID regionId = UUID.randomUUID(); + UUID issuerId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + UUID accountIndexFence = UUID.randomUUID(); + UUID reservationFence = UUID.randomUUID(); + UUID issuerCoverageOperationId = UUID.randomUUID(); + BigInteger rowRevision = BigInteger.valueOf(5); + BigInteger generation = BigInteger.valueOf(2); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + tenantId, + namespaceId, + characterId, + "SHARED", + gameInstanceId, + 29L, + UUID.randomUUID().toString(), + regionId, + BigInteger.ONE, + issuerId, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(8), + BigInteger.valueOf(32)); + var ref = identity.bindingRef(); + CanonicalGameplayBindingInventoryEntry active = + new CanonicalGameplayBindingInventoryEntry( + identity, + ref, + generation, + accountIndexFence, + reservationId, + transitionId, + CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE, + CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED, + CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED, + rowRevision); + CanonicalGameplayBindingInventoryEntry pending = + new CanonicalGameplayBindingInventoryEntry( + identity, + ref, + generation, + accountIndexFence, + reservationId, + transitionId, + CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED, + rowRevision); + CanonicalGameplayBindingTransitionSnapshot transition = + new CanonicalGameplayBindingTransitionSnapshot( + transitionId, + identity, + generation, + ref, + rowRevision, + reservationId, + reservationFence, + accountIndexFence, + null, + null, + CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED, + CanonicalGameplayAccountCoverageEvidence.noActiveFlow()); + CanonicalIssuerPartitionReservation reservation = + new CanonicalIssuerPartitionReservation( + reservationId, + identity, + generation, + transitionId, + ref.partitionId(identity.issuerIndexPartitionCount()), + CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, + reservationFence, + issuerCoverageOperationId, + BigInteger.ONE, + BigInteger.ONE, + rowRevision, + rowRevision); + CanonicalGameplayBindingAccountIndexObligation accountObligation = + new CanonicalGameplayBindingAccountIndexObligation( + transitionId, + 0, + ref, + accountId, + tenantId, + CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN, + generation, + null, + accountIndexFence, + CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS, + CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED, + rowRevision, + CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED, + null, + null); + CanonicalGameplayBindingIssuerIndexObligation issuerObligation = + new CanonicalGameplayBindingIssuerIndexObligation( + transitionId, + ref, + generation, + reservationId, + CanonicalGameplayBindingIssuerIndexObligation.Status.REQUIRED, + rowRevision); + CanonicalGameplayBindingRegionBridgeObligation regionObligation = + new CanonicalGameplayBindingRegionBridgeObligation( + transitionId, + ref, + generation, + accountId, + tenantId, + gameInstanceId, + 29L, + identity.sessionId(), + regionId, + BigInteger.ONE, + CanonicalGameplayBindingRegionBridgeObligation.Status.REQUIRED, + rowRevision); + return new CanonicalRows( + active, + pending, + transition, + reservation, + accountObligation, + issuerObligation, + regionObligation); + } + + private static void verifyNoRedisMutationOrValueRead(StringRedisTemplate redis) { + verify(redis, never()).delete(any(String.class)); + verify(redis, never()).opsForValue(); + verify(redis, never()).opsForHash(); + verify(redis, never()).opsForSet(); + } + + private static TestCohort cohort() { + return new TestCohort(0); + } + + private static final class TestCohort + implements CanonicalGameplayLegacyMigrationOwner.FencedCohort { + private final UUID cohortId = UUID.randomUUID(); + private UUID writerFence = UUID.randomUUID(); + private final CanonicalGameplayLegacyMigrationStorageIdentity identity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "cluster-uid", + "namespace-uid", + "producer-pod-uid", + "container-id", + "node-uid", + "987654321", + 42L, + "postgres-volume-uid", + "redis-run-id", + "redis-volume-uid"); + private final int driftAtFenceCheck; + private final AtomicInteger fenceChecks = new AtomicInteger(); + + private TestCohort(int driftAtFenceCheck) { + this.driftAtFenceCheck = driftAtFenceCheck; + } + + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return identity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + int check = fenceChecks.incrementAndGet(); + if (driftAtFenceCheck > 0 && check == driftAtFenceCheck) { + writerFence = UUID.randomUUID(); + } + if (!identity.equals(expectedIdentity)) { + throw new CanonicalGameplayBindingInventoryConflictException( + "synthetic storage identity drift"); + } + } + } + + private record ScanResult(List keys, long terminalCursorId, boolean failCursor) { + private static ScanResult empty() { + return withKeys(List.of()); + } + + private static ScanResult withKeys(List keys) { + return new ScanResult(keys, 0L, false); + } + + private static ScanResult withCursor(List keys, long cursorId) { + return new ScanResult(keys, cursorId, false); + } + + private static ScanResult failedCursor() { + return new ScanResult(List.of(), 0L, true); + } + } + + private record CanonicalRows( + CanonicalGameplayBindingInventoryEntry activeBinding, + CanonicalGameplayBindingInventoryEntry pendingBinding, + CanonicalGameplayBindingTransitionSnapshot transition, + CanonicalIssuerPartitionReservation reservation, + CanonicalGameplayBindingAccountIndexObligation accountObligation, + CanonicalGameplayBindingIssuerIndexObligation issuerObligation, + CanonicalGameplayBindingRegionBridgeObligation regionObligation) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwnerTest.java new file mode 100644 index 0000000000..281ebd69e4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwnerTest.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayLegacyMigrationOwnerTest { + @Test + void retainsOriginalAdapterFailureAndSuppressedBlockPersistenceFailure() { + CanonicalGameplayLegacyMigrationRepository migration = + mock(CanonicalGameplayLegacyMigrationRepository.class); + CanonicalGameplayBindingInventoryRepository inventory = + mock(CanonicalGameplayBindingInventoryRepository.class); + CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner namespaceIndex = + mock(CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner.class); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + CanonicalGameplayLegacyMigrationStorageIdentity identity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "cluster-uid", + "namespace-uid", + "producer-pod-uid", + "container-id", + "node-uid", + "987654321", + 42L, + "postgres-volume-uid", + "redis-run-id", + "redis-volume-uid"); + CanonicalGameplayLegacyMigrationOperation fencedOperation = + new CanonicalGameplayLegacyMigrationOperation( + operationId, + cohortId, + writerFence, + identity, + CanonicalGameplayLegacyMigrationOperation.State.FENCED, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null); + when(migration.begin(cohortId, writerFence, identity)).thenReturn(fencedOperation); + + IllegalStateException originalAdapterFailure = + new IllegalStateException("source snapshot adapter failed after cohort fencing"); + IllegalStateException blockPersistenceFailure = + new IllegalStateException("BLOCKED state persistence failed"); + when(migration.block(operationId, "OWNER_ADAPTER_AMBIGUOUS")) + .thenThrow(blockPersistenceFailure); + + CanonicalGameplayLegacyMigrationOwner.FencedCohort cohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return identity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + assertThat(expectedIdentity).isEqualTo(identity); + } + }; + CanonicalGameplayLegacyMigrationOwner owner = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> cohort, + ignored -> { + throw originalAdapterFailure; + }, + namespaceIndex); + + assertThatThrownBy(owner::migrate) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("remains fenced and unresolved") + .satisfies( + failure -> { + assertThat(failure.getCause()).isSameAs(originalAdapterFailure); + assertThat(originalAdapterFailure.getSuppressed()) + .containsExactly(blockPersistenceFailure); + }); + + verify(migration).begin(cohortId, writerFence, identity); + verify(migration).block(operationId, "OWNER_ADAPTER_AMBIGUOUS"); + verifyNoMoreInteractions(migration); + verifyNoInteractions(inventory, namespaceIndex); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSourceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSourceTest.java new file mode 100644 index 0000000000..2ce791b758 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSourceTest.java @@ -0,0 +1,362 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.connection.RedisClusterConnection; +import org.springframework.data.redis.connection.RedisClusterServerCommands; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.connection.RedisServerCommands; +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; + +class CanonicalGameplayLegacyRedisSourceTest { + private static final String TENANT_CONTEXT = "sessionctx:17:29:context"; + private static final String SESSION_ALIAS = "sessionctx:session:29:context"; + private static final String FIRST_PARTY_CONTEXT = "sessionctx:first-party:29:connect-context"; + + @Test + void fullyEnumeratedEmptyPrefixIsOnlyAnEmptySourceObservation() { + RedisFixture fixture = redisFixtureWithScans(List.of(List.of(), List.of())); + StringRedisTemplate redis = fixture.redis(); + var source = new CanonicalGameplayLegacyRedisSource(redis, limits()); + + var snapshot = source.captureEveryKnownFamily(cohort()); + + assertThat(snapshot.entries()).isEmpty(); + assertThat(snapshot.enumeratedEveryKnownFamily()).isTrue(); + assertThat(snapshot.everyEntryIsReconciled()).isTrue(); + verifySuccessfulReadOnlyCapture(fixture, 2); + } + + @Test + void clusterConnectionIsRefusedBeforeLegacyScanEvenWhenInfoClaimsStandalone() { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisClusterConnection connection = mock(RedisClusterConnection.class); + RedisClusterServerCommands serverCommands = mock(RedisClusterServerCommands.class); + Properties clusterInformation = new Properties(); + clusterInformation.setProperty("cluster_enabled", "0"); + when(serverCommands.info("cluster")).thenReturn(clusterInformation); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("cluster scan cannot prove complete cluster-wide inventory"); + + verify(connection, never()).scan(any(ScanOptions.class)); + } + + @Test + void unknownOrMissingStandaloneTopologyIsRefusedBeforeLegacyScan() { + Properties unknown = new Properties(); + unknown.setProperty("cluster_enabled", "unknown"); + for (Properties clusterInformation : new Properties[] {new Properties(), unknown, null}) { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisConnection connection = mock(RedisConnection.class); + RedisServerCommands serverCommands = mock(RedisServerCommands.class); + when(serverCommands.info("cluster")).thenReturn(clusterInformation); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("standalone topology could not be proven"); + + verify(connection, never()).scan(any(ScanOptions.class)); + } + } + + @Test + void topologyInfoFailureIsRefusedBeforeLegacyScan() { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisConnection connection = mock(RedisConnection.class); + RedisServerCommands serverCommands = mock(RedisServerCommands.class); + when(serverCommands.info("cluster")).thenThrow(new IllegalStateException("INFO unavailable")); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("standalone topology could not be proven"); + + verify(connection, never()).scan(any(ScanOptions.class)); + } + + @Test + void unknownPrefixKeyMakesTheInventoryIncompleteAndNonAuthorizing() { + StringRedisTemplate redis = + redisWithScans(List.of(List.of(FIRST_PARTY_CONTEXT), List.of(FIRST_PARTY_CONTEXT))); + var snapshot = + new CanonicalGameplayLegacyRedisSource(redis, limits()).captureEveryKnownFamily(cohort()); + + assertThat(snapshot.enumeratedEveryKnownFamily()).isFalse(); + assertThat(snapshot.everyEntryIsReconciled()).isFalse(); + assertThat(snapshot.entries()) + .singleElement() + .satisfies( + entry -> { + assertThat(entry.family()) + .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Family.UNCLASSIFIED); + assertThat(entry.disposition()) + .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN); + }); + assertThat(snapshot.toString()).doesNotContain(FIRST_PARTY_CONTEXT); + } + + @Test + void duplicateScanResultsAreDeduplicatedButRetainedKnownKeysRemainUnmappableAndUntouched() { + StringRedisTemplate redis = + redisWithScans( + List.of( + List.of(TENANT_CONTEXT, TENANT_CONTEXT), List.of(TENANT_CONTEXT, TENANT_CONTEXT))); + var snapshot = new CanonicalGameplayLegacyRedisSource(redis, limits()); + + var observed = snapshot.captureEveryKnownFamily(cohort()); + + assertThat(observed.entries()).hasSize(1); + assertThat(observed.entries().getFirst().sourceKeyDigest()).startsWith("sha256:"); + assertThat(observed.entries().getFirst().family()) + .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Family.TENANT_SESSION_CONTEXT); + assertThat(observed.entries().getFirst().disposition()) + .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNMAPPABLE); + assertThat(observed.toString()).doesNotContain(TENANT_CONTEXT); + verify(redis, never()).opsForValue(); + verify(redis, never()).delete(any(String.class)); + } + + @Test + void cursorFailureAndUniqueKeyLimitFailClosed() { + StringRedisTemplate brokenCursorRedis = mock(StringRedisTemplate.class); + RedisConnection brokenConnection = mock(RedisConnection.class); + Cursor brokenCursor = mock(Cursor.class); + when(brokenConnection.scan(any(ScanOptions.class))).thenReturn(brokenCursor); + when(brokenCursor.hasNext()).thenThrow(new IllegalStateException("incomplete cursor")); + RedisServerCommands brokenServerCommands = standaloneServerCommands(); + when(brokenConnection.serverCommands()).thenReturn(brokenServerCommands); + invokeThroughRedisCallback(brokenCursorRedis, brokenConnection); + + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(brokenCursorRedis, limits()) + .captureEveryKnownFamily(cohort())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("cursor failed before complete exhaustion"); + + StringRedisTemplate incompleteCursorRedis = mock(StringRedisTemplate.class); + RedisConnection incompleteConnection = mock(RedisConnection.class); + Cursor incompleteCursor = mock(Cursor.class); + when(incompleteConnection.scan(any(ScanOptions.class))).thenReturn(incompleteCursor); + when(incompleteCursor.hasNext()).thenReturn(false); + when(incompleteCursor.getCursorId()).thenReturn(17L); + RedisServerCommands incompleteServerCommands = standaloneServerCommands(); + when(incompleteConnection.serverCommands()).thenReturn(incompleteServerCommands); + invokeThroughRedisCallback(incompleteCursorRedis, incompleteConnection); + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(incompleteCursorRedis, limits()) + .captureEveryKnownFamily(cohort())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("terminal cursor identity"); + + StringRedisTemplate overLimitRedis = + redisWithScans( + List.of( + List.of(TENANT_CONTEXT, SESSION_ALIAS), List.of(TENANT_CONTEXT, SESSION_ALIAS))); + var tightLimits = + new CanonicalGameplayLegacyRedisSource.ScanLimits(2, 1, 4, 256, Duration.ofSeconds(5)); + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(overLimitRedis, tightLimits) + .captureEveryKnownFamily(cohort())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("unique-key bound"); + verify(overLimitRedis, times(1)).execute(any(RedisCallback.class)); + } + + @Test + void differentFirstAndSecondInventoriesAreRejected() { + StringRedisTemplate redis = + redisWithScans(List.of(List.of(TENANT_CONTEXT), List.of(SESSION_ALIAS))); + + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("changed between complete fenced scans"); + } + + @Test + void fenceDriftDuringABatchPreventsTheSecondScan() { + StringRedisTemplate redis = + redisWithScans(List.of(List.of(TENANT_CONTEXT), List.of(TENANT_CONTEXT))); + var driftingCohort = new TestCohort(3); + var oneKeyPerFenceCheck = + new CanonicalGameplayLegacyRedisSource.ScanLimits(1, 10, 10, 256, Duration.ofSeconds(5)); + + assertThatThrownBy( + () -> + new CanonicalGameplayLegacyRedisSource(redis, oneKeyPerFenceCheck) + .captureEveryKnownFamily(driftingCohort)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + verify(redis, times(1)).execute(any(RedisCallback.class)); + } + + private static CanonicalGameplayLegacyRedisSource.ScanLimits limits() { + return new CanonicalGameplayLegacyRedisSource.ScanLimits(2, 20, 40, 256, Duration.ofSeconds(5)); + } + + private static RedisServerCommands standaloneServerCommands() { + RedisServerCommands serverCommands = mock(RedisServerCommands.class); + Properties clusterInformation = new Properties(); + clusterInformation.setProperty("cluster_enabled", "0"); + when(serverCommands.info("cluster")).thenReturn(clusterInformation); + return serverCommands; + } + + private static StringRedisTemplate redisWithScans(List> scans) { + return redisFixtureWithScans(scans).redis(); + } + + private static RedisFixture redisFixtureWithScans(List> scans) { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + RedisConnection connection = mock(RedisConnection.class); + AtomicInteger scanIndex = new AtomicInteger(); + when(connection.scan(any(ScanOptions.class))) + .thenAnswer( + ignored -> { + int index = scanIndex.getAndIncrement(); + if (index >= scans.size()) { + throw new AssertionError("unexpected third Redis scan"); + } + return cursor(scans.get(index)); + }); + RedisServerCommands serverCommands = mock(RedisServerCommands.class); + Properties clusterInformation = new Properties(); + clusterInformation.setProperty("cluster_enabled", "0"); + when(serverCommands.info("cluster")).thenReturn(clusterInformation); + when(connection.serverCommands()).thenReturn(serverCommands); + invokeThroughRedisCallback(redis, connection); + return new RedisFixture(redis, connection, serverCommands); + } + + private static void verifySuccessfulReadOnlyCapture(RedisFixture fixture, int scanCount) { + verify(fixture.redis(), times(scanCount)).execute(any(RedisCallback.class)); + verify(fixture.redis(), never()).delete(any(String.class)); + verify(fixture.redis(), never()).opsForValue(); + verify(fixture.redis(), never()).opsForHash(); + verify(fixture.redis(), never()).opsForSet(); + verifyNoMoreInteractions(fixture.redis()); + verify(fixture.connection(), times(scanCount)).scan(any(ScanOptions.class)); + verify(fixture.connection(), times(scanCount)).serverCommands(); + verify(fixture.serverCommands(), times(scanCount)).info("cluster"); + verifyNoMoreInteractions(fixture.connection(), fixture.serverCommands()); + } + + private record RedisFixture( + StringRedisTemplate redis, RedisConnection connection, RedisServerCommands serverCommands) {} + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void invokeThroughRedisCallback( + StringRedisTemplate redis, RedisConnection connection) { + doAnswer( + invocation -> { + RedisCallback callback = invocation.getArgument(0); + return callback.doInRedis(connection); + }) + .when(redis) + .execute(any(RedisCallback.class)); + } + + @SuppressWarnings("unchecked") + private static Cursor cursor(List keys) { + Cursor cursor = mock(Cursor.class); + AtomicInteger index = new AtomicInteger(); + when(cursor.hasNext()).thenAnswer(ignored -> index.get() < keys.size()); + when(cursor.next()) + .thenAnswer(ignored -> keys.get(index.getAndIncrement()).getBytes(StandardCharsets.UTF_8)); + return cursor; + } + + private static TestCohort cohort() { + return new TestCohort(0); + } + + private static final class TestCohort + implements CanonicalGameplayLegacyMigrationOwner.FencedCohort { + private final UUID cohortId = UUID.randomUUID(); + private final UUID writerFence = UUID.randomUUID(); + private final CanonicalGameplayLegacyMigrationStorageIdentity identity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "cluster-uid", + "namespace-uid", + "producer-pod-uid", + "container-id", + "node-uid", + "987654321", + 42L, + "postgres-volume-uid", + "redis-run-id", + "redis-volume-uid"); + private final int failAtFenceCheck; + private final AtomicInteger fenceChecks = new AtomicInteger(); + + private TestCohort(int failAtFenceCheck) { + this.failAtFenceCheck = failAtFenceCheck; + } + + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return identity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + assertThat(expectedIdentity).isEqualTo(identity); + int check = fenceChecks.incrementAndGet(); + if (failAtFenceCheck > 0 && check >= failAtFenceCheck) { + throw new CanonicalGameplayBindingInventoryConflictException("synthetic fence drift"); + } + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java new file mode 100644 index 0000000000..e9f021d946 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java @@ -0,0 +1,199 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Map; +import java.util.Properties; +import org.flywaydb.core.api.CoreMigrationType; +import org.flywaydb.core.api.Location; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationVersion; +import org.junit.jupiter.api.Test; +import org.postgresql.ds.PGSimpleDataSource; + +class CanonicalGameplayMigrationDriverMainTest { + @Test + void postgresConnectionIsBoundToTheFixedUnixSocketWithoutTcpOrSslFallback() { + CanonicalGameplayMigrationDriverMain.PostgresSocketConfiguration socket = + CanonicalGameplayMigrationDriverMain.postgresSocketConfiguration(); + + assertThat(socket.host()).isEqualTo("localhost"); + assertThat(socket.port()).isEqualTo(5432); + assertThat(socket.factoryClass()) + .isEqualTo("org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg"); + assertThat(socket.socketPath()).isEqualTo("/var/run/postgresql/.s.PGSQL.5432"); + assertThat(socket.sslMode()).isEqualTo("disable"); + } + + @Test + void flywayUsesTheCanonicalServiceSpecificHistoryTable() { + assertThat(CanonicalGameplayMigrationDriverMain.flywayHistoryTable("game_session_service")) + .isEqualTo("flyway_schema_history_game_session_service"); + + assertThatThrownBy( + () -> CanonicalGameplayMigrationDriverMain.flywayHistoryTable("other;schema")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> CanonicalGameplayMigrationDriverMain.flywayHistoryTable("a".repeat(42))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void flywayOwnsTheCanonicalFreshSchemaAndHistoryConfiguration() { + var configuration = + CanonicalGameplayMigrationDriverMain.configuredFlyway( + "game_session_service", new PGSimpleDataSource()); + + assertThat(configuration.getSchemas()).containsExactly("game_session_service"); + assertThat(configuration.getDefaultSchema()).isEqualTo("game_session_service"); + assertThat(configuration.getTable()).isEqualTo("flyway_schema_history_game_session_service"); + // Flyway removes the redundant nested location; the parent scan includes saga resources. + assertThat(configuration.getLocations()) + .extracting(Location::getDescriptor) + .containsExactly("classpath:db/migration"); + assertThat(configuration.isCreateSchemas()).isTrue(); + } + + @Test + void migrationSourceInventoryExcludesOneExplicitFlywaySchemaMarkerAndSortsSqlSources() { + MigrationInfo v2 = migration(CoreMigrationType.SQL, "2", "V2__second.sql", 22); + MigrationInfo schemaMarker = migration(CoreMigrationType.SCHEMA, null, null, null); + MigrationInfo v1 = migration(CoreMigrationType.SQL, "1", "V1__first.sql", 11); + + var migrations = + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] {v2, schemaMarker, v1}); + + assertThat(migrations) + .extracting(CanonicalGameplayMigrationDriverMain.MigrationSourceIdentity::version) + .containsExactly("1", "2"); + assertThat(migrations) + .extracting(CanonicalGameplayMigrationDriverMain.MigrationSourceIdentity::script) + .containsExactly("V1__first.sql", "V2__second.sql"); + assertThat(migrations) + .extracting(CanonicalGameplayMigrationDriverMain.MigrationSourceIdentity::checksum) + .containsExactly(11, 22); + } + + @Test + void migrationSourceInventoryRejectsMultipleFlywaySchemaMarkers() { + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] { + migration(CoreMigrationType.SCHEMA, null, null, null), + migration(CoreMigrationType.SCHEMA, null, null, null) + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("schema marker was ambiguous"); + } + + @Test + void migrationSourceInventoryRetainsDuplicateAndMalformedNormalMigrationRejection() { + MigrationInfo firstVersionOne = migration(CoreMigrationType.SQL, "1", "V1__first.sql", 11); + MigrationInfo duplicateVersionOne = migration(CoreMigrationType.SQL, "1", "V1__second.sql", 12); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] {firstVersionOne, duplicateVersionOne})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("versions were ambiguous"); + + MigrationInfo missingVersion = + migration(CoreMigrationType.SQL, null, "V1__missing_version.sql", 11); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] {missingVersion})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("identity was incomplete"); + + MigrationInfo missingScript = migration(CoreMigrationType.SQL, "1", null, 11); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] {missingScript})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("identity was incomplete"); + } + + @Test + void redisTlsObservationRequiresOnlyTheExactTlsEndpointAndDisabledPlainPort() { + String runId = "a".repeat(40); + String caDigest = "sha256:" + "4".repeat(64); + + Map observation = + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, "0", "6380", caDigest); + + assertThat(observation) + .containsExactlyInAnyOrderEntriesOf( + Map.of("runId", runId, "tlsEnabled", true, "tlsPort", 6380, "trustCaSha256", caDigest)); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, null, "6380", caDigest)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, "6379", "6380", caDigest)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, "0", "6379", caDigest)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, "0", "6380", null)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void redisTopologyRequiresAnUnambiguousStandaloneServerObservation() { + Properties standalone = new Properties(); + standalone.setProperty("cluster_enabled", "0"); + + CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology(standalone); + assertThatThrownBy( + () -> CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("topology"); + assertThatThrownBy( + () -> + CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology( + new Properties())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("topology"); + + Properties malformed = new Properties(); + malformed.setProperty("cluster_enabled", "unknown"); + assertThatThrownBy( + () -> CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology(malformed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("topology"); + + Properties clustered = new Properties(); + clustered.setProperty("cluster_enabled", "1"); + assertThatThrownBy( + () -> CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology(clustered)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("topology"); + } + + private static MigrationInfo migration( + CoreMigrationType type, String version, String script, Integer checksum) { + MigrationInfo migration = mock(MigrationInfo.class); + when(migration.getType()).thenReturn(type); + when(migration.getVersion()) + .thenReturn(version == null ? null : MigrationVersion.fromVersion(version)); + when(migration.getScript()).thenReturn(script); + when(migration.getChecksum()).thenReturn(checksum); + return migration; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java new file mode 100644 index 0000000000..faf6418fa8 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java @@ -0,0 +1,443 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +class CanonicalGameplayMigrationDriverProtocolTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String FENCE_DIGEST = "sha256:" + "1".repeat(64); + private static final CanonicalGameplayLegacyMigrationStorageIdentity STORAGE_IDENTITY = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "kind-cluster-incarnation", + "namespace-incarnation", + "postgres-pod-uid", + "containerd://postgres-container-id", + "node-incarnation", + "12345678901234567890", + 4_294_967_295L, + "namespace-incarnation/postgres-pod-uid/data", + "a".repeat(40), + "namespace-incarnation/redis-pod-uid/data"); + + @Test + void initializationAcceptsExactClosedShapeAndUnsignedDatabaseOid() throws Exception { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol(input(initializationJson()), output)) { + var initialization = protocol.readInitialization(); + + assertThat(initialization.cohortId()) + .isEqualTo(UUID.fromString("00000000-0000-4000-8000-000000000001")); + assertThat(initialization.legacyWriterFence()) + .isEqualTo(UUID.fromString("00000000-0000-4000-8000-000000000002")); + assertThat(initialization.storageIdentity()).isEqualTo(STORAGE_IDENTITY); + assertThat(initialization.storageIdentity().postgresDatabaseOid()).isEqualTo(4_294_967_295L); + assertThat(initialization.fenceDigest()).isEqualTo(FENCE_DIGEST); + } + } + + @Test + void initializationRejectsUnknownFieldsAndDuplicateJsonProperties() { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + String withUnknownField = + initializationJson().replace("\"redisPort\":6380", "\"redisPort\":6380,\"trusted\":true"); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol(input(withUnknownField), output)) { + assertThatThrownBy(protocol::readInitialization) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing or unknown fields"); + } + + String withDuplicateField = + initializationJson() + .replace( + "\"schema\":\"firemud.gs.migration-driver/v1\",", + "\"schema\":\"firemud.gs.migration-driver/v1\",\"schema\":\"firemud.gs.migration-driver/v1\","); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol( + input(withDuplicateField), new ByteArrayOutputStream())) { + assertThatThrownBy(protocol::readInitialization) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("malformed"); + } + } + + @Test + void initializationRejectsAnOversizedUtf8Frame() { + byte[] oversized = new byte[CanonicalGameplayMigrationDriverProtocol.MAX_FRAME_BYTES + 1]; + java.util.Arrays.fill(oversized, (byte) ' '); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol( + new ByteArrayInputStream(oversized), new ByteArrayOutputStream())) { + assertThatThrownBy(protocol::readInitialization) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("malformed"); + } + } + + @Test + @Timeout(5) + void reobservationEmitsFreshNonceAndAcceptsOnlyTheExactBoundEcho() throws Exception { + PipedInputStream driverInput = new PipedInputStream(4096); + PipedOutputStream factoryOutput = new PipedOutputStream(driverInput); + PipedInputStream factoryInput = new PipedInputStream(4096); + PipedOutputStream driverOutput = new PipedOutputStream(factoryInput); + factoryOutput.write(initializationJson().getBytes(StandardCharsets.UTF_8)); + factoryOutput.write('\n'); + factoryOutput.flush(); + AtomicReference challenge = new AtomicReference<>(); + Thread responder = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(factoryInput, StandardCharsets.UTF_8))) { + JsonNode request = MAPPER.readTree(reader.readLine()); + challenge.set(request); + ObjectNode response = MAPPER.createObjectNode(); + response.put("schema", CanonicalGameplayMigrationDriverProtocol.SCHEMA); + response.put("kind", "observed"); + response.put("sequence", request.path("sequence").longValue()); + response.put("nonce", request.path("nonce").textValue()); + response.put("cohortId", request.path("cohortId").textValue()); + response.put("legacyWriterFence", request.path("legacyWriterFence").textValue()); + response.set("storageIdentity", storageIdentityJson()); + response.put("fenceDigest", request.path("fenceDigest").textValue()); + factoryOutput.write(MAPPER.writeValueAsBytes(response)); + factoryOutput.write('\n'); + factoryOutput.flush(); + } catch (Exception failure) { + throw new AssertionError( + "test factory could not answer the driver challenge", failure); + } + }, + "migration-driver-protocol-test-factory"); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol(driverInput, driverOutput)) { + // The responder reads the driver's re-observation frame after initialization is consumed. + var initialization = protocol.readInitialization(); + responder.start(); + protocol.requireFreshObservation(initialization, localObservation()); + responder.join(1000); + + assertThat(responder.isAlive()).isFalse(); + assertThat(challenge.get()).isNotNull(); + assertThat(fields(challenge.get())) + .containsExactlyInAnyOrder( + "schema", + "kind", + "sequence", + "nonce", + "cohortId", + "legacyWriterFence", + "storageIdentityDigest", + "fenceDigest", + "postgres", + "redis"); + assertThat(challenge.get().path("sequence").longValue()).isEqualTo(1L); + assertThat(challenge.get().path("nonce").textValue()) + .matches("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + assertThat(challenge.get().path("storageIdentityDigest").textValue()) + .isEqualTo(STORAGE_IDENTITY.digest()); + assertThat(fields(challenge.get().path("postgres"))) + .containsExactlyInAnyOrder( + "systemIdentifier", + "databaseOid", + "serverAddress", + "serverPort", + "listenAddresses", + "hbaFile", + "unixSocketDirectories", + "rolesDigest", + "hbaRulesDigest"); + assertThat(fields(challenge.get().path("redis"))) + .containsExactlyInAnyOrder("runId", "tlsEnabled", "tlsPort", "trustCaSha256"); + } finally { + responder.interrupt(); + factoryOutput.close(); + driverOutput.close(); + } + } + + @Test + @Timeout(5) + void reobservationRejectsWrongNonce() throws Exception { + assertResponseRejected( + response -> response.put("nonce", "00000000-0000-4000-8000-000000000099"), + "nonce did not match"); + } + + @Test + @Timeout(5) + void reobservationRejectsMissingFields() throws Exception { + assertResponseRejected(response -> response.remove("fenceDigest"), "missing or unknown fields"); + } + + @Test + @Timeout(5) + void reobservationRejectsChangedStorageIdentity() throws Exception { + assertResponseRejected( + response -> + ((ObjectNode) response.get("storageIdentity")).put("producerPodUid", "other-pod"), + "different physical storage identity"); + } + + @Test + @Timeout(5) + void reobservationRejectsReplayOfThePriorBoundReply() throws Exception { + PipedInputStream driverInput = new PipedInputStream(4096); + PipedOutputStream factoryOutput = new PipedOutputStream(driverInput); + PipedInputStream factoryInput = new PipedInputStream(4096); + PipedOutputStream driverOutput = new PipedOutputStream(factoryInput); + factoryOutput.write(initializationJson().getBytes(StandardCharsets.UTF_8)); + factoryOutput.write('\n'); + factoryOutput.flush(); + AtomicReference responderFailure = new AtomicReference<>(); + Thread responder = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(factoryInput, StandardCharsets.UTF_8))) { + JsonNode firstRequest = MAPPER.readTree(reader.readLine()); + byte[] firstReply = MAPPER.writeValueAsBytes(boundReply(firstRequest)); + factoryOutput.write(firstReply); + factoryOutput.write('\n'); + factoryOutput.flush(); + reader.readLine(); + factoryOutput.write(firstReply); + factoryOutput.write('\n'); + factoryOutput.flush(); + } catch (Throwable failure) { + responderFailure.set(failure); + } + }, + "migration-driver-replay-test-factory"); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol(driverInput, driverOutput)) { + var initialization = protocol.readInitialization(); + responder.start(); + protocol.requireFreshObservation(initialization, localObservation()); + assertThatThrownBy(() -> protocol.requireFreshObservation(initialization, localObservation())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sequence did not match"); + responder.join(1000); + assertThat(responder.isAlive()).isFalse(); + assertThat(responderFailure.get()).isNull(); + } finally { + responder.interrupt(); + factoryOutput.close(); + driverOutput.close(); + } + } + + @Test + @Timeout(5) + void reobservationRejectsEofBeforeTheBoundReply() { + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol( + input(initializationJson()), new ByteArrayOutputStream())) { + var initialization = protocol.readInitialization(); + assertThatThrownBy(() -> protocol.requireFreshObservation(initialization, localObservation())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("EOF"); + } + } + + @Test + @Timeout(5) + void protocolOutputWriteHasAnIndependentBoundedDeadline() throws InterruptedException { + BlockingOutputStream output = new BlockingOutputStream(); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol( + input(initializationJson()), output, java.time.Duration.ofMillis(500))) { + AtomicReference driverFailure = new AtomicReference<>(); + CountDownLatch completed = new CountDownLatch(1); + Thread driver = + new Thread( + () -> { + try { + var initialization = protocol.readInitialization(); + protocol.requireFreshObservation(initialization, localObservation()); + } catch (Throwable failure) { + driverFailure.set(failure); + } finally { + completed.countDown(); + } + }, + "migration-driver-blocked-output-test"); + driver.setDaemon(true); + driver.start(); + + assertThat(output.writeStarted.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(completed.await(2, TimeUnit.SECONDS)).isTrue(); + assertThat(driverFailure.get()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("output timed out"); + } + } + + private static void assertResponseRejected(Consumer mutation, String expectedMessage) + throws Exception { + PipedInputStream driverInput = new PipedInputStream(4096); + PipedOutputStream factoryOutput = new PipedOutputStream(driverInput); + PipedInputStream factoryInput = new PipedInputStream(4096); + PipedOutputStream driverOutput = new PipedOutputStream(factoryInput); + factoryOutput.write(initializationJson().getBytes(StandardCharsets.UTF_8)); + factoryOutput.write('\n'); + factoryOutput.flush(); + AtomicReference responderFailure = new AtomicReference<>(); + Thread responder = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(factoryInput, StandardCharsets.UTF_8))) { + JsonNode request = MAPPER.readTree(reader.readLine()); + ObjectNode response = boundReply(request); + mutation.accept(response); + factoryOutput.write(MAPPER.writeValueAsBytes(response)); + factoryOutput.write('\n'); + factoryOutput.flush(); + } catch (Throwable failure) { + responderFailure.set(failure); + } + }, + "migration-driver-invalid-reply-test-factory"); + try (CanonicalGameplayMigrationDriverProtocol protocol = + new CanonicalGameplayMigrationDriverProtocol(driverInput, driverOutput)) { + var initialization = protocol.readInitialization(); + responder.start(); + assertThatThrownBy(() -> protocol.requireFreshObservation(initialization, localObservation())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining(expectedMessage); + responder.join(1000); + assertThat(responder.isAlive()).isFalse(); + assertThat(responderFailure.get()).isNull(); + } finally { + responder.interrupt(); + factoryOutput.close(); + driverOutput.close(); + } + } + + private static ObjectNode boundReply(JsonNode request) { + ObjectNode response = MAPPER.createObjectNode(); + response.put("schema", CanonicalGameplayMigrationDriverProtocol.SCHEMA); + response.put("kind", "observed"); + response.put("sequence", request.path("sequence").longValue()); + response.put("nonce", request.path("nonce").textValue()); + response.put("cohortId", request.path("cohortId").textValue()); + response.put("legacyWriterFence", request.path("legacyWriterFence").textValue()); + response.set("storageIdentity", storageIdentityJson()); + response.put("fenceDigest", request.path("fenceDigest").textValue()); + return response; + } + + private static final class BlockingOutputStream extends java.io.OutputStream { + private final CountDownLatch writeStarted = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + + @Override + public void write(int value) throws java.io.IOException { + block(); + } + + @Override + public void write(byte[] value, int offset, int length) throws java.io.IOException { + block(); + } + + private void block() throws java.io.IOException { + writeStarted.countDown(); + try { + release.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new java.io.IOException("interrupted", interrupted); + } + } + } + + private static Set fields(JsonNode node) { + Set fields = new HashSet<>(); + node.fieldNames().forEachRemaining(fields::add); + return fields; + } + + private static CanonicalGameplayMigrationDriverProtocol.LocalObservation localObservation() { + Map postgres = new LinkedHashMap<>(); + postgres.put("systemIdentifier", STORAGE_IDENTITY.postgresSystemIdentifier()); + postgres.put("databaseOid", STORAGE_IDENTITY.postgresDatabaseOid()); + postgres.put("serverAddress", null); + postgres.put("serverPort", null); + postgres.put("listenAddresses", ""); + postgres.put("hbaFile", "/var/lib/postgresql/data/pg_hba.conf"); + postgres.put("unixSocketDirectories", "/var/run/postgresql"); + postgres.put("rolesDigest", "sha256:" + "2".repeat(64)); + postgres.put("hbaRulesDigest", "sha256:" + "3".repeat(64)); + Map redis = new LinkedHashMap<>(); + redis.put("runId", STORAGE_IDENTITY.redisRunId()); + redis.put("tlsEnabled", true); + redis.put("tlsPort", 6380); + redis.put("trustCaSha256", "sha256:" + "4".repeat(64)); + return new CanonicalGameplayMigrationDriverProtocol.LocalObservation(postgres, redis); + } + + private static ByteArrayInputStream input(String frame) { + return new ByteArrayInputStream((frame + "\n").getBytes(StandardCharsets.UTF_8)); + } + + private static String initializationJson() { + try { + ObjectNode root = MAPPER.createObjectNode(); + root.put("schema", CanonicalGameplayMigrationDriverProtocol.SCHEMA); + root.put("kind", "initialize"); + root.put("operation", "migrate-empty-cohort"); + root.put("cohortId", "00000000-0000-4000-8000-000000000001"); + root.put("legacyWriterFence", "00000000-0000-4000-8000-000000000002"); + root.set("storageIdentity", storageIdentityJson()); + root.put("fenceDigest", FENCE_DIGEST); + root.put("redisHost", "redis-0.redis.game-session.svc.cluster.local"); + root.put("redisPort", 6380); + return MAPPER.writeValueAsString(root); + } catch (Exception failure) { + throw new AssertionError("test initialization could not be serialized", failure); + } + } + + private static ObjectNode storageIdentityJson() { + ObjectNode identity = MAPPER.createObjectNode(); + identity.put("kubernetesClusterUid", STORAGE_IDENTITY.kubernetesClusterUid()); + identity.put("kubernetesNamespaceUid", STORAGE_IDENTITY.kubernetesNamespaceUid()); + identity.put("producerPodUid", STORAGE_IDENTITY.producerPodUid()); + identity.put("producerContainerId", STORAGE_IDENTITY.producerContainerId()); + identity.put("producerNodeUid", STORAGE_IDENTITY.producerNodeUid()); + identity.put("postgresSystemIdentifier", STORAGE_IDENTITY.postgresSystemIdentifier()); + identity.put("postgresDatabaseOid", STORAGE_IDENTITY.postgresDatabaseOid()); + identity.put("postgresStorageUid", STORAGE_IDENTITY.postgresStorageUid()); + identity.put("redisRunId", STORAGE_IDENTITY.redisRunId()); + identity.put("redisStorageUid", STORAGE_IDENTITY.redisStorageUid()); + return identity; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java index 919ab297cb..6c4c8be908 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java @@ -115,6 +115,15 @@ status VARCHAR(16) NOT NULL, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL, terminal_at TIMESTAMP, + catalog_source_kind VARCHAR(16) NOT NULL DEFAULT 'V9_FIXTURE', + fixture_catalog_realm_id UUID, + published_target_namespace VARCHAR(63), + canonical_tenant_id UUID, + game_template_id BIGINT, + launch_descriptor_id VARCHAR(128), + release_bundle_id BIGINT, + published_release_bundle_ref VARCHAR(200), + version_state_epoch BIGINT, UNIQUE (tenant_id, initial_admission_request_id) ) """); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java index 348c071737..38a5487836 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java @@ -230,7 +230,12 @@ private static void createSchema(DSLContext dsl) { + "catalog_revision BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, version_id BIGINT NOT NULL, " + "active_lifecycle_epoch BIGINT NOT NULL, hold_id UUID, hold_fence UUID, status VARCHAR(16) NOT NULL, " + "pointer_id BIGINT, audit_event_id BIGINT, created_at TIMESTAMP NOT NULL, " - + "updated_at TIMESTAMP NOT NULL, terminal_at TIMESTAMP, UNIQUE (tenant_id, initial_admission_request_id))"); + + "updated_at TIMESTAMP NOT NULL, terminal_at TIMESTAMP, " + + "catalog_source_kind VARCHAR(16) NOT NULL DEFAULT 'V9_FIXTURE', " + + "fixture_catalog_realm_id UUID, published_target_namespace VARCHAR(63), " + + "canonical_tenant_id UUID, game_template_id BIGINT, launch_descriptor_id VARCHAR(128), " + + "release_bundle_id BIGINT, published_release_bundle_ref VARCHAR(200), version_state_epoch BIGINT, " + + "UNIQUE (tenant_id, initial_admission_request_id))"); dsl.execute( "CREATE TABLE gameplay_admission_pointer (" + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, world_slug VARCHAR(120) NOT NULL, " diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 03b453aef3..7971ae90de 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -211,7 +211,47 @@ public long freshGameplayBaseline( clearDefaultDemoAdmissionBinding(jdbc, tenantId); } jdbc.execute("TRUNCATE TABLE runtime_region_status RESTART IDENTITY"); - jdbc.execute("TRUNCATE TABLE game_instances RESTART IDENTITY"); + // This is a disposable Testcontainers baseline reset, not runtime/bootstrap behavior. Keep + // the FK descendants explicit and temporarily suspend only the launch-evidence TRUNCATE guard + // inside the same transaction; the production migration and all application SQL retain it. + TransactionTemplate baselineReset = + new TransactionTemplate(gameSession.bean(PlatformTransactionManager.class)); + String originalLaunchGuardState = + baselineReset.execute( + status -> { + String originalState = canonicalLaunchTruncateGuardState(jdbc); + if (!"O".equals(originalState) && !"A".equals(originalState)) { + throw new IllegalStateException( + "Expected exactly one canonical launch TRUNCATE guard enabled during" + + " disposable gameplay fixture reset; observed " + + originalState); + } + jdbc.execute( + "ALTER TABLE game_session_canonical_instance_launch " + + "DISABLE TRIGGER game_session_canonical_instance_launch_no_truncate"); + requireCanonicalLaunchTruncateGuardState(jdbc, "D"); + jdbc.execute( + """ + TRUNCATE TABLE + game_session_canonical_closed_admission_pointer_request, + gameplay_initial_admission_bind_attempt, + game_session_canonical_initial_admission_intent, + game_session_canonical_initial_admission_attempt, + gameplay_admission_pointer_event, + gameplay_admission_pointer, + game_session_canonical_instance_launch, + game_instances + RESTART IDENTITY + """); + // PostgreSQL rolls back this transactional trigger change if TRUNCATE fails, + // preserving + // the real guard failure instead of masking it with a re-enable attempt on an aborted + // transaction. + restoreCanonicalLaunchTruncateGuard(jdbc, originalState); + requireCanonicalLaunchTruncateGuardState(jdbc, originalState); + return originalState; + }); + requireCanonicalLaunchTruncateGuardState(jdbc, originalLaunchGuardState); if (characterIds.length > 0) { clearScreenBuffers(tenantId, gameplayInstanceId, characterIds); } @@ -225,6 +265,56 @@ public long freshGameplayBaseline( return gameInstanceId; } + private static String canonicalLaunchTruncateGuardState(JdbcTemplate jdbc) { + List states = + jdbc.query( + """ + SELECT tgenabled::text + FROM pg_trigger + WHERE tgrelid = 'game_session_canonical_instance_launch'::regclass + AND tgname = 'game_session_canonical_instance_launch_no_truncate' + AND NOT tgisinternal + """, + (row, rowNumber) -> row.getString(1)); + if (states.size() != 1 + || (!"O".equals(states.getFirst()) + && !"A".equals(states.getFirst()) + && !"D".equals(states.getFirst()))) { + throw new IllegalStateException( + "Expected exactly one canonical launch TRUNCATE guard in O, A, or D state during" + + " disposable gameplay fixture reset; observed " + + states); + } + return states.getFirst(); + } + + private static void requireCanonicalLaunchTruncateGuardState( + JdbcTemplate jdbc, String expectedState) { + String observedState = canonicalLaunchTruncateGuardState(jdbc); + if (!expectedState.equals(observedState)) { + throw new IllegalStateException( + "Expected canonical launch TRUNCATE guard state " + + expectedState + + " during disposable gameplay fixture reset; observed " + + observedState); + } + } + + private static void restoreCanonicalLaunchTruncateGuard(JdbcTemplate jdbc, String state) { + String enableMode = + switch (state) { + case "O" -> "ENABLE"; + case "A" -> "ENABLE ALWAYS"; + default -> + throw new IllegalStateException( + "Cannot restore unsupported canonical launch TRUNCATE guard state " + state); + }; + jdbc.execute( + "ALTER TABLE game_session_canonical_instance_launch " + + enableMode + + " TRIGGER game_session_canonical_instance_launch_no_truncate"); + } + private void clearDefaultDemoAdmissionBinding(JdbcTemplate jdbc, long tenantId) { String requestId = defaultDemoRequestId(tenantId); TransactionTemplate transaction =