diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d25cd74309..697a5c443c 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -181,6 +181,12 @@ The response echoes the exact request scope and includes `CURRENT_AT_REVALIDATIO The handler returns `PERMISSION_DENIED` for a caller that is not the exact verified workload peer, `INVALID_ARGUMENT` for malformed scope or request shape, and `FAILED_PRECONDITION` when current owner evidence is absent or contradictory. Account source unavailability maps to `UNAVAILABLE`; other read or evidence-production failures map to `INTERNAL`. No partial evidence is returned on failure. +### Canonical public-production NEW admission lease source + +The local [AccountGameplayAdmissionLeaseService](../../../../protos/account/v1/account_gameplay_admission_lease.proto) carrier prepares the four purpose-specific `AcquireGameplayAdmissionLease`, `FinalizeGameplayAdmissionLease`, `ReadGameplayAdmissionLease` and `AbortGameplayAdmissionLease` methods selected by [canonical session admission](../../system-architecture-session-behavior.md#canonical-public-production-new-admission). The intended peer is the exact same-namespace Game Session workload. Acquisition carries a transient initial LOGIN GSA credential and typed expected candidate/target values; those values remain comparisons against independently resolved current owners. Finalize, Read and Abort carry the complete unchanged original canonical lease bytes. Abort's absent decision remains unknown, and its cleanup reference represents an outstanding obligation. The expected candidate’s `issuer_id` is the exact Account issuer string; the manual authenticated owner joins it to the independently verified token and current issuer source/checkpoint, rather than accepting an equal generation as issuer identity. + +The shared codec preserves the existing 64 KiB lease and 15-second lifetime bounds, closed presence-aware fields, exact operation and binding-scope correlation, and the complete original ACK-receipt shape for a committed readback. Parsing that shape proves neither authentication nor physical commit or receipt durability. The local source now includes a concrete authenticated lease owner and a same-namespace certificate-guarded manual receiver/server factory; it remains unregistered. Focused Account-source and manual TLS proof cover acquisition and first fresh finalization/ACK with controlled reverse Game Session responses. Exact non-admitting read/abort and retained terminal lookup revalidate the current caller/global Account/token while preserving the original lease; tenant-source changes do not authorize new admission or erase the cleanup obligation. Retained PostgreSQL-version restrictions, token-retirement and orphan-cleanup delivery, actual Game Session authority and admitted `PLAY`/`LOOK` remain unqualified. Account must use the existing original physical-commit and independently durable receipt owners; wire evidence cannot reconstruct their in-process acknowledgement. Local source and proof status remain in [Account runtime and data](./runtime-and-data.md#implementation-status). + ### Operator Authorization References StartSession response recovery preserves the raw `firemud/account-response-envelope/aad/v1` grammar and authenticates the canonical authority-evidence bytes directly; no digest replaces those bytes. The authority bundle is bounded at 128 KiB, the complete canonical binding and exact response plaintext at 144 KiB each, and the AES-GCM envelope by that plaintext maximum plus its bounded header and tag. Repository and PostgreSQL storage allow at most 160 KiB. Forward migration [V126.3](../../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql) replaces only the envelope-size guard and leaves retained ciphertext and the existing immutable/erasure rules intact. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 11898fa62b..e54d95585a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,6 +8,8 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ## Implementation Status +The caller verifier, lease owner and certificate-guarded four-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. Current-token verification alone grants no admission. Proof still uses controlled reverse Game Session and protected-source inputs; genuine owner composition, token-retirement and cleanup delivery, and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details. + The selected-recipient intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Expired preliminary recovery pages use a caller-held `(expiry epoch second, operation UUID)` keyset cursor that advances across every examined row, including invalid rows and candidates whose abort does not commit; a caller continues while a cursor is returned and starts a fresh sweep only after an empty page. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits and remaining dependencies. The additive [V1003 source-protection storage](../../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql) provides passive original StartSession admission and activation protection relations and source-writer exclusions. It adds no registered producer or transport. Qualification and remaining composition gates are recorded in the [source-protection tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 028e4fa149..8f133c6770 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,6 +8,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status +The local [canonical NEW admission lease contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) now has generated transport carriers and a manually composed `AccountGameplayAdmissionLeaseClient` for Account’s four purpose-specific methods. Its narrow candidate uses the exact Account issuer string at the original string wire tag; shape validation supplies no issuer authority. The [Account API](../account-service/api-contracts.md#canonical-public-production-new-admission-lease-source) owns caller authentication, acquisition, original finalization and read/abort recovery. The prepared Account-only reverse-read proto and closed codec preserve separate current published-target and exact provisional-decision purposes, with their finite transport bounds; this prerequisite does not supply their genuine Game Session owner composition or register a source receiver. The Account receiver’s focused physical-COMMIT and durable-ACK proof uses explicitly controlled reverse responses. These local components do not acknowledge issuer/region obligations or admit a binding; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) records component proof and remaining composition. + The initial-LOGIN PostgreSQL journal and exact original-attempt cleanup owner are unregistered source preparation, with no new Game Session endpoint or legacy LOGIN handler composition. Their unregistered Account client authenticates the exact same-namespace Account mTLS peer and validates the explicit initial delegation profile, signature, original request/context, token hash, claim/projection equality and bounded nonsecret evidence. Its one transient invocation permits at most one transport reload/retry under the unchanged deadline. It also uses the original-request retirement contract. The result retains compact private-token bytes only in process; validation supplies neither current registry authority nor live context installation. Journal snapshots and typed closure fixtures supply no authenticated caller custody or physical Redis closure; the separate Redis adapter remains outside runtime composition. See the [canonical coordination contract](../../system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). The source-first owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. `RunOwnedCanonicalLaunchPreparationOwner` exposes canonical fresh-association, catalog and `STARTING` creation with independent owner readback only through an explicit preparation call; it has no scheduler. The published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap and existing `GameInstanceServiceImpl` behavior remain until coherent canonical adoption, so this source-first path is not evidence that the current scheduled runtime allocates that canonical launch. Game Design source keys and Game Session's allocated private tenant/runtime keys remain separate. The published numeric fixture path has not been removed by this source-only split. This explicit canonical path establishes no canonical World materialization/activation, canonical first-`OPEN`, or canonical admission result. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 58c1802175..c42c989c33 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,12 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- **Local NEW issuer identity:** canonical inventory retains Account's exact issuer string, and typed reads refuse retained UUID issuers rather than relabel them. This storage boundary does not establish issuer ownership, complete coverage, or admission; see [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for migration proof and limits. + +- **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). + +- **Account-fence intent and CLOSED target preparation:** local sources persist account acquisition intent and cohort, tenant-to-gameplay-tag mapping, protected current observations, a one-key CLOSED installer/readback, and immutable per-target receipts. A receipt is historical AS-OF evidence; targets remain `REQUIRED`. Operational protected-incarnation authority, all-target `INSTALLED`, barrier `OPEN`, token release, final admitting CAS, and production admission remain unproved. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. + - **Current first-party receiving boundary:** Game Session's prepared receiver verifies the Gateway-signed context and rechecks the canonical target and retained private-handle evidence. When that first-party context is present, bare `LOGIN` and `PLAY` return `FIRST_PARTY_AUTHORITY_UNAVAILABLE` before legacy Account authentication, Entity resolution, or gameplay binding effects. Recovery from registry loss still requires the persisted compact JWS to remain valid; registry loss does not extend its expiry. The public Gateway cookie path is currently denied and its gameplay-route readiness is `OUT_OF_SERVICE`; no first-party wire success or admission is claimed. Account context production, shared replay fencing, and dedicated Gateway key qualification remain open. - Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index a8cc68a8b4..04e4598ebe 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -33,7 +33,7 @@ Every coordination script belongs to a **script category** that constrains which | Entity lock | `tick:{tenantRegionTag}:lock:` | A lock-acquiring invocation touches at most one entity-lock key. Multi-entity commands use owning transactions or durable effect legs rather than multi-lock Lua. | | Tick staging / pending | `tick:{tenantRegionTag}:pending` and related effect structures | Single-key or shard-local multi-key scripts that operate entirely within one `{tenantRegionTag}` slot. | | Timers and retries | `timer:{tenantRegionTag}`, `retry:{tenantRegionTag}` | Shard-local scripts operating on keys that share the same `{tenantRegionTag}`; no cross-slot operations. | -| Gameplay session CAS / bindings | `session:game:{tenantGameplayTag}::` plus tenant-tagged `session:game:index:*:{tenantGameplayTag}:*` | Gameplay session CAS/update scripts may be shard-local multi-key scripts where all gameplay-session keys share `{tenantGameplayTag}`. They own gameplay binding and reconnect state only; they do not operate on Account auth-token registry keys, tick keys, or the global account index in the same invocation. | +| Gameplay session CAS / bindings | `session:game:{tenantGameplayTag}::`, tenant-tagged `session:game:index:*:{tenantGameplayTag}:*`, and `session:game:account-admission:{tenantGameplayTag}::` | Gameplay session CAS/update scripts may be shard-local multi-key scripts where all gameplay-session keys share `{tenantGameplayTag}`. The final binding CAS checks the exact account-qualified barrier in that slot. These scripts do not operate on Account auth-token registry keys, tick keys, or the untagged global account index/control key in the same invocation. | | Cross-tenant gameplay-session account index | `session:game:index:account:` | This global account index cannot share every tenant gameplay slot and is never included in a shard-local gameplay CAS/Lua invocation. Game Session updates it through a separate idempotent write after the owning gameplay-session mutation and reconciles it from authoritative session bindings. Account-wide revocation uses the index as a discovery projection but verifies and mutates each tenant-local binding through its owning shard-local contract; missing or stale index entries are repaired rather than treated as authorization truth. | | Account auth-token registry | `session:auth:token:` | Account-owned issued-token registry operations are single-key operations for the exact token hash. The exact-token registry record is mandatory validity and per-token-revocation authority: a cryptographically valid JWT without a matching permitted record is denied, and Lua must not invent validity from absence or from a generation alone. Durable issuer/account/tenant/membership authority generations advance in Account Service; Redis entries project/read through those durable generations for validation, while Lua may enforce the stored record state but never becomes the authority for generation advancement. This is not part of gameplay session CAS. | | Gateway replay admission | `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` | The `gateway-connect-token-replay-consume/v1` descriptor is the only three-key descriptor in this category: it runs only on Coordination Redis and receives readiness/fence, replay, and deny keys in that order. The literal `{gateway-connect-token-replay-v1}` hash tag is required on all three keys so Redis Cluster executes the atomic operation in one slot; the readiness value carries `replayAdmissionFence`. The separate `gateway-connect-token-browser-revoke/v1` descriptor is a one-key deny-marker mutation using only `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` with the same literal tag; it is not part of this three-key key order. The current generic Cache-bound writer's only untagged output is the replay marker; it has no deny-marker, readiness, or replay-fence writer. That old replay key is migration-only drift and is not a valid descriptor shape. | @@ -208,6 +208,8 @@ Session scripts operate only on gameplay session keys that share one `{tenantGam - `session:game:index:tenant:{tenantGameplayTag}` - `session:game:index:realm-grant:{tenantGameplayTag}:` when the binding is private/playtest grant-gated, where `grantScopeId` is the exact canonical `grant/v1` scope ID for the complete Account-owned tuple +The final binding CAS additionally reads `session:game:account-admission:{tenantGameplayTag}::` as a checked key in the same gameplay slot; it never mutates that barrier. The separate one-key CLOSED installer owns its mutation, under the [account-admission barrier contract](./system-architecture-session-behavior.md#global-account-active-binding-index). The global account index remains excluded from this invocation. + `session:game:index:account-tenant:{tenantGameplayTag}:` is the canonical tenant-scoped account index key. It must not be shortened to `session:game:index:account:`; that is a separate cross-tenant discovery index and is never part of a shard-local Lua invocation. The lifecycle-qualified realm-grant key is enabled only through the [canonical versioned `grant/v1` direct cutover and shared index-key builder](./system-architecture-redis.md#canonical-grant-authority-stream-scope-codec). Lua callers receive the fully built key and never normalize or concatenate selector fields independently. This Lua-local consequence requires an immutable Account v1 grant inventory and checkpoint: affected Account grant mutations and inventory changes remain fenced while Game Session rebuilds the complete expected key set from that exact inventory/checkpoint and reads back the rebuilt v1 key/index set before activation. During enumeration, build, exact readback, and activation, affected legacy grant producers and consumers, runtime/index readers, and every non-migration grant-index writer remain quiesced or fenced; only the migration operation may write unless an atomic switch of all writers is proven. Readers never dual-read or fall back to the legacy key; legacy entries remain non-authoritative until post-activation proof permits their removal. An incomplete rebuild, concurrent non-migration write, unexpected legacy entry, crash, or contradictory readback keeps the affected scope fenced and resumes the same migration operation. Focused proof reuses the codec's canonical round-trip, malformed-input, tuple-distinctness, and collision-resistance vectors and demonstrates that every session writer, reader, Lua caller, reconciler, and reset path receives the same helper-built key rather than introducing a second key grammar. diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index a3a2b5dba9..6eb40aa45b 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -230,6 +230,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session::` | **Coordination (current legacy implementation drift; untagged)** | **Reset-sensitive** | This current Game Session runtime-state projection is derived from PostgreSQL/current ownership state, which remains authoritative. Missing, stale, partial, or ambiguous Redis state cannot authorize tick progress; Game Session must rebuild it and complete exact readback before resuming affected runtime operations. | `SessionStateService`/Game Session currently writes the projection for game-instance lifecycle state. It is distinct from target `session:game:*` gameplay bindings and from `sessionctx:*`; the current key has no canonical region scope and remains implementation drift. | | `session:game:index:character:{tenantGameplayTag}::` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the target `{tenantId, playableStateNamespaceId, characterId}` character-to-session controller uniqueness entry may be dropped; at region scope, only the exact key for an affected binding is retained, removed, or recreated from durable binding inventory, preserving unrelated character keys, regions, and tenants. Takeover, resume, and new admission remain fenced until Game Session rebuilds or reconciles the exact entry and validates the server-derived `playableStateScope` binding/routing evidence plus value/evidence `{sessionId, gameInstanceId, bindingGeneration}` against the session record. An unbound-character decision requires that durable inventory readback to prove there is no active binding; an empty Redis key alone never proves availability. See [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). | Tenant-scoped and namespace-qualified, with the shard-local session CAS; `playableStateScope` remains binding/routing context. Rebuild removes stale entries, recreates missing entries, and rejects conflicting identities. The existing `:` index key is current implementation drift, not the target key. | | `session:game:index:account:` | Coordination | **Reset-sensitive with mandatory account-wide reconciliation** | Account-wide lookup is unavailable while the global index is dropped; narrow parents do not rebuild the untagged key, and account-wide access remains fenced until the complete owner-defined recovery result is consumed. | This is the one retained untagged global account exception: every member is a complete tenant-qualified `accountIndexMember`, so the key is not a tenant-local selector. Its physical layout and member contract are owned by [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index); narrower resets preserve unrelated tenants and cluster reset rebuilds the complete key. | +| `session:game:account-admission:{tenantGameplayTag}::` | Coordination | **Reset-sensitive; missing or replaced state denies admission** | Loss, deletion, or storage replacement affecting the exact account/tenant/namespace slot keeps the affected scope closed. Absence is never implicit OPEN, and a retained historical CLOSED receipt does not prove current installation or authorize recreation as OPEN. | This persistent tenant-tagged hash is checked in the same slot as the tenant-local final binding CAS. Game Session must validate current protected incarnation and exact current owner/barrier state under the [Session account-intent protocol](./system-architecture-session-behavior.md#global-account-active-binding-index); reset alone proves neither installation nor account-wide coverage. | | `session:game:index:account-tenant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-qualified account lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant-scoped resume, takeover, and bounded revocation remain fenced until Game Session rebuilds it and the matching session/index obligations are acknowledged. Each index member remains an active `sessionId` value under the owner-defined schema. Reconciliation is inventory-led: it derives the exact expected active `sessionId` set from authoritative durable `GameplayBindingInventory` rows; each row's complete `bindingRef` and tenant/game/session identity supply `gameInstanceId` and directly address its canonical session record. Before deriving or writing a member or accepting readback, it exact-compares the row's canonical binding-owner `accountId` with the key's ``; a missing, malformed, or mismatched owner is rejected or quarantined and keeps the affected account/index scope fenced. It independently validates the exact session record, including controller identity `{tenantId, playableStateNamespaceId, characterId}`, server-derived `playableStateScope`, `gameInstanceId`, `bindingGeneration`, and lifecycle, then reads back the expected `sessionId` set before acknowledging the matching index/session obligations. Reconciliation never infers `gameInstanceId` from a bare member and does not use wildcard scans or invent a separate resolver. This consumes the existing owner-defined schema and producers; it does not change them. | Tenant-scoped and part of the shard-local session CAS. Reconciliation is limited to the gameplay tag and validates the canonical session record rather than treating index membership as authoritative. | | `session:game:index:tenant:{tenantGameplayTag}` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-wide active-session lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant revocation, inspection, and repair remain fenced until Game Session rebuilds or reconciles and reads back the tenant index. | Tenant-scoped and shard-local. Reconciliation must not use the global account index as a substitute or admit a binding from tenant-local key presence alone. | | `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the lifecycle-bound private/playtest grant lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds or reconciles and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index b4557e3e9a..e5c7faedef 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -313,6 +313,8 @@ Reset scope, session policy, and recovery release are canonical in [Redis Reset - Index mutation is a separate fenced operation from the tenant-local binding CAS. Narrow region/tenant or break-glass cleanup may repair only affected members of tenant-owned `session:game:index:*` projections and must preserve unrelated members and tenants. Untagged global account and issuer indexes are not narrow cleanup targets; replacement or rebuild requires the complete account- or issuer-wide durable inventory, coverage proof, exact readback, and the maintenance-lock release gate. If break-glass mutates an untagged global account or issuer index, the affected index and dependent admission remain fenced while evidence is preserved and the owner-defined [global index-family recovery consequence](./system-architecture-redis-reset-and-recovery.md#global-index-family-recovery-consequence) is followed; a narrow reset cannot serve as local repair. Redis `SCAN`, key absence, or a projection alone cannot establish coverage. - Every consumer validates each referenced tenant-qualified binding and current Account authority. The global key never authorizes cross-tenant gameplay or substitutes for membership, grant, or entitlement checks. +The account-qualified local admission barrier is a separate tenant-tagged Coordination key: `session:game:account-admission:{tenantGameplayTag}::`. It is a persistent hash in the same gameplay slot as the tenant-local final binding CAS, never a member of the untagged global account-index operation. The one-key CLOSED installer validates and changes only this exact hash; physical type/readback and exact scope are mandatory, unrelated account-index members are not consulted or changed, and a missing or reset barrier remains non-admitting. Session Behavior owns the intent, cohort, protected-incarnation, and receipt contract. A CLOSED value and its historical receipt do not establish installed account coverage, authorize OPEN, or prove admission. + ### Issuer Active-Binding Index The issuer cutoff family is intentionally **global per Account environment issuer**, not tenant-scoped. `issuerId` identifies the Account issuer and its issuer-generation cutoff; the `issuer/` authority stream and this derived index cover active and provisional gameplay bindings across every tenant under that issuer. Account owns the durable issuer generation, cutoff event, and outbox/checkpoint authority. Game Session owns the gameplay binding records, issuer partitions, repair obligations, coverage evidence, and socket/admission termination. The index cannot advance issuer authority and is not an authority source. @@ -624,6 +626,7 @@ Key principles: - Session-only Lua scripts may perform shard-local multi-key CAS/update flows across these tenant-scoped keys, but they must not include the untagged global account index, mix `{tenantGameplayTag}` session keys with `{tenantRegionTag}` tick-region keys, or claim cross-slot account-index atomicity in the same invocation. - Representative patterns: - `session:game:{tenantGameplayTag}::` + - `session:game:account-admission:{tenantGameplayTag}::` - `session:game:index:character:{tenantGameplayTag}::` - `session:game:index:account-tenant:{tenantGameplayTag}:` - `session:game:index:tenant:{tenantGameplayTag}` @@ -680,6 +683,7 @@ This table lists representative coordination keys and their responsibilities. Fu | `session:game:index:tenant:{tenantGameplayTag}` | Tenant-scoped reverse index used for bounded revocation, reconnect, and inspection without wildcard scans. | | `session:game:index:realm-grant:{tenantGameplayTag}:` | Tenant-scoped lifecycle-bound non-public grant index, covering ordinary private and playtest grants, used for bounded realm admission and revocation. `grantScopeId` is the exact shared-codec `grant/v1` scope ID for the complete Account-owned tuple; Account-owned grant state remains authoritative. Public-production and unscoped bindings have no entry. | | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Global-per-issuer bounded hash of active/provisional binding references and captured issuer generations across tenants, maintained by Game Session through the versioned-layout repair/CAS and durable coverage-ack protocol and swept across the finite configured partition range for issuer cutoffs. | +| `session:game:account-admission:{tenantGameplayTag}::` | Persistent tenant-slot hash for the exact account/tenant/playable-state namespace barrier. Game Session closes it under the durable account intent and checks it in the same tenant slot as the final binding CAS. It is missing-state non-admitting and is not the global account index or account-wide coverage evidence. | | `retry:{tenantRegionTag}` | Retry queue for failed actions, keyed by `next_eligible_tick_id` on the target region timeline (not wall-clock due time). | | `tick-executor-lease:{tenantRegionTag}` | Redis-local liveness key for the active tick executor. Its value is an opaque token checked by lease Lua; durable ownership and handoff semantics are owned by [Tick System: Region Authority and Tick Executor](./system-architecture-ticks.md#region-authority-and-tick-executor). | | `timer:{tenantRegionTag}` | Typed due-domain projection for region timers. Every source carries exactly one due-domain tag: tick/game timers use `dueTickId`, while wall-clock timers retain one immutable absolute `dueAt`; a wall-clock source may receive a separately assigned `due_tick_id` only as its gameplay-tick admission-order coordinate. Storage/indexing must preserve the tag and must never numerically compare or alias tick IDs and epoch-millisecond values. The due-point and ordering owner is [Tick Execution Flow: Work Ordering Inputs](./system-architecture-tick-execution-flows.md#work-ordering-inputs-adr-0065). | diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index cb1c1b4ef8..e38327a467 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -56,6 +56,16 @@ The one-controller invariant is exactly one active gameplay controller for `{ten At the transfer linearization point, the old binding becomes non-admitting for new input. Input arriving from the displaced transport after that point is rejected, while work durably admitted before it retains its existing command/effect identity and follows its ordinary durable execution and reconciliation contract. Takeover does not recreate admitted work from client input, blindly cancel it, reset character-owned ticks/timers/state, or require close-frame delivery to make the transfer authoritative. Closing the displaced transport and emitting `session_replaced` are best-effort consequences after the CAS; failure to deliver them never restores old authority. +### Canonical public-production NEW admission + +The selected canonical `NEW` path uses Account's purpose-specific `AccountGameplayAdmissionLeaseService` Acquire, Finalize, Read and Abort operations under the exact same-namespace Game Session workload certificate. Account authenticates its current caller independently; a caller-workload field, account selector or generic service JWT is never that authority. The unchanged complete `AccountGameplayAdmissionLeaseEvidence` is bounded to 64 KiB and an absolute lifetime of at most 15,000 milliseconds. Current predicates, source locks and writer exclusion must hold in the decisive original Account physical-COMMIT transaction. A pre-transaction source check is insufficient. The original synchronous COMMIT and same-connection post-COMMIT clock bound, followed by independently durable acknowledgement-receipt proof, cannot be reconstructed from a later read or serialized in-process acknowledgement. + +The binding and issuer-index `issuerId` is the exact Account issuer identifier defined by [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md), carried without normalization or a UUID surrogate. Acquisition, finalization and reconciliation compare that identity together with its generation and original source/checkpoint evidence against authenticated current Account owners; generation equality or caller-supplied spelling alone is insufficient. Existing UUID-shaped issuer records without exact original authoritative provenance remain non-admitting and retained for explicit fenced reconciliation. A forward storage conversion preserves their original identity, evidence and cleanup obligations; it never relabels them as the Account issuer or assumes an empty inventory. + +The pre-lease published-target read and exact lease-bound `PROVISIONAL` decision read are separate Account-only purposes on the same Game Session service, following the [authentication sequence](./system-architecture-authentication.md#in-band-play-admission-boundary). Game Session independently joins the actual initial World placement to its current runtime-region assignment through the [World owner read](./microservices/world-management-service/api-contracts.md#grpc-apis) and revalidates that source at the binding gate. A guessed region, template-region identity or single-entry map is not placement authority. The candidate remains non-admitting until exact Account `COMMITTED` evidence, actual account-index and issuer-partition acknowledgements, the region bridge acknowledgement and the final tenant-local session/index CAS agree. Only that final CAS admits `PLAY` or `LOOK`. This initial path may refuse existing-controller transfer and resume until their complete protocols are qualified; it does not introduce an ordinary session-save or default-room shortcut. + +These are the selected target requirements. The current manual source/decision transports, caller verifier and component proof do not establish a complete admitted player binding or default runtime registration. Remaining implementation and proof are recorded in the [Player Access and Session tracker](../project-management/implementation-tracking/player-access-and-session.md). + ## Multi-Client Behavior and Session Takeover Each gameplay identity can only be controlled by one session at a time. The target uniqueness and CAS owner key is `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` and `gameInstanceId` are carried as binding/routing evidence, not as additional controller keys. @@ -173,7 +183,7 @@ Target-state Game Session must also maintain bounded authoritative secondary ind Index contract requirements: - In target state, Game Session is the sole writer for all six index families; Account authority and realm-grant state remain the authorization source, not the indexes. -- The shard-local CAS/update flow contains exactly the gameplay session record plus the four tenant-scoped indexes: character, account-tenant, tenant, and realm-grant. All of those keys share `{tenantGameplayTag}`. The initial CAS publishes only the provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. +- The shard-local CAS/update flow mutates exactly the gameplay session record plus the four tenant-scoped indexes: character, account-tenant, tenant, and realm-grant. The final binding CAS additionally reads the exact account-admission barrier as a checked key and never writes it; the separate one-key CLOSED installer owns that mutation. All of these keys share `{tenantGameplayTag}`. The initial CAS publishes only the provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. - The cross-tenant `session:game:index:account:` and issuer-partition indexes are explicitly excluded from that shard-local CAS because they span tenant hash slots or issuer partitions. The untagged account key is also excluded from every tenant-local Lua invocation. Before the tenant-scoped CAS publishes a new binding, Game Session durably commits deterministic account-index and issuer-index repair obligations keyed to that binding transition. The account obligation contains the expected prior generation, candidate `bindingGeneration`, unique transition identity, desired add/remove, and `accountIndexFence`; the issuer obligation also carries its exact reservation identity. The shard-local CAS may publish only a provisional binding with each applicable `accountIndexState=REPAIR_REQUIRED` and `issuerIndexState=REPAIR_REQUIRED`; it is not admissible for gameplay, resume, or takeover. Game Session then performs each separate idempotent single-key index/capacity compare-and-set, reads back the exact generation/fence-qualified member and reservation state, and durably acknowledges each matching account/issuer obligation. The region-lease bridge is another ordered, separately acknowledged follow-up using the validated binding generation and region epoch. Only after all required account, issuer, and region acknowledgements does the final follow-up shard-local CAS exact-compare the provisional generation, set the applicable states to `ACKNOWLEDGED`, and admit the binding at the controller linearization point. This ordered protocol closes the cross-slot and region-bridge crash windows without claiming a cross-store transaction. - An issuer-index write or removal compares the complete expected `bindingRef`, `bindingGeneration`, `issuerAuthGeneration`, and active `issuerIndexLayoutVersion` before changing the hash field; the same operation also compares the exact reservation owner, transition, partition/layout, lifecycle, fence, and revision. An identical already-applied value is an idempotent success, while a newer or conflicting value is a repair conflict. At the start of an issuer cutoff or recovery, Game Session captures the active layout pointer's version, partition count, and capacity while establishing the operation and coverage fences, then reads exactly that pinned finite partition range and maps every binding through the canonical mapping helper; it does not reread the pointer and mix layouts during the operation. If the pointer no longer matches before acknowledgement, the current operation fails closed or enters the explicit layout-transition workflow, which accounts for the complete pinned old layout and separately built new layout before cutover; neither workflow evaluates a mixed partition set. The operation validates every returned value and reservation, then fences or terminates the referenced bindings through their ordinary binding CAS. Missing Redis responses, unreadable partitions, unresolved reservations or repair obligations, or conflicting field values are unavailable or ambiguous coverage, never an empty result. Recovery rebuilds each partition from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, canonical mapping, and capacity rules and clears the repair obligation only after every required partition, reservation, and binding acknowledgement is proven. - An issuer-partition acknowledgement is a durable evidence object, not an aggregate flag. For preserved region/tenant recovery it must carry the child-owned `issuerCoverageOperationId` and child lifecycle, the child `issuerCoverageOperationFence`, distinct issuer-wide `coverageFence`, `coverageGeneration`, issuer-wide `inventorySnapshotRevision`, pinned `issuerIndexLayoutVersion`, pinned partition count and capacity, `partitionId`, the exact `issuer/` cutoff checkpoint (`issuerAuthGeneration`, `issuanceFence`, and complete applicable `outboxCheckpoints`), every reservation identity with its owner, transition, lifecycle, fence, and inventory revision, and the capacity tuple `{partitionId, reservationCount, partitionCapacity, aggregateReservationCount, aggregateCapacity}`. The independent parent edge and the parent's consumption record carry the exact linked `parentRecoveryOperationId`, both current lifecycles, parent `operationFence`, distinct `parentCoverageFence`, resolved issuer/scope, and link revision; the child request/digest, transition, partition and reservation readback, acknowledgement, and immutable child result are parent-independent. `coverageGeneration=NOT_YET_ISSUED` remains the pre-coverage value and becomes concrete only after complete finite coverage is proven. For a standalone issuer-wide operation, the operation identity is its own issuer coverage operation identity and still carries its own maintenance fence and coverage fence; all parent fields and account-wide fields are the exact `NOT_APPLICABLE` marker plus `NO_ACTIVE_ACCOUNT_WIDE_FLOW`. The acknowledgement is valid only when all of that evidence comes from the same complete issuer-wide snapshot and operation attempt, with exact readback of the partition and reservation state. Cross-snapshot, cross-attempt, narrow-scope, stale-layout, changed-cutoff, mixed-partition, missing-reservation, or partial-capacity evidence is rejected; no acknowledgement may be assembled from separately read responses or used to authorize a different operation or layout. @@ -227,7 +237,19 @@ accountIndexAcknowledgement = { The independent linked edge and the parent's exact consumption record carry `parentRecoveryOperationId`, `parentLifecycle`, `parentOperationFence`, and `parentCoverageFence` alongside the child result identity and `linkRevision`; none of those parent-link fields is part of the parent-independent child acknowledgement. -`operationFence`, `coverageFence`, `coverageGeneration`, and `inventorySnapshotRevision` must bind the acknowledgement to the same durable operation and immutable account inventory snapshot; `accountIndexFence` must bind it to the exact binding generation. `accountCoverageState` is the sole versioned discriminator for the account-fence lifecycle: `ACTIVE` requires concrete `accountCoverageOperationId`, `accountCoverageLifecycle`, `accountCoverageOperationFence`, `resolvedScope`, and `accountAdmissionFence`, with `historicalAccountAdmissionFence=NOT_APPLICABLE`; `HISTORICAL` requires the same concrete account-coverage identity and exact released `historicalAccountAdmissionFence`, with `accountAdmissionFence=NOT_APPLICABLE`; and `NO_ACTIVE_ACCOUNT_WIDE_FLOW` requires `accountCoverageOperationId=NOT_APPLICABLE`, `accountCoverageLifecycle=NOT_APPLICABLE`, `accountCoverageOperationFence=NOT_APPLICABLE`, `accountAdmissionFence=NOT_APPLICABLE`, `historicalAccountAdmissionFence=NOT_APPLICABLE`, and `resolvedScope=NOT_APPLICABLE`. The state and its lifecycle-appropriate fence are carried and exact-compared through the child-owned request/digest, transition, member readback, acknowledgement, exact retry, linked edge, and parent-consumption record; a flow that acquired account-wide fencing never enters the no-active arm. The independent edge and parent-consumption record additionally carry the parent tuple and `linkRevision` and exact-compare the historical account fence after release; those edge fields never enter or specialize the reusable child result. A standalone account-wide operation uses its own concrete account coverage fields and the same live-then-historical fence lifecycle and has no parent edge. `coverageGeneration` is `NOT_YET_ISSUED` before coverage is proven and becomes concrete only in the atomic coverage-proven transition that releases the live account admission fence and retains its historical value. `ADD_OR_RETAIN` requires the exact generation-qualified member in `PRESENT` readback, while `REMOVE` requires `ABSENT` readback and omits `member`. No acknowledgement may be assembled from separately read or cross-snapshot evidence. +`operationFence`, `coverageFence`, `coverageGeneration`, and `inventorySnapshotRevision` must bind the acknowledgement to the same durable operation and its immutable, owner-scoped inventory snapshot; `accountIndexFence` must bind it to the exact binding generation. `ACTIVE` and `HISTORICAL` use the complete account-wide snapshot. `NO_ACTIVE_ACCOUNT_WIDE_FLOW` uses the binding-local snapshot defined below and never establishes whole-account completeness. `accountCoverageState` is the sole versioned discriminator for the account-fence lifecycle: `ACTIVE` requires concrete `accountCoverageOperationId`, `accountCoverageLifecycle`, `accountCoverageOperationFence`, `resolvedScope`, and `accountAdmissionFence`, with `historicalAccountAdmissionFence=NOT_APPLICABLE`; `HISTORICAL` requires the same concrete account-coverage identity and exact released `historicalAccountAdmissionFence`, with `accountAdmissionFence=NOT_APPLICABLE`; and `NO_ACTIVE_ACCOUNT_WIDE_FLOW` requires `accountCoverageOperationId=NOT_APPLICABLE`, `accountCoverageLifecycle=NOT_APPLICABLE`, `accountCoverageOperationFence=NOT_APPLICABLE`, `accountAdmissionFence=NOT_APPLICABLE`, `historicalAccountAdmissionFence=NOT_APPLICABLE`, and `resolvedScope=NOT_APPLICABLE`. The state and its lifecycle-appropriate fence are carried and exact-compared through the child-owned request/digest, transition, member readback, acknowledgement, exact retry, linked edge, and parent-consumption record; a flow that acquired account-wide fencing never enters the no-active arm. The independent edge and parent-consumption record additionally carry the parent tuple and `linkRevision` and exact-compare the historical account fence after release; those edge fields never enter or specialize the reusable child result. A standalone account-wide operation uses its own concrete account coverage fields and the same live-then-historical fence lifecycle and has no parent edge. `coverageGeneration` is `NOT_YET_ISSUED` before the applicable owner proves its outcome. For `ACTIVE` and `HISTORICAL`, it becomes concrete only in the atomic account-wide coverage-proven transition that releases the live account admission fence and retains its historical value. For `NO_ACTIVE_ACCOUNT_WIDE_FLOW`, the separate binding-local completion rule below allocates the concrete evidence generation without acquiring or releasing an account-wide fence. `ADD_OR_RETAIN` requires the exact generation-qualified member in `PRESENT` readback, while `REMOVE` requires `ABSENT` readback and omits `member`. No acknowledgement may be assembled from separately read or cross-snapshot evidence. + +For an ordinary first `NEW` with a positively read account-control state of `NO_ACTIVE_ACCOUNT_WIDE_FLOW`, the existing Game Session transition owner begins one durable binding-local member-repair operation for the original transition. It freezes the original `ADD_OR_RETAIN` obligation, exact tenant-qualified `bindingRef`, binding-owner `accountId`, tenant, candidate generation, `accountIndexFence`, the positively present control row's nonnegative epoch, and immutable inventory snapshot, and allocates one operation identity, monotonic operation fence, and distinct coverage fence. Exact retry and restart retain that tuple; they do not take a fresh snapshot or invent new fences. This snapshot covers only the one original member obligation and cannot establish account-wide inventory completeness. Outside SQL, the separate physical Redis operation adds or retains exactly the generation-qualified member in `session:game:index:account:`, preserving unrelated tenants and newer generations; it does not enumerate, rebuild, delete, or infer completeness from key absence. SQL accepts only the actual exact-member readback after independently reloading the original tuple and current control row, then atomically records the acknowledgement and its later binding-local `coverageGeneration`. That generation acknowledges this member operation only. A missing control row, missing or malformed member, changed operation/control epoch, unavailable readback, or ambiguous mutation leaves the original obligation unresolved and the candidate non-admitting. This arm has no account-wide operation, lifecycle, fence, or resolved scope and never supplies one. An already acknowledged binding-local record remains retained unchanged when the current account-control state or epoch moves; its acknowledgement flag does not make it current again. Current-candidate reads and continuation refuse the stale epoch, preserving the original operation, frozen tuple, readback and outstanding repair or cleanup obligations as a non-admitting handoff to the actual account-wide fenced settlement owner. Reconciliation must not mint a replacement identity or generation, silently reanchor the original operation, or treat a later no-active state as proof that the old candidate was settled. + +Account-control acquisition and per-tenant barrier installation are a separate account-scoped protocol from this member repair. The owner durably records one original acquisition intent and closes new candidate preparation and admission-capable token issuance for that account before freezing the complete affected cohort of bindings, reservations, unresolved obligations, and in-flight candidates across tenants. A racing candidate is included or refused by that same durable boundary; a Redis index or barrier is not inventory authority. The frozen target set identifies exact tenant and playable-state namespace slots through persisted tenant-to-gameplay-tag assignments. For each target, the owner obtains a protected current-incarnation observation before and after the remote Redis step, performs the one-key `CLOSED` mutation, then reads the physical value back and reloads the SQL owner context. No SQL transaction spans a Redis or protected-source call. + +The account-qualified barrier key is `session:game:account-admission:{tenantGameplayTag}::`. Its persistent hash has exactly nine fields: `schema=gs_account_admission_barrier/v1`, `accountId`, `tenantId`, `playableStateNamespaceId`, `tenantGameplayTag`, `ownerOperationId`, `ownerFenceEpoch`, `incarnationDigest`, and `state`. Epochs are canonical decimal strings compared without floating-point conversion. A `CLOSED` acquisition uses a positive epoch; the positively established initial no-active control epoch may be zero, so the first acquisition may close a prior `OPEN` epoch `0` at epoch `1`. Zero never stands for a missing control row. A missing key may be created `CLOSED` only under the current original intent. An older well-formed barrier may advance only under a newer epoch and a different owner operation; equal epoch permits only exact same-operation, same-incarnation `CLOSED` replay. Malformed, expiring, foreign-scope, equal-conflicting, or newer barriers are refused without mutation. This key shares the tenant gameplay slot with the final session CAS; the global account index is never a member of that Lua invocation. A `CLOSED` write or a key-builder result grants no opening or admission authority. + +The stable `incarnationDigest` is SHA-256 over strict canonical JSON for the protected attestor binding, accepted canonical attestation digest, complete `targetDeploymentEvidence/v1` tuple (including deployment, Redis build, Lua registry, boot/startup and storage/AOF generations), and separately observed ACL and Redis-configuration digests. Fresh current-observation nonces, observation times, operation context, and signing-key identifiers do not change that stable storage binding. Each signed bounded current observation must bind the fresh receiver nonce and time window to the original account operation/fence, frozen cohort and exact tenant/namespace target, and must match the fixed trusted deployment expectation. The operational accepted-attestation/current-proof source is not supplied by the local controlled-signature fixture, so that fixture proves verifier mechanics only, not production custody or reset continuity. + +A retained barrier with the same operation and epoch but a changed stable incarnation is a conflict even after a fresh protected observation; it cannot be rewritten in place by an exact retry. Game Session’s account-wide fenced recovery owner must resolve replacement under the [canonical reset and recovery boundary](./system-architecture-redis-reset-and-recovery.md#canonical-reset-sequence-boundary), preserving the original intent and historical evidence while the affected target stays closed and unresolved. The local CLOSED installer does not supply that recovery; see the [implementation gap](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). + +The owner stores an immutable per-target historical `CLOSED` receipt only after actual bounded Redis mutation/readback, protected observations, and post-call SQL currentness checks agree. It binds the original intent, target ordinal and scope, exact barrier postimage and stable incarnation. A receipt is AS-OF evidence: it is not a current Redis observation, a durable `INSTALLED` state, or permission to open a barrier. Only a future current, complete all-target owner boundary could establish installed fencing; a missing, partial, stale, or reset target remains closed and unresolved. The local account-fence source currently has no all-target installation publication, barrier-opening or token-release phase, final admitting CAS, or admission proof. For account-wide recovery, logout-all, or reconciliation, the canonical account-wide child enumerates the complete durable inventory for the account, including all tenants and unresolved obligations, under an immutable snapshot. Every child-owned post-fence transition, account-index request/digest, exact member readback, acknowledgement, and retry must carry and exact-compare the child tuple `{child operationId, child lifecycle, child operationFence, child coverageFence, coverageGeneration, inventorySnapshotRevision, accountCoverageState}`; the independent parent edge and the parent's consumption CAS additionally carry and exact-compare `{parentRecoveryOperationId, parentLifecycle, parentOperationFence, parentCoverageFence}` plus the child result identity and `linkRevision`. Neither parent fence nor child fence, coverage generation, inventory snapshot revision, account coverage state, or lifecycle-appropriate account fence may be omitted or substituted by a high-water mark. The issuer-partition form uses the separate issuer-wide acknowledgement tuple above, with parent fields held only by its linked edge and parent-consumption record; account-wide and issuer-wide evidence must not be substituted for one another. A region- or tenant-scoped parent may repair only individually fenced affected `accountIndexMember` entries, must leave unrelated global members untouched, and cannot drop or rebuild the untagged global account key or publish account-wide coverage from that narrow snapshot; it remains subordinate to the canonical account-wide child. The canonical account-wide child rebuilds the complete account key before protected admission reopens. The workflow reads back the exact expected generation-qualified member set and fails closed on missing rows, partial coverage, duplicate identities, stale entries, or unresolved obligations; it never uses Redis `SCAN`, key absence, or the global index alone as proof. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 274774a523..8a0f63bdf6 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -396,3 +396,18 @@ Entry format: - Context: the shared Gameplay observer inspected paginated GitHub commit-status records for the PR train. - Observation: `/statuses` retained superseded pending and failed entries even after the same gate had published success. Treating every historical entry as current briefly misclassified a green candidate; the direct combined `/status` response and latest entry per context established the actual state before any CI mutation or escalation. - Expected pattern: use the current combined-status response and latest status per context for readiness; preserve pagination for full check-run coverage, and treat raw status history as history. Verify a reported failure against its exact run and job before retrying or attributing a CI defect. + +- `2026-10-26`: Bind PostgreSQL timestamps and binary Redis keys explicitly in fixtures + - Context: In Gameplay R517, jOOQ plain SQL bound an `OffsetDateTime` fixture value as `VARCHAR`; PostgreSQL refused the timestamp column before the migration test reached its subject. R518 passed the retained-row upgrade and restart case. In the new CLOSED-barrier fixture, both a direct `byte[]` and an inline single-element `byte[][]` triggered SpotBugs' primitive-array varargs detector for Lettuce `RedisCommands` key varargs. + - Observation: Plain SQL fixture timestamp bindings need an explicit database type, and Lettuce's primitive-array key varargs require an explicitly typed collection conversion. The native test result remains separate from the aggregate's static failure. + - Expected pattern: Use `CAST(? AS timestamp with time zone)` at the fixture binding while retaining timestamp and schema constraints. Reuse `List.of(key).toArray(byte[][]::new)` from the [initial-context AOF probe cleanup](../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java), rather than suppressing the detector. + +- `2026-10-26`: Preserve the R526 Redis startup refusal as undiagnosed evidence + - Context: The CLOSED-owner test failed while its Redis 8.10 container was starting and waiting on `localhost:54214`; assertions did not run. The exact run-owned container `e00a9761678b8fa9dead11e45604ad263049409c19746034c72b7565d549b669` was absent at inspection, as were all 11 R526 containers. + - Observation: The cause is unknown; this does not diagnose a test defect, timeout, or OOM. A passing retry would not diagnose the cause. + - Expected pattern: Preserve the failed aggregate and rerun focused normal proof without timeout or host-setting changes. + +- `2026-10-26`: Capture original evidence before investigating R533 finalization timing + - Context: `staleSerializableGenuineAckCreatorRetriesAndRetainsOneExactWinner` failed in `finalized()` after 1.292 seconds, before the serializable race began. + - Observation: The SQL guard message `storage deadline expired` covers either `evaluatedAt >` the database clock or `expiresAt <=` the database clock, so the branch and clock cause are unknown. Retain the failed result; an unchanged future retry cannot recover the original failure-time clock evidence. + - Expected pattern: Capture the original evidence timestamps, JVM and database wall clocks, and monotonic elapsed time only after a failure, without delaying the original COMMIT or changing its lifetime or guard. 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 7bf6da24a0..c1d94dee24 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,20 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Canonical NEW admission components + +The Account gameplay-admission lease and the unregistered Game Session receiver remain separate authority boundaries. The unregistered Account verifier uses the pinned trusted JWKS and fixed gameplay-delegation profile, selects the current `COMMITTED`/`ACTIVE` issuance by verified JTI, and compares the full immutable token identity, hash and authority; it retains no presented JWT and makes no membership, entitlement or lease decision. Focused acquisition proof joins the exact recovered JWT to actual current issuance, physical Coordination Redis and the same-connection Account source graph, preserving the original pending lease on retry. R494 freshly passes 104 Account unit cases and eight selected PostgreSQL/Redis cases, with affected static analysis and formatting. Its manual TLS receiver exercises all four generated RPCs with the exact recovered Account JWT and current issuance/registry and SQL sources, then performs PostgreSQL 18 physical COMMIT and independent durable original-ACK insertion/readback. The original lease attempt and ACK are immutable. The original physical-commit executor retains focused PostgreSQL component proof, and the Game Session lease client has controlled mTLS proof; the retained PostgreSQL 18 receipt-reader denial remains unchanged. The reverse Game Session target/decision response and protected signer/materializer evidence remain controlled. Exact metadata and cleanup-obligation recovery revalidate the current caller/global Account/token under Account-first SQL locks without requiring a superseded tenant admission baseline; new acquisition and first finalization retain full tenant-source checks. These results do not prove genuine Game Session authority, cleanup delivery, final controller admission, production custody or activation. Token-retirement, orphan-cleanup delivery and admitted binding remain open. + +The Game Session canonical inventory now retains Account's exact issuer string through the forward V1024→V1025 conversion. R488 passes 19 selected PostgreSQL cases, including populated-row migration preservation, restart, canonical writes, and refusal by the typed reader to reinterpret retained UUID issuers. This proves storage identity conversion only; issuer ownership and admission remain unqualified. + +The unregistered no-active first-NEW member-repair owner composes the original durable operation, the physical one-key global account-member write/readback outside SQL, and separate SQL acceptance. V1026 preserves the operation and completion. R506 freshly passes all 29 selected PostgreSQL/Redis cases, including composed completion, frozen retry/restart, retained prior PRESENT observations, positive control-row requirements, exact member preservation, and malformed-completion refusal. Seven focused unit cases retain R505 attribution; ten shared Redis contract cases retain R500 attribution. This is binding-local `ADD_OR_RETAIN` evidence only: it does not enumerate the account, establish global completeness, or admit the candidate. + +The account-fence preparation source consists of the durable intent/cohort owner, persisted tenant-tag/key mapping, controlled protected current-observation receiver, one-key CLOSED Redis owner, and immutable historical CLOSED receipt. R515 freshly passes nine focused unit and 37 PostgreSQL/Redis cases for intent, cohort, serialization and controlled signed current observations. R521 freshly passes nine focused unit and 46 PostgreSQL/Redis cases, including actual Redis readback acceptance into immutable per-target V1029 receipts, expiry/current-owner refusal, trigger immutability, and populated V1028→V1029 migration/restart preservation. R523 freshly passes ten native cases, including an actual intent advancing initial control epoch 0 to epoch 1 and closing a controlled prior OPEN epoch 0; prior CLOSED epoch 0 remains a non-mutating refusal. The current-observation signer/channel, prior barrier, clock, and high-water fixtures are controlled local inputs, not operational custody or lifecycle producers. These receipts are historical AS-OF evidence: the account control remains `ACQUISITION_INTENT`, targets remain `REQUIRED`, and there is no `INSTALLED`, OPEN, token, final-CAS, admission, or account-wide-coverage proof. No operational protected attestor, accepted deployment-attestation producer, or fresh protected current-proof source is supplied. + +A Redis restart or reset can change the stable incarnation while AOF retains the original CLOSED barrier. The same operation and epoch then remain a non-mutating conflict even with a fresh protected observation; the pending intent and historical receipts are retained, and admission remains closed. The local installer does not implement the canonical Game Session account-wide fenced replacement or original-intent settlement, so restart recovery liveness is unqualified. No in-place same-epoch rewrite, key deletion, inferred recovery, or automatic opening is supplied. + +The local member-repair acknowledgement also retains its original account-control epoch. Moving control to an acquisition intent or a later `NO_ACTIVE_ACCOUNT_WIDE_FLOW` epoch denies current use of an already acknowledged candidate while preserving its original operation, exact tuple and readback. The retained record is a non-admitting recovery handoff, not a newly current acknowledgement or a settled cleanup obligation. This prerequisite does not implement the account-wide fenced settlement or release owner that must reconcile that cohort before later admission; controlled higher-epoch fixtures are not production release proof. No reader allocates replacement IDs or generations, reanchors the original work or invents a terminal outcome to escape this refusal. + ### Player-created roster consumer preparation The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. diff --git a/protos/account/v1/account_gameplay_admission_lease.proto b/protos/account/v1/account_gameplay_admission_lease.proto new file mode 100644 index 0000000000..2063a5022f --- /dev/null +++ b/protos/account/v1/account_gameplay_admission_lease.proto @@ -0,0 +1,96 @@ +syntax = "proto3"; + +package account.v1; + +import "game-session/v1/canonical_gameplay_admission_decision_read.proto"; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; +option java_outer_classname = "AccountGameplayAdmissionLeaseProto"; + +// Explicit, manually composed Account-only NEW-binding owner protocol. The same-namespace +// Game Session certificate is the workload identity; no generic service JWT is accepted as it. +service AccountGameplayAdmissionLeaseService { + rpc AcquireGameplayAdmissionLease(AcquireGameplayAdmissionLeaseRequest) + returns (AccountGameplayAdmissionLeaseResponse); + rpc FinalizeGameplayAdmissionLease(FinalizeGameplayAdmissionLeaseRequest) + returns (AccountGameplayAdmissionLeaseResponse); + rpc ReadGameplayAdmissionLease(ReadGameplayAdmissionLeaseRequest) + returns (AccountGameplayAdmissionLeaseResponse); + rpc AbortGameplayAdmissionLease(AbortGameplayAdmissionLeaseRequest) + returns (AccountGameplayAdmissionLeaseResponse); +} + +// A new operation selector and expected current values only; Account still resolves and checks +// every owner. These fields do not authorize or allocate a lease. +message AcquireGameplayAdmissionLeaseRequest { + repeated uint32 schema_version = 1; + repeated string request_uuid = 2; + // Transient credential input, bounded by the existing GSA profile; never echoed in a response. + repeated string presented_initial_gsa_compact_jwt = 3; + repeated game_session.v1.CanonicalGameplayAdmissionCandidate expected_candidate = 4; + repeated game_session.v1.CanonicalPlayableTargetEvidence expected_target = 5; + repeated string binding_generation = 6; +} + +// Finalization binds the exact original Account lease to the supplied Game Session decision. +message FinalizeGameplayAdmissionLeaseRequest { + repeated uint32 schema_version = 1; + // Transient credential input, bounded by the existing GSA profile; never echoed in a response. + repeated string presented_initial_gsa_compact_jwt = 2; + repeated bytes original_lease_evidence_utf8 = 3; + repeated string binding_decision_uuid = 4; +} + +// Read is exact-operation recovery; it neither renews nor recreates a lease. +message ReadGameplayAdmissionLeaseRequest { + repeated uint32 schema_version = 1; + // Transient credential input, bounded by the existing GSA profile; never echoed in a response. + repeated string presented_initial_gsa_compact_jwt = 2; + repeated bytes original_lease_evidence_utf8 = 3; +} + +// A missing decision UUID remains UNKNOWN, never NO_TOKEN or completed cleanup. +message AbortGameplayAdmissionLeaseRequest { + repeated uint32 schema_version = 1; + // Transient credential input, bounded by the existing GSA profile; never echoed in a response. + repeated string presented_initial_gsa_compact_jwt = 2; + repeated bytes original_lease_evidence_utf8 = 3; + repeated string binding_decision_uuid = 4; +} + +enum AccountGameplayAdmissionLeaseState { + ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_UNSPECIFIED = 0; + ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_PENDING = 1; + ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED = 2; + ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED = 3; +} + +// All four methods return the same closed original-operation readback. Repeated fields preserve +// absence and duplicates for receiver validation. The lease bytes remain unchanged and complete. +message AccountGameplayAdmissionLeaseResponse { + repeated uint32 schema_version = 1; + repeated bytes original_lease_evidence_utf8 = 2; + repeated AccountGameplayAdmissionLeaseState state = 3; + repeated string binding_decision_uuid = 4; + // ABORTED-only pending cleanup obligation; this never reports cleanup completion. + repeated string orphan_cleanup_uuid = 5; + repeated AccountGameplayAdmissionOriginalAckReceiptEvidence original_ack_receipt = 6; +} + +// Complete durable AccountGameplayAdmissionOriginalAckReceipt shape. The operation identity and +// state are supplied by the enclosing response. These values are source evidence, not a serialized +// in-process OriginalCommitAcknowledgement or standalone admission authority. +message AccountGameplayAdmissionOriginalAckReceiptEvidence { + repeated uint32 schema_version = 1; + repeated string request_uuid = 2; + repeated string account_uuid = 3; + repeated string lease_uuid = 4; + repeated string lease_fence = 5; + repeated string evidence_sha256 = 6; + repeated string binding_decision_uuid = 7; + repeated string expires_at_ms = 8; + repeated string finalization_xid = 9; + repeated string committed_before_ms = 10; + repeated string receipt_xid = 11; +} diff --git a/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto new file mode 100644 index 0000000000..cd52ec8e36 --- /dev/null +++ b/protos/game-session/v1/canonical_gameplay_admission_decision_read.proto @@ -0,0 +1,135 @@ +syntax = "proto3"; + +package game_session.v1; + +import "game-session/v1/canonical_gameplay_roster_owner_read.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; +option java_outer_classname = "CanonicalGameplayAdmissionDecisionReadProto"; + +// Explicit, manually composed Account-purpose reads. GS requires the exact same-namespace Account +// workload and returns existing owner evidence without claiming gameplay admission. +service CanonicalGameplayAdmissionDecisionReadService { + rpc GetCanonicalGameplayAdmissionDecision( + GetCanonicalGameplayAdmissionDecisionRequest) + returns (GetCanonicalGameplayAdmissionDecisionResponse); + rpc GetPublishedRealmAdmissionOwnerRead( + GetPublishedRealmAdmissionOwnerReadRequest) + returns (GetPublishedRealmAdmissionOwnerReadResponse); +} + +// Repeated fields preserve wire presence and duplicate evidence for closed receiver validation. +// Lease evidence is the complete unchanged canonical AccountGameplayAdmissionLeaseEvidence UTF-8. +message GetCanonicalGameplayAdmissionDecisionRequest { + repeated uint32 schema_version = 1; + repeated string binding_decision_uuid = 2; + repeated bytes expected_lease_evidence_utf8 = 3; +} + +// Pre-lease selectors and binding correlation only. The Account UUID and counters confer no +// membership, ownership, current-caller, or admission authority; GS rereads its current owners. +message GetPublishedRealmAdmissionOwnerReadRequest { + repeated uint32 schema_version = 1; + repeated GetCanonicalGameplayRosterOwnerReadRequest selector = 2; +} + +enum CanonicalGameplayAdmissionDecisionStatus { + CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_UNSPECIFIED = 0; + CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_PROVISIONAL = 1; +} + +enum CanonicalGameplayAdmissionOriginKind { + CANONICAL_GAMEPLAY_ADMISSION_ORIGIN_KIND_UNSPECIFIED = 0; + CANONICAL_GAMEPLAY_ADMISSION_ORIGIN_KIND_NO_PRIOR_POINTER = 1; + CANONICAL_GAMEPLAY_ADMISSION_ORIGIN_KIND_EXPECT_CLOSED = 2; +} + +enum CanonicalGameplayAdmissionOwnerProofOutcome { + CANONICAL_GAMEPLAY_ADMISSION_OWNER_PROOF_OUTCOME_UNSPECIFIED = 0; + CANONICAL_GAMEPLAY_ADMISSION_OWNER_PROOF_OUTCOME_PENDING = 1; + CANONICAL_GAMEPLAY_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED = 2; + CANONICAL_GAMEPLAY_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED = 3; +} + +// The response repeats the exact original lease and complete stored owner values. Counters and +// arbitrary-precision generations use canonical positive decimal strings; private positive row +// identifiers retain int64 representation. The manual client and handler cap this full message at +// 256 KiB without changing global gRPC limits. +message GetCanonicalGameplayAdmissionDecisionResponse { + repeated uint32 schema_version = 1; + repeated string binding_decision_uuid = 2; + repeated bytes original_lease_evidence_utf8 = 3; + repeated CanonicalGameplayAdmissionDecisionStatus status = 4; + repeated string binding_generation = 5; + repeated string expected_old_binding_generation = 6; + repeated string resume_episode_uuid = 7; + repeated CanonicalGameplayAdmissionCandidate candidate = 8; + repeated CanonicalPlayableTargetEvidence target_evidence = 9; +} + +// Complete CanonicalGameplayBindingIdentity, including exact Account issuer partition evidence. +message CanonicalGameplayAdmissionCandidate { + repeated string account_uuid = 1; + repeated string tenant_uuid = 2; + repeated string playable_state_namespace_uuid = 3; + repeated string character_uuid = 4; + repeated string playable_state_scope = 5; + repeated string game_instance_uuid = 6; + repeated int64 runtime_game_instance_id = 7; + repeated string session_uuid = 8; + repeated string region_uuid = 9; + repeated string region_epoch = 10; + repeated string issuer_id = 11; + repeated string issuer_auth_generation = 12; + repeated string issuer_index_layout_version = 13; + repeated string issuer_index_partition_count = 14; + repeated string issuer_index_partition_capacity = 15; +} + +// Complete existing CanonicalPlayableTarget. Nullable expectedPriorPointerVersion is represented +// by zero or one repeated values; every other field must occur exactly once. +message CanonicalPlayableTargetEvidence { + repeated string target_namespace = 1; + repeated string tenant_slug = 2; + repeated string canonical_tenant_uuid = 3; + repeated string world_slug = 4; + repeated string world_display_name = 5; + repeated string realm_uuid = 6; + repeated string realm_slug = 7; + repeated string realm_display_name = 8; + repeated int64 game_session_tenant_id = 9; + repeated int64 game_instance_id = 10; + repeated string playable_state_namespace_uuid = 11; + repeated string playable_state_scope = 12; + repeated string canonical_game_instance_uuid = 13; + repeated string canonical_version_uuid = 14; + repeated int64 runtime_version_id = 15; + repeated string catalog_revision = 16; + repeated string pointer_version = 17; + repeated string admission_pointer_snapshot_digest = 18; + repeated string active_world_epoch = 19; + repeated string initial_admission_request_id = 20; + repeated string initial_admission_request_digest = 21; + repeated CanonicalGameplayAdmissionOriginKind initial_admission_origin_kind = 22; + repeated string expected_prior_pointer_version = 23; + repeated string hold_uuid = 24; + repeated string hold_fence_uuid = 25; + repeated string hold_binding_digest = 26; + repeated int64 audit_event_id = 27; + repeated string owner_proof_digest = 28; + repeated CanonicalGameplayAdmissionOwnerProofOutcome owner_proof_outcome = 29; + repeated bool positive_durable_abort = 30; + repeated string owner_proof_terminal_at = 31; + repeated string character_creation_policy = 32; +} + +// Complete current GS target and the existing full source response (owner proof, launch/source, +// complete published policy set). The existing source response remains independently validated +// by CanonicalGameplayRosterOwnerReadGrpcCodec. Total bound is below 4 MiB and includes target +// protobuf headroom; the Account client applies it only to this RPC. +message GetPublishedRealmAdmissionOwnerReadResponse { + repeated uint32 schema_version = 1; + repeated GetCanonicalGameplayRosterOwnerReadResponse published_source = 2; + repeated CanonicalPlayableTargetEvidence current_target = 3; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java new file mode 100644 index 0000000000..d5841ce38d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClient.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.accountservice.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Evidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionReadServiceGrpc; + +/** Explicit, manually composed Account mTLS client for Game Session's provisional decision read. */ +public final class CanonicalGameplayAdmissionDecisionReadClient + extends AbstractReloadingBlockingGrpcClient< + CanonicalGameplayAdmissionDecisionReadServiceGrpc + .CanonicalGameplayAdmissionDecisionReadServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final long PUBLISHED_REALM_READ_DEADLINE_SECONDS = 15L; + private final String workloadNamespace; + + public CanonicalGameplayAdmissionDecisionReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties, "Canonical gameplay admission decision read"), + channelFactory, + CanonicalGameplayAdmissionDecisionReadClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning Account service explicitly composes this client. */ + public void init() throws SSLException, IOException { + requireNoAmbientSql( + "Gameplay admission decision client initialization requires no ambient SQL transaction"); + initOnce( + "Gameplay admission decision client is closed", + "Gameplay admission decision client is not initialized"); + } + + /** Returns only a closed typed response from the exact same-namespace Game Session peer. */ + public Evidence read( + UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence) { + requireNoAmbientSql("Gameplay admission decision read requires no ambient Account transaction"); + if (SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService()) { + throw new IllegalStateException( + "Gameplay admission decision read requires a workload-only caller context"); + } + Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); + Objects.requireNonNull(expectedLeaseEvidence, "expectedLeaseEvidence"); + if (!workloadNamespace.equals(expectedLeaseEvidence.carrier().get("targetNamespace"))) { + throw new IllegalArgumentException( + "Gameplay admission decision read must use the configured workload namespace"); + } + + var wireRequest = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toRequest( + bindingDecisionId, expectedLeaseEvidence); + RequestEvidence expected = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(wireRequest); + var response = + requireInitializedStub("Gameplay admission decision client is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCanonicalGameplayAdmissionDecision(wireRequest); + try { + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromResponse(expected, response); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Game Session returned invalid canonical gameplay admission evidence", malformed); + } + } + + /** + * Reads the current published route and complete sealed source before Account lease allocation. + * Selector account identity and expected counters are correlation only, never authorization. + */ + public PublishedRealmEvidence readPublishedRealmAdmissionOwner( + CanonicalGameplayRosterOwnerReadEvidence.Request selector) { + requireNoAmbientSql("Published realm owner read requires no ambient Account transaction"); + if (SessionContext.hasAuthenticatedCallerContext() || SessionContext.isInternalService()) { + throw new IllegalStateException( + "Published realm owner read requires a workload-only caller context"); + } + Objects.requireNonNull(selector, "selector"); + if (!workloadNamespace.equals(selector.targetNamespace())) { + throw new IllegalArgumentException( + "Published realm owner read must use the configured workload namespace"); + } + + var wireRequest = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(selector); + var expected = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(wireRequest); + var response = + requireInitializedStub("Gameplay admission decision client is not initialized") + .withMaxInboundMessageSize( + CanonicalGameplayAdmissionDecisionReadGrpcCodec + .MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES) + .withDeadlineAfter(PUBLISHED_REALM_READ_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getPublishedRealmAdmissionOwnerRead(wireRequest); + try { + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + expected, response); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Game Session returned invalid published realm owner evidence", malformed); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected CanonicalGameplayAdmissionDecisionReadServiceGrpc + .CanonicalGameplayAdmissionDecisionReadServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + return CanonicalGameplayAdmissionDecisionReadServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java new file mode 100644 index 0000000000..dcf7055cfb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java @@ -0,0 +1,505 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.sql.Connection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.TenantBillingCutoff; +import net.firedevops.firemud.common.account.authority.RuntimeMembershipAuthorityEvidenceValidator.Snapshot; +import net.firedevops.firemud.common.account.authority.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account-local current-source composition for canonical public-production NEW + * admission. + * + *

The caller enlists the exact supplied DSLContext in its writable SERIALIZABLE transaction. + * This component creates no transaction, performs no writes or network calls, and owns no lease. It + * reads current Account membership, tenant entitlement, and the active SQL token fence under the + * canonical Account-first lock order. The caller verifier remains responsible for JWT/JWKS and + * exact Redis currentness outside SQL; this source cannot re-prove either remote registry state or + * a published gameplay target. + * + *

The returned membership snapshot is complete current Account evidence. The Current result can + * produce the five unchanged Account source subtrees for a lease and compare them against an + * original lease; it never creates, renews, or rewrites that lease. + * + *

Exact non-admitting recovery uses a separately named caller-only read. That path retains the + * global issuer/account authority and ACTIVE token checks but deliberately does not require the + * original tenant membership or entitlement baseline to remain unchanged. + */ +final class AccountGameplayAdmissionCurrentSources { + private static final String ACCOUNT_ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Set LEASE_SOURCE_FIELDS = + Set.of( + "authorityTuple", + "issuanceFence", + "membershipBaseline", + "outboxCheckpoints", + "tokenIdentityEvidence"); + + private final DSLContext dsl; + private final AccountCanonicalRuntimeMembershipSnapshotRepository membershipSnapshots; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + private final AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox; + private final AccountGameplayDelegationIssuanceRepository issuance; + + private AccountGameplayAdmissionCurrentSources( + DSLContext dsl, + AccountCanonicalRuntimeMembershipSnapshotRepository membershipSnapshots, + AccountTenantAuthorityEventRepository tenantAuthorityEvents, + AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox, + AccountGameplayDelegationIssuanceRepository issuance) { + this.dsl = Objects.requireNonNull(dsl); + this.membershipSnapshots = Objects.requireNonNull(membershipSnapshots); + this.tenantAuthorityEvents = Objects.requireNonNull(tenantAuthorityEvents); + this.tenantEntitlementOutbox = Objects.requireNonNull(tenantEntitlementOutbox); + this.issuance = Objects.requireNonNull(issuance); + } + + /** + * Builds the concrete read graph over one exact caller-enlisted DSLContext. + * + *

The workload namespace is passed only to Account's existing fresh-tenant source reader; it + * is not interpreted as a caller or gameplay authority. + */ + static AccountGameplayAdmissionCurrentSources bind( + DSLContext exactDsl, String configuredWorkloadNamespace) { + Objects.requireNonNull(exactDsl, "The caller-enlisted DSLContext is required"); + if (!GrpcPeerIdentity.isValidNamespace(configuredWorkloadNamespace)) { + throw new IllegalArgumentException("Configured Account workload namespace is invalid"); + } + + AccountAuthorityGenerationRepository generations = + new AccountAuthorityGenerationRepository(exactDsl); + AccountAuthorityOutboxRepository authorityOutbox = + new AccountAuthorityOutboxRepository(exactDsl); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(exactDsl, generations, authorityOutbox); + FreshTenantIdentityAssociationRepository freshTenants = + new FreshTenantIdentityAssociationRepository(exactDsl, configuredWorkloadNamespace); + AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox = + new AccountTenantEntitlementOutboxRepository(exactDsl); + AccountTenantAuthorityEventRepository tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + exactDsl, authorityOutbox, tenantEntitlementOutbox, freshTenants, generations); + AccountRepository accounts = new AccountRepository(exactDsl, sourceEvidence); + AccountMembershipPairAuthorityRepository membershipPairs = + new AccountMembershipPairAuthorityRepository(exactDsl); + AccountTenantMembershipRepository memberships = + new AccountTenantMembershipRepository(exactDsl, accounts, freshTenants, membershipPairs); + AccountTenantMembershipRoleSnapshotRepository membershipRoles = + new AccountTenantMembershipRoleSnapshotRepository(exactDsl); + AccountCanonicalRuntimeMembershipSnapshotRepository membershipSnapshots = + new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, + generations, + sourceEvidence, + tenantAuthorityEvents, + freshTenants, + memberships, + membershipPairs, + membershipRoles, + authorityOutbox); + AccountAuthEvidenceBundleRepository evidenceBundles = + new AccountAuthEvidenceBundleRepository(exactDsl, generations, authorityOutbox); + AccountGameplayDelegationIssuanceRepository issuance = + new AccountGameplayDelegationIssuanceRepository(exactDsl, sourceEvidence, evidenceBundles); + + return new AccountGameplayAdmissionCurrentSources( + exactDsl, membershipSnapshots, tenantAuthorityEvents, tenantEntitlementOutbox, issuance); + } + + /** + * Captures current Account-owned sources for one authenticated original token and exact tenant. + * + *

{@code expectedCommittedCandidate} is used only as the verified caller's correlation value: + * its Account and JTI select current owner reads, and every immutable candidate field is compared + * with the independent in-transaction SQL readback before it is returned. + */ + Current readCurrentPublicProductionNew( + UUID targetTenantId, + UUID expectedOriginalTokenJti, + CommittedCandidateVerificationData expectedCommittedCandidate) { + Objects.requireNonNull(expectedCommittedCandidate, "Verified caller candidate is required"); + requireNonNilUuid(targetTenantId, "Canonical target tenant UUID"); + requireV4Uuid(expectedOriginalTokenJti, "Expected original token JTI"); + + var expectedIdentity = expectedCommittedCandidate.identity(); + UUID accountId = expectedIdentity.accountId(); + requireNonNilUuid(accountId, "Verified caller Account UUID"); + if (!expectedOriginalTokenJti.equals(expectedIdentity.tokenJti()) + || !accountId.equals(expectedCommittedCandidate.authoritySnapshot().accountId())) { + throw unavailable(); + } + + requireWritableSerializableAccountTransaction(); + lockExactAccountFirst(accountId); + + Snapshot snapshot = membershipSnapshots.readCurrent(accountId, targetTenantId); + TenantAuthorityEventV1Codec.Event authorityEvent = + tenantAuthorityEvents.readCurrentByTenant(targetTenantId); + DemoTenantEntitlementEventV1Codec.Event typedTenantEvent = + readExactCurrentTenantEntitlement(targetTenantId, authorityEvent); + + requireCurrentActiveMembership(snapshot, accountId, targetTenantId); + requireSupportedPublicTenantTuple(snapshot, targetTenantId, authorityEvent, typedTenantEvent); + if (!typedTenantEvent.gameplayAvailable() || !typedTenantEvent.allowNewGameplayBindings()) { + throw unavailable(); + } + + CommittedCandidateVerificationData currentCommittedCandidate = + issuance + .readCurrentCommittedCandidateByJti(expectedOriginalTokenJti) + .orElseThrow(AccountGameplayAdmissionCurrentSources::unavailable); + if (!CommittedCandidateVerificationData.hasSameOwnerEvidence( + expectedCommittedCandidate, currentCommittedCandidate)) { + throw unavailable(); + } + requireCandidateAuthorityMatchesSnapshot(currentCommittedCandidate, snapshot, accountId); + + return new Current(snapshot, typedTenantEvent, currentCommittedCandidate); + } + + /** + * Revalidates only the current authenticated Account caller for non-admitting exact recovery. + * + *

This intentionally omits tenant membership and entitlement reads: a retained lease read or + * orphan-cleanup transition does not create a new binding. It still locks Account first and + * independently resolves the exact current committed issuance, global/account authority, + * immutable commit proof, and ACTIVE SQL token fence on this caller-enlisted transaction. + */ + void requireCurrentAuthenticatedCallerOnly( + CommittedCandidateVerificationData expectedCommittedCandidate) { + Objects.requireNonNull(expectedCommittedCandidate, "Verified caller candidate is required"); + var expectedIdentity = expectedCommittedCandidate.identity(); + UUID accountId = expectedIdentity.accountId(); + UUID tokenJti = expectedIdentity.tokenJti(); + requireNonNilUuid(accountId, "Verified caller Account UUID"); + requireV4Uuid(tokenJti, "Verified caller token JTI"); + requireWritableSerializableAccountTransaction(); + + // The verifier's private candidate supplies only the account lock and JTI lookup selectors. + // The issuance owner independently reads and compares every immutable owner value below. + lockExactAccountFirst(accountId); + CommittedCandidateVerificationData currentCommittedCandidate = + issuance + .readCurrentCommittedCandidateByJti(tokenJti) + .orElseThrow(AccountGameplayAdmissionCurrentSources::unavailable); + if (!CommittedCandidateVerificationData.hasSameOwnerEvidence( + expectedCommittedCandidate, currentCommittedCandidate) + || !accountId.equals(currentCommittedCandidate.identity().accountId()) + || !tokenJti.equals(currentCommittedCandidate.identity().tokenJti())) { + throw unavailable(); + } + } + + private DemoTenantEntitlementEventV1Codec.Event readExactCurrentTenantEntitlement( + UUID tenantId, TenantAuthorityEventV1Codec.Event authorityEvent) { + DemoTenantEntitlementEventV1Codec.Event entitlement = + tenantEntitlementOutbox + .readEvent(tenantId, authorityEvent.tenantBillingSequence()) + .orElseThrow(AccountGameplayAdmissionCurrentSources::unavailable); + if (!tenantId.equals(authorityEvent.tenantId()) + || !tenantId.equals(entitlement.canonicalTenantId()) + || !authorityEvent.requestId().equals(entitlement.requestId()) + || !authorityEvent.requestDigest().equals(entitlement.requestDigest()) + || authorityEvent.tenantBillingSequence() != entitlement.tenantBillingSequence() + || !authorityEvent.tenantBillingStreamKey().equals(entitlement.outboxStreamKey()) + || !authorityEvent.tenantBillingEventId().equals(entitlement.eventId()) + || !authorityEvent.tenantBillingEventDigest().equals(entitlement.eventDigest()) + || authorityEvent.tenantAuthorityGeneration() != entitlement.tenantAuthorityGeneration() + || authorityEvent.tenantAuthoritySourceVersion() + != entitlement.tenantAuthoritySourceVersion() + || !authorityEvent.sourceEvidence().equals(entitlement.sourceEvidence())) { + throw unavailable(); + } + return entitlement; + } + + private static void requireCurrentActiveMembership( + Snapshot snapshot, UUID accountId, UUID tenantId) { + if (!ACCOUNT_ISSUER.equals(snapshot.issuerId()) + || !accountId.toString().equals(snapshot.accountId()) + || !tenantId.toString().equals(snapshot.tenantId()) + || !snapshot.membershipExists() + || !"ACTIVE".equals(snapshot.membershipLifecycleState()) + || !snapshot.gameplayAdmissionAllowed()) { + throw unavailable(); + } + } + + private static Map currentLeaseSourceFields( + Snapshot snapshot, CommittedCandidateVerificationData currentCommittedCandidate) { + Map membershipBaseline = + Map.of( + "membershipLifecycleState", snapshot.membershipLifecycleState(), + "membershipVersion", snapshot.membershipVersion(), + "membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration()); + List> outboxCheckpoints = + snapshot.checkpoints().stream() + .map( + checkpoint -> + Map.of( + "outboxStreamKey", + checkpoint.outboxStreamKey(), + "outboxSequence", + checkpoint.outboxSequence())) + .toList(); + + return Map.of( + "authorityTuple", currentAuthorityTuple(snapshot), + "issuanceFence", snapshot.issuanceFence(), + "membershipBaseline", membershipBaseline, + "outboxCheckpoints", outboxCheckpoints, + "tokenIdentityEvidence", currentTokenIdentityEvidence(snapshot, currentCommittedCandidate)); + } + + private static Map currentAuthorityTuple(Snapshot snapshot) { + AuthorityTuple current = snapshot.authorityTuple(); + Optional accountCutoff = + current + .accountSecurityCutoff() + .map( + cutoff -> + new AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); + Map authorityTuple = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple( + Long.parseLong(current.issuerAuthGeneration()), + Long.parseLong(current.accountAuthorityGeneration()), + accountCutoff)); + authorityTuple.put("tenantAuthorityGeneration", current.tenantAuthorityGeneration()); + authorityTuple.put("membershipAuthorityGeneration", current.membershipAuthorityGeneration()); + authorityTuple.put("privateRealmGrantVersions", current.privateRealmGrantVersions()); + current + .tenantBillingCutoff() + .ifPresent( + cutoffs -> + authorityTuple.put("tenantBillingCutoff", currentTenantBillingCutoff(cutoffs))); + return Map.copyOf(authorityTuple); + } + + private static Map currentTenantBillingCutoff( + Map currentCutoffs) { + Map cutoffs = new LinkedHashMap<>(); + currentCutoffs.forEach( + (tenantId, cutoff) -> + cutoffs.put( + tenantId, + Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + return Map.copyOf(cutoffs); + } + + private static Map currentTokenIdentityEvidence( + Snapshot snapshot, CommittedCandidateVerificationData currentCommittedCandidate) { + var identity = currentCommittedCandidate.identity(); + return Map.ofEntries( + Map.entry("accountId", identity.accountId().toString()), + Map.entry("operationId", identity.operationId().toString()), + Map.entry("issuanceRequestId", identity.requestId().toString()), + Map.entry("tokenJti", identity.tokenJti().toString()), + Map.entry("tokenSHA256", currentCommittedCandidate.tokenSha256()), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", snapshot.issuanceFence()), + // The SQL candidate reader returns only after requiring the exact ACTIVE fence at 1. + Map.entry("tokenIdentityFence", "1"), + Map.entry("tokenProfile", GameSessionAccountDelegationProfile.PROFILE), + Map.entry("issuedAt", Long.toString(identity.issuedAtEpochSecond())), + Map.entry("notBefore", Long.toString(identity.notBeforeEpochSecond())), + Map.entry("expiresAt", Long.toString(identity.expiresAtEpochSecond()))); + } + + private static void requireSupportedPublicTenantTuple( + Snapshot snapshot, + UUID tenantId, + TenantAuthorityEventV1Codec.Event authorityEvent, + DemoTenantEntitlementEventV1Codec.Event typedTenantEvent) { + String tenantKey = tenantId.toString(); + AuthorityTuple tuple = snapshot.authorityTuple(); + Map expectedTenantGeneration = + Map.of(tenantKey, Long.toString(authorityEvent.tenantAuthorityGeneration())); + Map expectedMembershipGeneration = + Map.of(tenantKey, snapshot.membershipAuthorityGeneration()); + TenantBillingCutoff expectedBillingCutoff = + new TenantBillingCutoff( + Long.toString(authorityEvent.tenantAuthorityGeneration()), + Long.toString(typedTenantEvent.tenantBillingSequence()), + authorityEvent.outboxStreamKey(), + Long.toString(authorityEvent.outboxSequence())); + Map expectedBillingCutoffs = + Map.of(tenantKey, expectedBillingCutoff); + String membershipVersion = snapshot.membershipVersion().get(tenantKey); + + boolean tenantCheckpointPresent = + snapshot.checkpoints().stream() + .anyMatch( + checkpoint -> + authorityEvent.outboxStreamKey().equals(checkpoint.outboxStreamKey()) + && Long.toString(authorityEvent.outboxSequence()) + .equals(checkpoint.outboxSequence())); + boolean tenantSourceEventPresent = + snapshot.sourceEvidence().stream() + .anyMatch( + evidence -> + authorityEvent.outboxStreamKey().equals(evidence.outboxStreamKey()) + && Long.toString(authorityEvent.outboxSequence()) + .equals(evidence.outboxSequence()) + && authorityEvent.eventId().toString().equals(evidence.eventId()) + && authorityEvent.eventDigest().equals(evidence.eventDigest())); + + if (snapshot.membershipVersion().size() != 1 + || !snapshot.membershipVersion().keySet().equals(Set.of(tenantKey)) + || !isPositiveDecimal(membershipVersion) + || !isPositiveDecimal(snapshot.membershipAuthorityGeneration()) + || !isPositiveDecimal(snapshot.issuanceFence()) + || !isPositiveDecimal(tuple.issuerAuthGeneration()) + || !isPositiveDecimal(tuple.accountAuthorityGeneration()) + || !tuple.tenantAuthorityGeneration().equals(expectedTenantGeneration) + || !tuple.membershipAuthorityGeneration().equals(expectedMembershipGeneration) + || !tuple.privateRealmGrantVersions().isEmpty() + || tuple.tenantBillingCutoff().isEmpty() + || !tuple.tenantBillingCutoff().orElseThrow().equals(expectedBillingCutoffs) + || !tenantCheckpointPresent + || !tenantSourceEventPresent) { + throw unavailable(); + } + } + + private static void requireCandidateAuthorityMatchesSnapshot( + CommittedCandidateVerificationData candidate, Snapshot snapshot, UUID accountId) { + var authority = candidate.authoritySnapshot(); + AuthorityTuple tuple = snapshot.authorityTuple(); + if (!accountId.equals(authority.accountId()) + || !Long.toString(authority.issuerGeneration()).equals(tuple.issuerAuthGeneration()) + || !Long.toString(authority.accountGeneration()).equals(tuple.accountAuthorityGeneration()) + || !Long.toString(authority.issuanceFence()).equals(snapshot.issuanceFence()) + || !sameAccountSecurityCutoff( + authority.accountSecurityCutoff(), tuple.accountSecurityCutoff())) { + throw unavailable(); + } + } + + private static boolean sameAccountSecurityCutoff( + Optional issuanceCutoff, + Optional membershipCutoff) { + if (issuanceCutoff.isEmpty() || membershipCutoff.isEmpty()) { + return issuanceCutoff.isEmpty() && membershipCutoff.isEmpty(); + } + AccountSecurityCutoff left = issuanceCutoff.orElseThrow(); + MembershipAuthorityEventV1Codec.AccountSecurityCutoff right = membershipCutoff.orElseThrow(); + return left.accountAuthorityGeneration().equals(right.accountAuthorityGeneration()) + && left.outboxStreamKey().equals(right.outboxStreamKey()) + && left.outboxSequence().equals(right.outboxSequence()); + } + + private void requireWritableSerializableAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw unavailable(); + } + Integer declaredIsolation = + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(); + if (!Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE).equals(declaredIsolation)) { + throw unavailable(); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { + throw unavailable(); + } + }); + } + + private void lockExactAccountFirst(UUID accountId) { + Record locked = + dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", accountId); + if (locked == null || !accountId.equals(locked.get("account_uuid", UUID.class))) { + throw unavailable(); + } + } + + private static void requireNonNilUuid(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private static void requireV4Uuid(UUID value, String label) { + requireNonNilUuid(value, label); + if (value.version() != 4 || value.variant() != 2) { + throw new IllegalArgumentException(label + " must be a canonical UUIDv4"); + } + } + + private static boolean isPositiveDecimal(String value) { + return value != null && value.matches("[1-9][0-9]*"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account gameplay admission current sources are unavailable"); + } + + /** Complete, immutable source result; it contains neither a JWT nor registry bytes. */ + record Current( + Snapshot snapshot, + DemoTenantEntitlementEventV1Codec.Event typedTenantEvent, + CommittedCandidateVerificationData currentCommittedCandidate) { + Current { + Objects.requireNonNull(snapshot); + Objects.requireNonNull(typedTenantEvent); + Objects.requireNonNull(currentCommittedCandidate); + } + + /** Returns exactly the five immutable, current-source subtrees used by lease capture. */ + Map leaseSourceFields() { + return currentLeaseSourceFields(snapshot, currentCommittedCandidate); + } + + /** Exact-compares current source evidence with an original NEW lease without rewriting it. */ + void requireMatchesOriginalLease(AccountGameplayAdmissionLeaseEvidence originalLease) { + if (originalLease == null + || originalLease.leaseKind() + != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) { + throw unavailable(); + } + Map carrier = originalLease.carrier(); + Object scopeValue = carrier.get("bindingScope"); + if (!(scopeValue instanceof Map bindingScope) + || !snapshot.accountId().equals(bindingScope.get("accountId")) + || !snapshot.tenantId().equals(bindingScope.get("tenantId"))) { + throw unavailable(); + } + + Map expected = leaseSourceFields(); + for (String field : LEASE_SOURCE_FIELDS) { + if (!Objects.equals(expected.get(field), carrier.get(field))) throw unavailable(); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java new file mode 100644 index 0000000000..40a0f7c37a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java @@ -0,0 +1,896 @@ +package net.firedevops.firemud.accountservice.repository; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.math.BigInteger; +import java.sql.Connection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionOriginalAckReceipt; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseRepository.Allocation; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionOriginalCommitExecutor.OriginalCommitAcknowledgement; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Evidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Account owner for the exact public-production NEW admission operation. + * + *

This class is manually composed. It owns no Spring registration and accepts no caller-supplied + * authority adapter, candidate source, SQL callback, or authentication flag. It composes Account's + * concrete caller verifier and source graph, the exact same-namespace Game Session owner reads, the + * existing lease repository, and the original physical-COMMIT and ACK-receipt executors. + * + *

Responses report only the retained Account operation and, for COMMITTED, a receipt read from + * the separate durable receipt owner. They do not admit a Game Session binding. + */ +public final class AccountGameplayAdmissionLeaseOwner { + private static final String ACCOUNT_ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String GAME_SESSION_SERVICE = "game-session-service"; + + private final DataSource dataSource; + private final AccountGameplayAdmissionCallerVerifier callerVerifier; + private final CanonicalGameplayAdmissionDecisionReadClient decisionReadClient; + private final String workloadNamespace; + private final AccountGameplayAdmissionOriginalCommitExecutor originalCommitExecutor; + private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor receiptExecutor; + + public AccountGameplayAdmissionLeaseOwner( + AccountGameplayAdmissionCallerVerifier callerVerifier, + CanonicalGameplayAdmissionDecisionReadClient decisionReadClient, + String workloadNamespace, + DataSource dataSource) { + this.callerVerifier = + Objects.requireNonNull(callerVerifier, "Account caller verifier required"); + this.decisionReadClient = + Objects.requireNonNull(decisionReadClient, "Canonical Game Session owner client required"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + this.dataSource = Objects.requireNonNull(dataSource, "Account DataSource required"); + originalCommitExecutor = new AccountGameplayAdmissionOriginalCommitExecutor(dataSource); + receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource); + } + + /** Verifies current caller and published target before allocating or returning an operation. */ + public AccountGameplayAdmissionLeaseResponse acquire( + AcquireGameplayAdmissionLeaseRequest wireRequest) { + GrpcPeerIdentity peer = requireGameSessionCaller(); + requireNoAmbientSql(); + final AcquireRequest request; + try { + request = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(wireRequest); + } catch (RuntimeException malformed) { + throw invalidArgument(); + } + + VerifiedCaller caller = verifyCaller(request.presentedInitialGsACompactJwt(), peer); + Candidate expectedCandidate = request.expectedCandidate(); + Target expectedTarget = request.expectedTarget(); + requireCandidateMatchesCaller(expectedCandidate, caller, peer); + requireCandidateMatchesTarget(expectedCandidate, expectedTarget); + requireTargetNamespace(expectedTarget); + + // The independent Game Session read is deliberately complete before opening Account SQL. + PublishedRealmEvidence published = + readPublishedTarget(request.requestId(), expectedCandidate, expectedTarget); + if (!published.currentTarget().equals(expectedTarget)) throw unavailable(); + + AccountGameplayAdmissionLeaseOperation operation = + withCurrentSources( + caller, + expectedTarget.canonicalTenantId(), + current -> { + current.requireCandidate(expectedCandidate, caller, peer); + AccountGameplayAdmissionLeaseRepository repository = current.repository(); + UUID accountId = caller.identity().accountId(); + Allocation priorAllocation = + repository.findAllocation(accountId, request.requestId()).orElse(null); + if (priorAllocation != null) { + AccountGameplayAdmissionLeaseOperation retained = + repository + .findByRequest(accountId, request.requestId(), peer.uri()) + .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); + requireAllocationMatchesOperation(priorAllocation, retained); + current.currentSources().requireMatchesOriginalLease(retained.evidence()); + requireLeaseMatchesCandidateTarget( + retained.evidence(), + request.requestId(), + expectedCandidate, + expectedTarget, + request.bindingGeneration()); + return retained; + } + + Allocation allocation = + repository.allocate(accountId, request.requestId(), UUID.randomUUID()); + AccountGameplayAdmissionLeaseEvidence evidence = + buildOriginalEvidence( + current.dsl(), + allocation, + peer.uri(), + expectedCandidate, + expectedTarget, + request.bindingGeneration(), + current.currentSources().leaseSourceFields(), + caller.identity().expiresAtEpochSecond()); + return repository.beginPending(evidence); + }); + + OriginalAckReceiptEvidence receipt = requireReceiptIfCommitted(operation); + return AccountGameplayAdmissionLeaseGrpcCodec.toAcquireResponse( + request, + operation.evidence(), + wireState(operation.state()), + operation.bindingDecisionId(), + operation.orphanCleanupId(), + receipt); + } + + /** Revalidates the exact original PROVISIONAL decision and current published target. */ + public AccountGameplayAdmissionLeaseResponse finalizeLease( + FinalizeGameplayAdmissionLeaseRequest wireRequest) { + GrpcPeerIdentity peer = requireGameSessionCaller(); + requireNoAmbientSql(); + final AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest request; + try { + request = AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(wireRequest); + } catch (RuntimeException malformed) { + throw invalidArgument(); + } + + AccountGameplayAdmissionLeaseEvidence lease = request.originalLeaseEvidence(); + VerifiedCaller caller = verifyCaller(request.presentedInitialGsACompactJwt(), peer); + requireCallerMatchesLease(caller, peer, lease); + + // Exact retries of a completed original operation can replay only its actual durable receipt. + // Game Session is allowed to have advanced the decision beyond PROVISIONAL after the original + // physical COMMIT, so do this narrowly fenced read before asking for a fresh provisional view. + AccountGameplayAdmissionLeaseOperation retainedBeforeRemoteReads = + readExactForFinalization(caller, lease); + if (retainedBeforeRemoteReads.state() + == AccountGameplayAdmissionLeaseOperation.State.COMMITTED) { + OriginalAckReceiptEvidence receipt = + requireReceipt(retainedBeforeRemoteReads, request.bindingDecisionId()); + return AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeResponse( + request, + retainedBeforeRemoteReads.evidence(), + wireState(retainedBeforeRemoteReads.state()), + retainedBeforeRemoteReads.bindingDecisionId(), + retainedBeforeRemoteReads.orphanCleanupId(), + receipt); + } + if (retainedBeforeRemoteReads.state() == AccountGameplayAdmissionLeaseOperation.State.ABORTED) { + return AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeResponse( + request, + retainedBeforeRemoteReads.evidence(), + wireState(retainedBeforeRemoteReads.state()), + retainedBeforeRemoteReads.bindingDecisionId(), + retainedBeforeRemoteReads.orphanCleanupId(), + null); + } + + // Both remote authorities are read after the short Account replay lookup and before the + // original physical-COMMIT path. The decision reader returns only the actual retained + // lease-bound PROVISIONAL decision, never request echoes. + Evidence decision; + PublishedRealmEvidence published; + try { + decision = decisionReadClient.read(request.bindingDecisionId(), lease); + requireDecisionMatchesLease(decision, request.bindingDecisionId(), lease, caller, peer); + published = + readPublishedTarget(requestId(lease), decision.candidate(), decision.targetEvidence()); + if (!published.currentTarget().equals(decision.targetEvidence())) throw unavailable(); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + + AccountGameplayAdmissionLeaseOperation beforeCommit = readExactForFinalization(caller, lease); + + if (beforeCommit.state() == AccountGameplayAdmissionLeaseOperation.State.COMMITTED) { + OriginalAckReceiptEvidence receipt = + requireReceipt(beforeCommit, request.bindingDecisionId()); + return AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeResponse( + request, + beforeCommit.evidence(), + wireState(beforeCommit.state()), + beforeCommit.bindingDecisionId(), + beforeCommit.orphanCleanupId(), + receipt); + } + if (beforeCommit.state() == AccountGameplayAdmissionLeaseOperation.State.ABORTED) { + return AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeResponse( + request, + beforeCommit.evidence(), + wireState(beforeCommit.state()), + beforeCommit.bindingDecisionId(), + beforeCommit.orphanCleanupId(), + null); + } + + // This is the one original physical Account COMMIT. Retained COMMITTED state is never passed + // through this executor to reconstruct a late acknowledgement. + OriginalCommitAcknowledgement acknowledgement; + try { + acknowledgement = + originalCommitExecutor.executeWithCurrentSources( + lease, request.bindingDecisionId(), workloadNamespace, caller.currentCandidate()); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + AccountGameplayAdmissionOriginalAckReceipt receipt; + try { + receipt = receiptExecutor.confirm(acknowledgement); + } catch (RuntimeException unavailable) { + // The original COMMITTED row, if present, is intentionally left for exact recovery. This + // call never rebuilds its timing acknowledgement or fabricates an ACK receipt. + throw unavailable(); + } + requireReceiptOperation(receipt, lease, request.bindingDecisionId()); + return AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeResponse( + request, + receipt.operation().evidence(), + wireState(receipt.operation().state()), + receipt.operation().bindingDecisionId(), + receipt.operation().orphanCleanupId(), + receiptEvidence(receipt)); + } + + /** Reads only the exact retained operation after fresh caller and Account-source checks. */ + public AccountGameplayAdmissionLeaseResponse read(ReadGameplayAdmissionLeaseRequest wireRequest) { + GrpcPeerIdentity peer = requireGameSessionCaller(); + requireNoAmbientSql(); + final AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest request; + try { + request = AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(wireRequest); + } catch (RuntimeException malformed) { + throw invalidArgument(); + } + + AccountGameplayAdmissionLeaseEvidence lease = request.originalLeaseEvidence(); + VerifiedCaller caller = verifyCaller(request.presentedInitialGsACompactJwt(), peer); + requireCallerMatchesLease(caller, peer, lease); + AccountGameplayAdmissionLeaseOperation operation = + readExactWithCurrentCallerOnly(caller, lease); + OriginalAckReceiptEvidence receipt = requireReceiptIfCommitted(operation); + return AccountGameplayAdmissionLeaseGrpcCodec.toReadResponse( + request, + operation.evidence(), + wireState(operation.state()), + operation.bindingDecisionId(), + operation.orphanCleanupId(), + receipt); + } + + /** + * Records an exact ABORTED operation with its durable orphan-cleanup identity. + * + *

An omitted decision identity remains unknown. If one is supplied for a pending operation, it + * must first resolve to the real lease-bound PROVISIONAL Game Session decision. This method does + * not delete Game Session state or claim token retirement, registry removal, or cleanup delivery; + * those remain separately fenced owner obligations. + */ + public AccountGameplayAdmissionLeaseResponse abort( + AbortGameplayAdmissionLeaseRequest wireRequest) { + GrpcPeerIdentity peer = requireGameSessionCaller(); + requireNoAmbientSql(); + final AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest request; + try { + request = AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(wireRequest); + } catch (RuntimeException malformed) { + throw invalidArgument(); + } + + AccountGameplayAdmissionLeaseEvidence lease = request.originalLeaseEvidence(); + VerifiedCaller caller = verifyCaller(request.presentedInitialGsACompactJwt(), peer); + requireCallerMatchesLease(caller, peer, lease); + + AccountGameplayAdmissionLeaseOperation initial = readExactWithCurrentCallerOnly(caller, lease); + + if (initial.state() == AccountGameplayAdmissionLeaseOperation.State.COMMITTED) { + requireAbortDecisionMatches(request.bindingDecisionId(), initial); + OriginalAckReceiptEvidence receipt = requireReceiptIfCommitted(initial); + return AccountGameplayAdmissionLeaseGrpcCodec.toAbortResponse( + request, + initial.evidence(), + wireState(initial.state()), + initial.bindingDecisionId(), + initial.orphanCleanupId(), + receipt); + } + if (initial.state() == AccountGameplayAdmissionLeaseOperation.State.ABORTED) { + requireAbortDecisionMatches(request.bindingDecisionId(), initial); + return AccountGameplayAdmissionLeaseGrpcCodec.toAbortResponse( + request, + initial.evidence(), + wireState(initial.state()), + initial.bindingDecisionId(), + initial.orphanCleanupId(), + null); + } + + UUID decisionId = request.bindingDecisionId(); + if (decisionId != null) { + // A supplied decision is verified outside SQL. No response or timeout is interpreted as + // authoritative NO_TOKEN or as permission to clear a candidate. + try { + Evidence decision = decisionReadClient.read(decisionId, lease); + requireDecisionMatchesLease(decision, decisionId, lease, caller, peer); + } catch (RuntimeException unknown) { + throw unavailable(); + } + } + + AccountGameplayAdmissionLeaseOperation aborted = + abortExactWithCurrentCallerOnly(caller, lease, decisionId); + + OriginalAckReceiptEvidence receipt = requireReceiptIfCommitted(aborted); + return AccountGameplayAdmissionLeaseGrpcCodec.toAbortResponse( + request, + aborted.evidence(), + wireState(aborted.state()), + aborted.bindingDecisionId(), + aborted.orphanCleanupId(), + receipt); + } + + private PublishedRealmEvidence readPublishedTarget( + UUID requestId, Candidate candidate, Target target) { + requireTargetNamespace(target); + CanonicalGameplayRosterOwnerReadEvidence.Request selector = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + requestId, + candidate.accountId(), + workloadNamespace, + target.canonicalTenantId(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch()); + PublishedRealmEvidence published; + try { + published = decisionReadClient.readPublishedRealmAdmissionOwner(selector); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + if (!selector.equals(published.selector())) throw unavailable(); + return published; + } + + private void requireTargetNamespace(Target target) { + if (!workloadNamespace.equals(target.targetNamespace())) throw unavailable(); + } + + private static void requireCandidateMatchesTarget(Candidate candidate, Target target) { + if (!candidate.tenantId().equals(target.canonicalTenantId()) + || !candidate.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !candidate.playableStateScope().equals(target.playableStateScope()) + || !candidate.gameInstanceId().equals(target.canonicalGameInstanceId()) + || candidate.runtimeGameInstanceId() != target.gameInstanceId()) { + throw unavailable(); + } + } + + private static void requireCandidateMatchesCaller( + Candidate candidate, VerifiedCaller caller, GrpcPeerIdentity peer) { + var identity = caller.identity(); + var authority = caller.currentCandidate().authoritySnapshot(); + if (!candidate.accountId().equals(identity.accountId()) + || !identity.accountId().equals(authority.accountId()) + || !ACCOUNT_ISSUER.equals(candidate.issuerId()) + || !BigInteger.valueOf(authority.issuerGeneration()) + .equals(candidate.issuerAuthGeneration()) + || !peer.uri().equals(identity.callerWorkload())) { + throw unavailable(); + } + } + + private void requireCallerMatchesLease( + VerifiedCaller caller, GrpcPeerIdentity peer, AccountGameplayAdmissionLeaseEvidence lease) { + if (lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || !workloadNamespace.equals(lease.carrier().get("targetNamespace")) + || !peer.uri().equals(lease.carrier().get("callerWorkload")) + || !peer.uri().equals(caller.identity().callerWorkload())) { + throw unavailable(); + } + Map scope = object(lease.carrier().get("bindingScope")); + Map token = object(lease.carrier().get("tokenIdentityEvidence")); + if (!caller.identity().accountId().toString().equals(scope.get("accountId")) + || !caller.identity().accountId().toString().equals(token.get("accountId")) + || !caller.identity().tokenJti().toString().equals(token.get("tokenJti")) + || !caller.currentCandidate().tokenSha256().equals(token.get("tokenSHA256")) + || !GameSessionAccountDelegationProfile.PROFILE.equals(token.get("tokenProfile")) + || !"1".equals(token.get("tokenIdentityFence"))) { + throw unavailable(); + } + } + + private static void requireDecisionMatchesLease( + Evidence decision, + UUID requestedDecisionId, + AccountGameplayAdmissionLeaseEvidence lease, + VerifiedCaller caller, + GrpcPeerIdentity peer) { + if (!requestedDecisionId.equals(decision.bindingDecisionId()) + || decision.status() != CanonicalGameplayAdmissionDecisionReadGrpcCodec.Status.PROVISIONAL + || !decision.leaseEvidence().hasSameIdentity(lease)) { + throw unavailable(); + } + requireCandidateMatchesCaller(decision.candidate(), caller, peer); + requireCandidateMatchesTarget(decision.candidate(), decision.targetEvidence()); + requireCandidateMatchesLease(decision.candidate(), lease); + requireTargetMatchesLease(decision.targetEvidence(), lease); + } + + private static void requireCandidateMatchesLease( + Candidate candidate, AccountGameplayAdmissionLeaseEvidence lease) { + Map scope = object(lease.carrier().get("bindingScope")); + Map authority = object(lease.carrier().get("authorityTuple")); + if (!candidate.accountId().toString().equals(scope.get("accountId")) + || !candidate.tenantId().toString().equals(scope.get("tenantId")) + || !candidate + .playableStateNamespaceId() + .toString() + .equals(scope.get("playableStateNamespaceId")) + || !candidate.playableStateScope().equals(scope.get("playableStateScope")) + || !candidate.gameInstanceId().toString().equals(scope.get("gameInstanceId")) + || !candidate.characterId().toString().equals(scope.get("characterId")) + || !candidate.sessionId().toString().equals(scope.get("sessionId")) + || !candidate.regionId().toString().equals(scope.get("regionId")) + || !candidate.regionEpoch().toString().equals(scope.get("regionEpoch")) + || !candidate + .issuerAuthGeneration() + .toString() + .equals(authority.get("issuerAuthGeneration")) + || !candidate.issuerId().equals(ACCOUNT_ISSUER)) { + throw unavailable(); + } + } + + private static void requireTargetMatchesLease( + Target target, AccountGameplayAdmissionLeaseEvidence lease) { + // Account's closed lease pins the canonical realm/catalog/pointer reference. Game Session's + // fresh published-owner read resolves that reference to the complete immutable pointer, + // catalog and committed OPEN proof (including active epoch and proof fields); the owner then + // exact-compares that full result with the original PROVISIONAL decision. + Map scope = object(lease.carrier().get("bindingScope")); + if (!target.targetNamespace().equals(lease.carrier().get("targetNamespace")) + || !target.canonicalTenantId().toString().equals(scope.get("tenantId")) + || !target.realmId().toString().equals(scope.get("realmId")) + || !target.worldSlug().equals(scope.get("worldSlug")) + || !target.realmSlug().equals(scope.get("realmSlug")) + || !target + .playableStateNamespaceId() + .toString() + .equals(scope.get("playableStateNamespaceId")) + || !target.playableStateScope().equals(scope.get("playableStateScope")) + || !target.canonicalGameInstanceId().toString().equals(scope.get("gameInstanceId")) + || !Long.toString(target.catalogRevision()).equals(scope.get("catalogRevision")) + || !Long.toString(target.pointerVersion()).equals(scope.get("pointerVersion"))) { + throw unavailable(); + } + } + + private static void requireLeaseMatchesCandidateTarget( + AccountGameplayAdmissionLeaseEvidence lease, + UUID expectedRequestId, + Candidate candidate, + Target target, + BigInteger bindingGeneration) { + Map scope = object(lease.carrier().get("bindingScope")); + if (!expectedRequestId.equals(UUID.fromString((String) lease.carrier().get("requestId"))) + || !bindingGeneration.toString().equals(scope.get("bindingGeneration")) + || !candidate.accountId().toString().equals(scope.get("accountId")) + || !candidate.tenantId().toString().equals(scope.get("tenantId")) + || !candidate.characterId().toString().equals(scope.get("characterId")) + || !candidate.sessionId().toString().equals(scope.get("sessionId")) + || !candidate.regionId().toString().equals(scope.get("regionId")) + || !candidate.regionEpoch().toString().equals(scope.get("regionEpoch"))) { + throw unavailable(); + } + requireCandidateMatchesTarget(candidate, target); + requireTargetMatchesLease(target, lease); + } + + private static void requireAllocationMatchesOperation( + Allocation allocation, AccountGameplayAdmissionLeaseOperation operation) { + AccountGameplayAdmissionLeaseEvidence evidence = operation.evidence(); + if (!allocation + .accountId() + .toString() + .equals(object(evidence.carrier().get("bindingScope")).get("accountId")) + || !allocation.requestId().toString().equals(evidence.carrier().get("requestId")) + || !allocation.leaseId().toString().equals(evidence.carrier().get("leaseId")) + || !Long.toString(allocation.leaseFence()).equals(evidence.carrier().get("leaseFence"))) { + throw unavailable(); + } + } + + private AccountGameplayAdmissionLeaseEvidence buildOriginalEvidence( + DSLContext dsl, + Allocation allocation, + String callerWorkload, + Candidate candidate, + Target target, + BigInteger bindingGeneration, + Map currentSourceFields, + long tokenExpiryEpochSecond) { + Long databaseNow = + dsl.fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + if (databaseNow == null || databaseNow <= 0L) throw unavailable(); + long now = databaseNow; + long originalExpiry; + try { + originalExpiry = + Math.min( + Math.addExact(now, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS), + Math.multiplyExact(tokenExpiryEpochSecond, 1000L)); + } catch (ArithmeticException overflow) { + throw unavailable(); + } + if (now <= 0L || originalExpiry <= now) throw unavailable(); + + Map scope = + Map.ofEntries( + Map.entry("accountId", candidate.accountId().toString()), + Map.entry("tenantId", target.canonicalTenantId().toString()), + Map.entry("realmId", target.realmId().toString()), + Map.entry("worldSlug", target.worldSlug()), + Map.entry("realmSlug", target.realmSlug()), + Map.entry("playableStateNamespaceId", target.playableStateNamespaceId().toString()), + Map.entry("playableStateScope", target.playableStateScope()), + Map.entry("gameInstanceId", target.canonicalGameInstanceId().toString()), + Map.entry("characterId", candidate.characterId().toString()), + Map.entry("sessionId", candidate.sessionId().toString()), + Map.entry("bindingGeneration", bindingGeneration.toString()), + Map.entry("catalogRevision", Long.toString(target.catalogRevision())), + Map.entry("pointerVersion", Long.toString(target.pointerVersion())), + Map.entry("regionId", candidate.regionId().toString()), + Map.entry("regionEpoch", candidate.regionEpoch().toString())); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put("callerWorkload", callerWorkload); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("bindingScope", scope); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.putAll(currentSourceFields); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put("expiresAt", Long.toString(originalExpiry)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private T withCurrentSources( + VerifiedCaller caller, UUID tenantId, CurrentSourceOperation operation) { + Objects.requireNonNull(caller); + Objects.requireNonNull(tenantId); + try { + return inWritableSerializableTransaction( + dsl -> { + AccountGameplayAdmissionCurrentSources currentSources = + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); + var current = + currentSources.readCurrentPublicProductionNew( + tenantId, caller.identity().tokenJti(), caller.currentCandidate()); + return operation.apply( + new CurrentAccountOperation( + dsl, current, new AccountGameplayAdmissionLeaseRepository(dsl))); + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw unavailable(); + } + } + + /** Exact non-admitting read after fresh current caller/global Account/token SQL proof. */ + private AccountGameplayAdmissionLeaseOperation readExactWithCurrentCallerOnly( + VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { + try { + return inWritableSerializableTransaction( + dsl -> { + AccountGameplayAdmissionCurrentSources currentSources = + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); + currentSources.requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); + return new AccountGameplayAdmissionLeaseRepository(dsl) + .readExact(lease) + .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw unavailable(); + } + } + + /** + * Exact finalization lookup: terminal history needs only current caller proof, while PENDING + * still requires the complete current public-production tenant source tuple in this transaction. + */ + private AccountGameplayAdmissionLeaseOperation readExactForFinalization( + VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { + try { + return inWritableSerializableTransaction( + dsl -> { + AccountGameplayAdmissionCurrentSources currentSources = + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); + currentSources.requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); + AccountGameplayAdmissionLeaseRepository repository = + new AccountGameplayAdmissionLeaseRepository(dsl); + AccountGameplayAdmissionLeaseOperation operation = + repository + .readExact(lease) + .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); + if (operation.state() == AccountGameplayAdmissionLeaseOperation.State.PENDING) { + var current = + currentSources.readCurrentPublicProductionNew( + tenantId(lease), caller.identity().tokenJti(), caller.currentCandidate()); + current.requireMatchesOriginalLease(lease); + } + return operation; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw unavailable(); + } + } + + /** + * Atomically records or replays the exact orphan obligation under fresh caller-only SQL proof. + */ + private AccountGameplayAdmissionLeaseOperation abortExactWithCurrentCallerOnly( + VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease, UUID decisionId) { + try { + return inWritableSerializableTransaction( + dsl -> { + AccountGameplayAdmissionCurrentSources currentSources = + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); + currentSources.requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); + AccountGameplayAdmissionLeaseRepository repository = + new AccountGameplayAdmissionLeaseRepository(dsl); + AccountGameplayAdmissionLeaseOperation operation = + repository + .readExact(lease) + .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); + if (operation.state() == AccountGameplayAdmissionLeaseOperation.State.PENDING) { + // Null decision records an unresolved orphan obligation, not proof of absence. + return repository.recordAborted(lease, decisionId, UUID.randomUUID()); + } + if (operation.state() == AccountGameplayAdmissionLeaseOperation.State.ABORTED) { + requireAbortDecisionMatches(decisionId, operation); + } else if (decisionId != null && !decisionId.equals(operation.bindingDecisionId())) { + throw unavailable(); + } + return operation; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw unavailable(); + } + } + + private T inWritableSerializableTransaction( + java.util.function.Function operation) { + DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(manager); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setReadOnly(false); + T result = + transaction.execute( + status -> { + if (!status.isNewTransaction()) throw unavailable(); + Object resource = + TransactionSynchronizationManager.getResource( + Objects.requireNonNull(manager.getDataSource())); + if (!(resource instanceof ConnectionHolder holder)) throw unavailable(); + Connection connection = holder.getConnection(); + try { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != Connection.TRANSACTION_SERIALIZABLE) { + throw unavailable(); + } + } catch (java.sql.SQLException failure) { + throw unavailable(); + } + return operation.apply(DSL.using(connection, SQLDialect.POSTGRES)); + }); + return Objects.requireNonNull(result); + } + + private void requireNoAmbientSql() { + Object managedDataSource = + Objects.requireNonNull(new DataSourceTransactionManager(dataSource).getDataSource()); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || TransactionSynchronizationManager.hasResource(dataSource) + || TransactionSynchronizationManager.hasResource(managedDataSource)) { + throw Status.FAILED_PRECONDITION + .withDescription("Gameplay admission owner requires no ambient Account transaction") + .asRuntimeException(); + } + } + + private GrpcPeerIdentity requireGameSessionCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || !GAME_SESSION_SERVICE.equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !expectedGameSessionPeer().equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + return peer; + } + + private VerifiedCaller verifyCaller(String compactJwt, GrpcPeerIdentity peer) { + VerifiedCaller caller; + try { + caller = callerVerifier.verifyPresentedCompactToken(compactJwt); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + if (!peer.uri().equals(caller.identity().callerWorkload())) throw unavailable(); + return caller; + } + + private OriginalAckReceiptEvidence requireReceiptIfCommitted( + AccountGameplayAdmissionLeaseOperation operation) { + if (operation.state() != AccountGameplayAdmissionLeaseOperation.State.COMMITTED) return null; + return requireReceipt(operation, operation.bindingDecisionId()); + } + + private OriginalAckReceiptEvidence requireReceipt( + AccountGameplayAdmissionLeaseOperation operation, UUID decisionId) { + if (operation.state() != AccountGameplayAdmissionLeaseOperation.State.COMMITTED + || decisionId == null + || !decisionId.equals(operation.bindingDecisionId())) throw unavailable(); + AccountGameplayAdmissionOriginalAckReceipt receipt; + try { + receipt = receiptExecutor.read(operation.evidence(), decisionId); + } catch (RuntimeException unavailable) { + throw unavailable(); + } + requireReceiptOperation(receipt, operation.evidence(), decisionId); + return receiptEvidence(receipt); + } + + private static void requireReceiptOperation( + AccountGameplayAdmissionOriginalAckReceipt receipt, + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decisionId) { + if (!receipt.operation().evidence().hasSameIdentity(evidence) + || receipt.operation().state() != AccountGameplayAdmissionLeaseOperation.State.COMMITTED + || !decisionId.equals(receipt.bindingDecisionId())) throw unavailable(); + } + + private static OriginalAckReceiptEvidence receiptEvidence( + AccountGameplayAdmissionOriginalAckReceipt receipt) { + return OriginalAckReceiptEvidence.fromFields( + receipt.schemaVersion(), + receipt.requestId(), + receipt.accountId(), + receipt.leaseId(), + receipt.leaseFence(), + receipt.evidenceSha256(), + receipt.bindingDecisionId(), + receipt.expiresAtMs(), + receipt.finalizationXid(), + receipt.committedBeforeMs(), + receipt.receiptXid()); + } + + private static void requireAbortDecisionMatches( + UUID requestedDecision, AccountGameplayAdmissionLeaseOperation operation) { + if (requestedDecision != null && !requestedDecision.equals(operation.bindingDecisionId())) { + throw unavailable(); + } + } + + private static AccountGameplayAdmissionLeaseGrpcCodec.State wireState( + AccountGameplayAdmissionLeaseOperation.State state) { + return switch (state) { + case PENDING -> AccountGameplayAdmissionLeaseGrpcCodec.State.PENDING; + case COMMITTED -> AccountGameplayAdmissionLeaseGrpcCodec.State.COMMITTED; + case ABORTED -> AccountGameplayAdmissionLeaseGrpcCodec.State.ABORTED; + }; + } + + private static UUID tenantId(AccountGameplayAdmissionLeaseEvidence evidence) { + Map scope = object(evidence.carrier().get("bindingScope")); + return UUID.fromString((String) scope.get("tenantId")); + } + + private static UUID requestId(AccountGameplayAdmissionLeaseEvidence evidence) { + return UUID.fromString((String) evidence.carrier().get("requestId")); + } + + private String expectedGameSessionPeer() { + return "spiffe://firemud/ns/" + workloadNamespace + "/sa/" + GAME_SESSION_SERVICE; + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) throw unavailable(); + return map; + } + + private static StatusRuntimeException invalidArgument() { + return Status.INVALID_ARGUMENT + .withDescription("Malformed Account gameplay admission request") + .asRuntimeException(); + } + + private static StatusRuntimeException unavailable() { + return Status.UNAVAILABLE + .withDescription("Account gameplay admission owner is unavailable") + .asRuntimeException(); + } + + private record CurrentAccountOperation( + DSLContext dsl, + AccountGameplayAdmissionCurrentSources.Current currentSources, + AccountGameplayAdmissionLeaseRepository repository) { + private void requireCandidate( + Candidate candidate, VerifiedCaller caller, GrpcPeerIdentity peer) { + requireCandidateMatchesCaller(candidate, caller, peer); + } + } + + @FunctionalInterface + private interface CurrentSourceOperation { + T apply(CurrentAccountOperation current); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java index f0a2786a79..008e21744d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java @@ -10,6 +10,7 @@ import java.util.UUID; import javax.sql.DataSource; import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation.State; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -40,6 +41,36 @@ final class AccountGameplayAdmissionOriginalCommitExecutor { OriginalCommitAcknowledgement execute( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId) { + return execute(evidence, decisionId, null); + } + + /** + * Revalidates the authenticated caller's exact current Account sources on the original physical + * COMMIT connection. Remote JWT/JWKS/registry and published-target reads must precede this entry; + * neither the expected candidate nor this acknowledgement supplies those remote authorities. + */ + OriginalCommitAcknowledgement executeWithCurrentSources( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decisionId, + String configuredNamespace, + CommittedCandidateVerificationData authenticatedCandidate) { + Objects.requireNonNull(evidence); + if (evidence.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || evidence.carrier().containsKey("expectedOldBindingGeneration")) { + throw denied(); + } + return execute( + evidence, + decisionId, + new CurrentSourceScope( + Objects.requireNonNull(configuredNamespace), + Objects.requireNonNull(authenticatedCandidate))); + } + + private OriginalCommitAcknowledgement execute( + AccountGameplayAdmissionLeaseEvidence evidence, + UUID decisionId, + CurrentSourceScope currentSources) { Objects.requireNonNull(evidence); Objects.requireNonNull(decisionId); var manager = new OriginalCommitTransactionManager(dataSource); @@ -58,10 +89,23 @@ OriginalCommitAcknowledgement execute( ignored -> { if (!ignored.isNewTransaction()) throw denied(); Connection connection = manager.enlistedConnection(); - // The repository cannot acquire another connection: its DSL uses this connection itself. - var repository = - new AccountGameplayAdmissionLeaseRepository( - DSL.using(connection, SQLDialect.POSTGRES)); + // Every source and lease repository uses this exact enlisted connection. The concrete + // source graph locks Account first, before authority, token and lease-operation rows, and + // retains those locks through the original physical COMMIT below. + var exactDsl = DSL.using(connection, SQLDialect.POSTGRES); + if (currentSources != null) { + var scope = (java.util.Map) evidence.carrier().get("bindingScope"); + var token = (java.util.Map) evidence.carrier().get("tokenIdentityEvidence"); + var current = + AccountGameplayAdmissionCurrentSources.bind( + exactDsl, currentSources.configuredNamespace()) + .readCurrentPublicProductionNew( + UUID.fromString((String) scope.get("tenantId")), + UUID.fromString((String) token.get("tokenJti")), + currentSources.authenticatedCandidate()); + current.requireMatchesOriginalLease(evidence); + } + var repository = new AccountGameplayAdmissionLeaseRepository(exactDsl); var prior = repository .readExact(evidence) @@ -122,6 +166,9 @@ public String toString() { } } + private record CurrentSourceScope( + String configuredNamespace, CommittedCandidateVerificationData authenticatedCandidate) {} + private record OriginalBinding( AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId, String finalizationXid) {} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java index 82856c0427..b60aabedfd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -2513,6 +2513,30 @@ public AccountGameplayDelegationRedisClient.PendingRegistrationOutcome registrat return registrationOutcome; } + /** Complete immutable owner-value comparison; this does not establish current authority. */ + public static boolean hasSameOwnerEvidence( + CommittedCandidateVerificationData left, CommittedCandidateVerificationData right) { + return left != null + && right != null + && left.identity().equals(right.identity()) + && left.authoritySnapshot().equals(right.authoritySnapshot()) + && left.evidenceBundleReference().equals(right.evidenceBundleReference()) + && left.tokenSha256().equals(right.tokenSha256()) + && left.signerKid().equals(right.signerKid()) + && left.signerGeneration().equals(right.signerGeneration()) + && left.canonicalRegistryRecordSha256().equals(right.canonicalRegistryRecordSha256()) + && left.commitProofSha256().equals(right.commitProofSha256()) + && left.signerCorrespondence().equals(right.signerCorrespondence()) + && left.envelopeKeyId().equals(right.envelopeKeyId()) + && left.envelopeSha256().equals(right.envelopeSha256()) + && left.envelopeBytesLength() == right.envelopeBytesLength() + && left.responseRecoveryExpiryEpochMillis() == right.responseRecoveryExpiryEpochMillis() + && left.registryAbsoluteExpiryMillis() == right.registryAbsoluteExpiryMillis() + && left.registrationLocalAofCount() == right.registrationLocalAofCount() + && left.registrationReplicaAofCount() == right.registrationReplicaAofCount() + && left.registrationOutcome() == right.registrationOutcome(); + } + @Override public String toString() { return "CommittedCandidateVerificationData[redacted]"; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java new file mode 100644 index 0000000000..bfc5846ae3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifier.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account source component for internal gameplay-admission owner integration. + * + *

This source has no runtime registration or callable API. Successful verification is only a + * private input to an admission composition; it is not membership, entitlement, current admission, + * or a Game Session binding decision. The presented token is never retained or returned. + */ +public final class AccountGameplayAdmissionCallerVerifier { + private static final Duration MAX_JWKS_CACHE_AGE = Duration.ofSeconds(30); + private static final ExplicitRouteProfilePolicy POLICY = + new ExplicitRouteProfilePolicy( + "account-gameplay-admission-caller", + GameSessionAccountDelegationProfile.PROFILE, + GameSessionAccountDelegationProfile.TYPE, + GameSessionAccountDelegationProfile.ISSUER, + GameSessionAccountDelegationProfile.AUDIENCE, + GameSessionAccountDelegationJwtProfileValidator.REQUIRED_CLAIMS, + GameSessionAccountDelegationJwtProfileValidator.OPTIONAL_CLAIMS, + GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS, + 5, + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES, + GameSessionAccountDelegationJwtProfileValidator::validateClaims); + + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final AccountGameplayDelegationCommittedIssuanceOwner currentIssuanceOwner; + private final Clock clock; + private final Object cacheMonitor = new Object(); + private AccountPublicJwksCache publicJwksCache; + + public AccountGameplayAdmissionCallerVerifier( + AccountJwtJwksTrustedSource trustedJwksSource, + AccountGameplayDelegationCommittedIssuanceOwner currentIssuanceOwner, + Clock clock) { + this.trustedJwksSource = Objects.requireNonNull(trustedJwksSource); + this.currentIssuanceOwner = Objects.requireNonNull(currentIssuanceOwner); + this.clock = Objects.requireNonNull(clock); + } + + /** + * Verifies signature and the fixed initial LOGIN profile before using the token JTI as a lookup + * hint for Account's current committed issuance and exact ACTIVE registry owner. + */ + public VerifiedCaller verifyPresentedCompactToken(String compactJwt) { + if (compactJwt == null + || compactJwt.isBlank() + || TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } + + try { + SourceIdentity trustedPin = trustedJwksSource.sourceIdentity(); + VerifiedClaims verified = + new AccountAsymmetricJwtVerifier(currentCache(trustedPin), clock) + .verify(compactJwt, POLICY); + + // The cryptographically and profile-verified JTI is only a lookup selector. It is not + // passed to Account's committed-currentness owner until signature/profile validation above. + UUID tokenJti = requireCanonicalUuid(verified.claims().get("jti")); + CommittedCandidateVerificationData candidate = + currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(tokenJti); + requireExactCandidate(compactJwt, verified, candidate); + return new VerifiedCaller(candidate); + } catch (RuntimeException failure) { + // Do not preserve exception text or causes that could expose credential or parser details. + throw unavailable(); + } + } + + private AccountPublicJwksCache currentCache(SourceIdentity identity) { + synchronized (cacheMonitor) { + if (publicJwksCache == null || !identity.equals(publicJwksCache.sourceIdentity())) { + publicJwksCache = + new AccountPublicJwksCache(trustedJwksSource, identity, clock, MAX_JWKS_CACHE_AGE); + } + return publicJwksCache; + } + } + + private static void requireExactCandidate( + String compactJwt, VerifiedClaims verified, CommittedCandidateVerificationData candidate) { + Objects.requireNonNull(candidate); + AccountGameplayDelegationPendingIdentity identity = candidate.identity(); + Map claims = verified.claims(); + var authority = candidate.authoritySnapshot(); + Map expectedAuthorityTuple = + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff()); + + byte[] compactBytes = compactJwt.getBytes(StandardCharsets.UTF_8); + String compactDigest; + try { + compactDigest = + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(compactBytes)); + } catch (NoSuchAlgorithmException failure) { + throw unavailable(); + } finally { + Arrays.fill(compactBytes, (byte) 0); + } + + Object membershipVersion = claims.get("membershipVersion"); + if (!GameSessionAccountDelegationProfile.PROFILE.equals(verified.profile()) + || !GameSessionAccountDelegationProfile.TYPE.equals(verified.tokenType()) + || !candidate.signerKid().equals(verified.keyId()) + || !identity.accountId().toString().equals(claims.get("sub")) + || !identity.accountId().toString().equals(claims.get("accountId")) + || !identity.tokenJti().toString().equals(claims.get("jti")) + || !identity.tokenJti().equals(requireCanonicalUuid(claims.get("jti"))) + // The current Account issuance reader selects only its supported generation-1 profile. + || positiveCounter(claims, "tokenGeneration") != 1L + || numberClaim(claims, "iat") != identity.issuedAtEpochSecond() + || numberClaim(claims, "nbf") != identity.notBeforeEpochSecond() + || numberClaim(claims, "exp") != identity.expiresAtEpochSecond() + || positiveCounter(claims, "issuanceFence") != authority.issuanceFence() + || !(membershipVersion instanceof Map versionMap) + || !versionMap.isEmpty() + || !expectedAuthorityTuple.equals(claims.get("authorityTuple")) + || claims.containsKey("globalRoles") + || claims.containsKey("scopedRoles") + || !identity.accountId().equals(authority.accountId()) + || !compactDigest.equals(candidate.tokenSha256())) { + throw unavailable(); + } + } + + private static UUID requireCanonicalUuid(Object value) { + if (!(value instanceof String text)) throw unavailable(); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.version() != 4 || parsed.variant() != 2) { + throw unavailable(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw unavailable(); + } + } + + private static long positiveCounter(Map claims, String field) { + try { + return AccountJwtExactValues.positiveDecimalCounter(claims.get(field)).longValueExact(); + } catch (IllegalArgumentException | ArithmeticException malformed) { + throw unavailable(); + } + } + + private static long numberClaim(Map claims, String field) { + Object value = claims.get(field); + if (!(value instanceof Number number)) throw unavailable(); + try { + return new BigDecimal(number.toString()).longValueExact(); + } catch (ArithmeticException | NumberFormatException malformed) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account gameplay caller verification is unavailable"); + } + + /** + * Unforgeable Account-source result for the manually composed admission owner. Its public + * accessors expose only immutable owner identity/current-candidate evidence; it retains no JWT, + * claim map, or registry bytes. The committed currentness owner returns only after the immutable + * token fence is ACTIVE; AccountGameplayTokenIdentityFence constrains that fence value to 1. + */ + public static final class VerifiedCaller { + private final CommittedCandidateVerificationData committedCandidate; + + private VerifiedCaller(CommittedCandidateVerificationData committedCandidate) { + this.committedCandidate = Objects.requireNonNull(committedCandidate); + } + + public CommittedCandidateVerificationData currentCandidate() { + return committedCandidate; + } + + CommittedCandidateVerificationData committedCandidate() { + return committedCandidate; + } + + public AccountGameplayDelegationPendingIdentity identity() { + return committedCandidate.identity(); + } + + long tokenIdentityFence() { + return 1L; + } + + String tokenProfile() { + return GameSessionAccountDelegationProfile.PROFILE; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java new file mode 100644 index 0000000000..7ea03fe510 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcService.java @@ -0,0 +1,188 @@ +package net.firedevops.firemud.accountservice.service.session; + +import com.google.protobuf.MessageLite; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import org.jooq.exception.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone, unregistered receiver for Account's four NEW lease operations. */ +public final class AccountGameplayAdmissionLeaseGrpcService + extends AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceImplBase { + private static final String FAILURE_DESCRIPTION = + "Account gameplay admission lease operation denied or unavailable"; + + private final AccountGameplayAdmissionLeaseOwner owner; + private final AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard; + + AccountGameplayAdmissionLeaseGrpcService( + AccountGameplayAdmissionLeaseOwner owner, + AccountGameplayAdmissionLeaseWorkloadGuard workloadGuard) { + this.owner = Objects.requireNonNull(owner, "Account gameplay admission lease owner required"); + this.workloadGuard = + Objects.requireNonNull(workloadGuard, "Account gameplay admission lease guard required"); + } + + @Override + public void acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + receive( + request, + observer, + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ACQUIRE_REQUEST_WIRE_BYTES, + () -> { + var parsed = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(request); + workloadGuard.requireAcquisitionNamespace(parsed); + return () -> owner.acquire(request); + }); + } + + @Override + public void finalizeGameplayAdmissionLease( + FinalizeGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + receive( + request, + observer, + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + () -> { + var parsed = AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(request); + workloadGuard.requireOriginalLeaseNamespace(parsed); + return () -> owner.finalizeLease(request); + }); + } + + @Override + public void readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + receive( + request, + observer, + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + () -> { + var parsed = AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(request); + workloadGuard.requireOriginalLeaseNamespace(parsed); + return () -> owner.read(request); + }); + } + + @Override + public void abortGameplayAdmissionLease( + AbortGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + receive( + request, + observer, + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, + () -> { + var parsed = AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(request); + workloadGuard.requireOriginalLeaseNamespace(parsed); + return () -> owner.abort(request); + }); + } + + private void receive( + T request, + StreamObserver observer, + int maximumBytes, + Supplier> validateAndCall) { + Objects.requireNonNull(observer, "response observer is required"); + + final Supplier ownerCall; + try { + // This is deliberately the first request-related operation. + workloadGuard.requireGameSessionCaller(); + } catch (StatusRuntimeException denied) { + fail(observer, denied.getStatus()); + return; + } + + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } + if (request == null || serializedSize(request) > maximumBytes) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } + + try { + ownerCall = validateAndCall.get(); + } catch (StatusRuntimeException invalidOrDenied) { + fail(observer, invalidOrDenied.getStatus()); + return; + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT); + return; + } catch (RuntimeException malformed) { + fail(observer, Status.INTERNAL); + return; + } + + final AccountGameplayAdmissionLeaseResponse response; + try { + response = Objects.requireNonNull(ownerCall.get(), "Account owner response required"); + } catch (StatusRuntimeException failure) { + fail(observer, failure.getStatus()); + return; + } catch (CannotCreateTransactionException unavailable) { + fail(observer, Status.UNAVAILABLE); + return; + } catch (DataAccessResourceFailureException unavailable) { + fail(observer, Status.UNAVAILABLE); + return; + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + fail(observer, hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL); + return; + } catch (IllegalArgumentException ownerPrecondition) { + fail(observer, Status.FAILED_PRECONDITION); + return; + } catch (RuntimeException failure) { + fail(observer, Status.INTERNAL); + return; + } + + // Keep observer callbacks out of the owner failure boundary. A broken observer must not + // trigger a second terminal callback or be translated into an owner failure status. + observer.onNext(response); + observer.onCompleted(); + } + + private static int serializedSize(Object request) { + return request instanceof MessageLite message ? message.getSerializedSize() : Integer.MAX_VALUE; + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) return true; + } + } + return false; + } + + private static void fail(StreamObserver observer, Status status) { + observer.onError( + Status.fromCode(status.getCode()) + .withDescription(FAILURE_DESCRIPTION) + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java new file mode 100644 index 0000000000..8eb97c6693 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseManualFactory.java @@ -0,0 +1,57 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.TlsServerCredentials; +import java.util.List; +import java.util.Objects; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; + +/** Explicit construction path for the unregistered Account NEW lease receiver. */ +public final class AccountGameplayAdmissionLeaseManualFactory { + private AccountGameplayAdmissionLeaseManualFactory() {} + + public static AccountGameplayAdmissionLeaseGrpcService createUnregisteredReceiver( + AccountGameplayAdmissionLeaseOwner owner, String workloadNamespace) { + return new AccountGameplayAdmissionLeaseGrpcService( + Objects.requireNonNull(owner, "Account gameplay admission lease owner required"), + new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace)); + } + + /** Creates an unstarted TLS server with a finite ceiling and no production registration. */ + public static Server createUnregisteredServer( + String address, + KeyManagerFactory keys, + TrustManagerFactory trust, + AccountGameplayAdmissionLeaseOwner owner, + String workloadNamespace) { + Objects.requireNonNull(address, "gRPC server address required"); + Objects.requireNonNull(keys, "gRPC server key manager required"); + Objects.requireNonNull(trust, "gRPC server trust manager required"); + int transportMaximum = + Math.max( + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ACQUIRE_REQUEST_WIRE_BYTES, + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES); + var factory = + new BoundedGrpcServerFactory( + address, + List.of(), + keys, + trust, + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + transportMaximum); + factory.addService( + ServerInterceptors.interceptForward( + createUnregisteredReceiver(owner, workloadNamespace), + new GrpcPeerIdentityInterceptor(), + new AccountGameplayAdmissionLeaseWorkloadGuard(workloadNamespace))); + return factory.createServer(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java new file mode 100644 index 0000000000..76aae99c5f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuard.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Method-specific gate for Account's same-namespace Game Session lease receiver. */ +public final class AccountGameplayAdmissionLeaseWorkloadGuard implements ServerInterceptor { + private static final String GAME_SESSION_SERVICE = "game-session-service"; + + private final String namespace; + + public AccountGameplayAdmissionLeaseWorkloadGuard(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + /** Checks the certificate-derived peer before the receiver examines request fields. */ + public void requireGameSessionCaller() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified Game Session workload identity required") + .asRuntimeException(); + } + if (hasSessionContext() + || !GAME_SESSION_SERVICE.equals(peer.service()) + || !namespace.equals(peer.namespace()) + || !expectedPeerUri().equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Session workload required") + .asRuntimeException(); + } + } + + /** Authenticates the peer and closes every non-lease method before its request is parsed. */ + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + try { + requireGameSessionCaller(); + } catch (StatusRuntimeException denied) { + call.close( + Status.fromCode(denied.getStatus().getCode()) + .withDescription("Exact same-namespace Game Session workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + if (!isLeaseMethod(call.getMethodDescriptor())) { + call.close( + Status.PERMISSION_DENIED.withDescription( + "Account gameplay admission lease method required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } + + private static boolean isLeaseMethod(MethodDescriptor method) { + String fullMethodName = method.getFullMethodName(); + return AccountGameplayAdmissionLeaseServiceGrpc.getAcquireGameplayAdmissionLeaseMethod() + .getFullMethodName() + .equals(fullMethodName) + || AccountGameplayAdmissionLeaseServiceGrpc.getFinalizeGameplayAdmissionLeaseMethod() + .getFullMethodName() + .equals(fullMethodName) + || AccountGameplayAdmissionLeaseServiceGrpc.getReadGameplayAdmissionLeaseMethod() + .getFullMethodName() + .equals(fullMethodName) + || AccountGameplayAdmissionLeaseServiceGrpc.getAbortGameplayAdmissionLeaseMethod() + .getFullMethodName() + .equals(fullMethodName); + } + + public void requireAcquisitionNamespace( + AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest request) { + if (request == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Malformed Account gameplay admission lease request") + .asRuntimeException(); + } + if (!namespace.equals(request.expectedTarget().targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Gameplay admission lease target namespace is not authorized") + .asRuntimeException(); + } + } + + public void requireOriginalLeaseNamespace( + AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest request) { + if (request == null) { + throw Status.INVALID_ARGUMENT + .withDescription("Malformed Account gameplay admission lease request") + .asRuntimeException(); + } + Object targetNamespace = request.originalLeaseEvidence().carrier().get("targetNamespace"); + if (!namespace.equals(targetNamespace)) { + throw Status.PERMISSION_DENIED + .withDescription("Gameplay admission lease target namespace is not authorized") + .asRuntimeException(); + } + } + + private static boolean hasSessionContext() { + return SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null; + } + + private String expectedPeerUri() { + return "spiffe://firemud/ns/" + namespace + "/sa/" + GAME_SESSION_SERVICE; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java index c3b7c93d6a..c79bfaee41 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java @@ -219,23 +219,7 @@ private static void requireExactActiveReceipt( private static boolean sameCommittedOwnerEvidence( CommittedCandidateVerificationData left, CommittedCandidateVerificationData right) { - return left.identity().equals(right.identity()) - && left.authoritySnapshot().equals(right.authoritySnapshot()) - && left.evidenceBundleReference().equals(right.evidenceBundleReference()) - && left.tokenSha256().equals(right.tokenSha256()) - && left.signerKid().equals(right.signerKid()) - && left.signerGeneration().equals(right.signerGeneration()) - && left.canonicalRegistryRecordSha256().equals(right.canonicalRegistryRecordSha256()) - && left.commitProofSha256().equals(right.commitProofSha256()) - && left.signerCorrespondence().equals(right.signerCorrespondence()) - && left.envelopeKeyId().equals(right.envelopeKeyId()) - && left.envelopeSha256().equals(right.envelopeSha256()) - && left.envelopeBytesLength() == right.envelopeBytesLength() - && left.responseRecoveryExpiryEpochMillis() == right.responseRecoveryExpiryEpochMillis() - && left.registryAbsoluteExpiryMillis() == right.registryAbsoluteExpiryMillis() - && left.registrationLocalAofCount() == right.registrationLocalAofCount() - && left.registrationReplicaAofCount() == right.registrationReplicaAofCount() - && left.registrationOutcome() == right.registrationOutcome(); + return CommittedCandidateVerificationData.hasSameOwnerEvidence(left, right); } private static OwnerUnavailableException unavailable() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java new file mode 100644 index 0000000000..c29c6a8b57 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java @@ -0,0 +1,2671 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import io.grpc.Context; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.ClientCalls; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.output.CommandOutput; +import io.lettuce.core.output.StatusOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +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 java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.dto.AccountGameplayAdmissionLeaseOperation; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence; +import net.firedevops.firemud.accountservice.dto.AccountGameplayTokenIdentityFence.TokenIdentity; +import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementSnapshot; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionLeaseManualFactory; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommitSignerFixture; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.LettuceAccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.ConnectionHolder; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DelegatingDataSource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.DockerClientFactory; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; + +/** + * PostgreSQL proof for the Account-local current-source graph and its authenticated acquire owner. + * + *

The fixture creates a controlled fresh tenant, typed demo-entitlement event, first active + * membership/event, and real committed SQL token issuance through their existing owner writers. The + * source-lock cases retain their command-controlled Redis fixture. The authenticated acquire case + * uses physical test Redis and actual cryptographic verification over the manual mTLS receiver. The + * signer performs real RSA/JWS operations with its exact test JWKS, while protected + * signer/materializer evidence and Game Session published/provisional reads remain controlled + * boundaries. The fresh Account finalization path uses physical PostgreSQL 18 COMMIT and durable + * ACK insertion; PG18 retained-receipt replay remains intentionally unavailable. This proves + * neither production custody, real Game Session owner authority, runtime registration, nor an + * admitted Game Session binding. + */ +class AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "gameplay_admission_current_"; + private static final String TEST_NAMESPACE = "test"; + private static final String CALLER_WORKLOAD = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ACCOUNT_WORKLOAD = "spiffe://firemud/ns/test/sa/account-service"; + private static final String ACCOUNT_ISSUER = "firemud-account-service"; + + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + + @TempDir Path temporaryDirectory; + private final Set runOwnedSchemas = java.util.concurrent.ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate root = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : runOwnedSchemas) { + if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean a schema not owned by this test"); + } + root.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + runOwnedSchemas.clear(); + } + + @Test + void positiveCurrentReadReturnsExactFiveSourcesAndOriginalCommitPreservesOwners() + throws Exception { + Fixture fixture = newFixture(); + List sourceImageBeforeRead = fixture.sourceAndIssuanceImage(); + CommittedCandidateVerificationData independentCandidate = fixture.readCommittedCandidate(); + var current = fixture.readCurrent(independentCandidate); + + assertThat(fixture.sourceAndIssuanceImage()).isEqualTo(sourceImageBeforeRead); + assertThat( + CommittedCandidateVerificationData.hasSameOwnerEvidence( + independentCandidate, current.currentCommittedCandidate())) + .isTrue(); + assertThat(current.typedTenantEvent().gameplayAvailable()).isTrue(); + assertThat(current.typedTenantEvent().allowNewGameplayBindings()).isTrue(); + assertThat(current.leaseSourceFields().keySet()) + .containsExactlyInAnyOrder( + "authorityTuple", + "issuanceFence", + "membershipBaseline", + "outboxCheckpoints", + "tokenIdentityEvidence"); + assertThat(current.leaseSourceFields()).isEqualTo(expectedLeaseSourceFields(fixture, current)); + + AccountGameplayAdmissionLeaseEvidence originalLease = + fixture.beginPendingAdmissionLease(current); + List ownerImageBeforeOriginalCommit = fixture.sourceAndIssuanceImage(); + UUID decisionId = UUID.randomUUID(); + var acknowledgement = + new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) + .executeWithCurrentSources( + originalLease, decisionId, TEST_NAMESPACE, independentCandidate); + + assertThat(acknowledgement.evidence()).isEqualTo(originalLease); + assertThat(acknowledgement.decisionId()).isEqualTo(decisionId); + assertThat(acknowledgement.finalizationXid()).matches("[1-9][0-9]{0,19}"); + assertThat(fixture.readLeaseOperation(originalLease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + assertThat(fixture.sourceAndIssuanceImage()).isEqualTo(ownerImageBeforeOriginalCommit); + assertThat(fixture.readCurrent(fixture.readCommittedCandidate()).leaseSourceFields()) + .isEqualTo(current.leaseSourceFields()); + } + + @Test + void authenticatedAccountOwnerAcquiresAndRetriesTheExactRecoveredAccountToken() throws Exception { + try (PhysicalRedisFixture redis = PhysicalRedisFixture.start()) { + Fixture fixture = newFixture(redis.client()); + var issuanceIdentity = fixture.committedCandidate.identity(); + CallerIdentity recoveryCaller = + new CallerIdentity(issuanceIdentity.callerWorkload(), issuanceIdentity.callerContextId()); + // Recovery returns the original committed JWT; this test never signs a replacement token. + RecoveredCredential recovered = + fixture.responseRecoveryOwner.recoverInitialLoginResponse( + issuanceIdentity.requestId(), issuanceIdentity.accountId(), recoveryCaller); + String originalJwt = new String(recovered.compactJwtBytes(), StandardCharsets.US_ASCII); + + assertThat(recovered.profile()).isEqualTo(GameSessionAccountDelegationProfile.PROFILE); + assertThat(recovered.accountId()).isEqualTo(fixture.account.getAccountUuid()); + assertThat(recovered.tokenJti()).isEqualTo(issuanceIdentity.tokenJti()); + assertThat(recovered.tokenSha256()).isEqualTo(fixture.committedCandidate.tokenSha256()); + + Candidate candidate = admissionCandidate(fixture); + UUID requestId = UUID.randomUUID(); + Target target = admissionTarget(candidate, UUID.randomUUID()); + // This exact typed return is a controlled Game Session transport boundary, not GS authority. + CanonicalGameplayAdmissionDecisionReadClient decisionClient = + controlledPublishedTargetClient(candidate, target, requestId); + controlProvisionalDecisionRead(decisionClient, candidate, target); + AccountGameplayAdmissionCallerVerifier callerVerifier = + new AccountGameplayAdmissionCallerVerifier( + fixture.signerFixture.trustedJwksSource(), + fixture.committedIssuanceOwner, + Clock.systemUTC()); + AdmissionClockCapture clockCapture = new AdmissionClockCapture(); + DataSource ownerDataSource = captureAdmissionClockReads(fixture.dataSource, clockCapture); + AccountGameplayAdmissionLeaseOwner owner = + new AccountGameplayAdmissionLeaseOwner( + callerVerifier, decisionClient, TEST_NAMESPACE, ownerDataSource); + var wireRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + requestId, originalJwt, candidate, target, BigInteger.ONE); + var parsedRequest = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(wireRequest); + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(CALLER_WORKLOAD).orElseThrow(); + UUID accountId = fixture.account.getAccountUuid(); + var sourceImageBeforeAcquire = fixture.sourceAndIssuanceImageForAuthenticatedAcquire(); + var allocatorBeforeAcquire = fixture.leaseAllocationState(requestId, accountId); + assertThat(allocatorBeforeAcquire).isEqualTo(new LeaseAllocationState(0L, 0L, null, null)); + + AtomicReference first = new AtomicReference<>(); + withPeer(peer, () -> first.set(owner.acquire(wireRequest))); + var firstEvidence = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + parsedRequest, Objects.requireNonNull(first.get())); + + var originalLease = firstEvidence.originalLeaseEvidence(); + long evaluatedAt = Long.parseLong((String) originalLease.carrier().get("evaluatedAt")); + assertThat(clockCapture.databaseMillis.get()).isEqualTo(evaluatedAt); + assertThat(clockCapture.clockConnection.get()) + .isNotNull() + .isSameAs(clockCapture.operationInsertConnection.get()); + assertThat(clockCapture.clockReadUsedEnlistedConnection.get()).isTrue(); + assertThat(clockCapture.operationInsertUsedEnlistedConnection.get()).isTrue(); + long originalExpiry = Long.parseLong((String) originalLease.carrier().get("expiresAt")); + assertThat(originalExpiry) + .isEqualTo( + Math.min( + Math.addExact( + evaluatedAt, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS), + Math.multiplyExact(issuanceIdentity.expiresAtEpochSecond(), 1_000L))); + UUID originalRequestId = UUID.fromString((String) originalLease.carrier().get("requestId")); + UUID originalLeaseId = UUID.fromString((String) originalLease.carrier().get("leaseId")); + long originalFence = originalLease.leaseFence().longValueExact(); + var allocationAfterFirst = fixture.leaseAllocationState(originalRequestId, accountId); + assertThat(allocationAfterFirst.allocationCount()).isEqualTo(1L); + assertThat(allocationAfterFirst.fenceCount()).isEqualTo(1L); + assertThat(allocationAfterFirst.allocation()) + .isEqualTo( + new LeaseAllocationRow(accountId, originalRequestId, originalLeaseId, originalFence)); + assertThat(allocationAfterFirst.fence()) + .isEqualTo(new LeaseFenceRow(accountId, originalFence)); + assertThat(originalRequestId).isEqualTo(requestId); + Map originalScope = (Map) originalLease.carrier().get("bindingScope"); + assertThat(originalScope.get("accountId")).isEqualTo(accountId.toString()); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAcquire); + assertThat(fixture.leaseOperationCount()).isEqualTo(1L); + + AtomicReference exactRetry = new AtomicReference<>(); + withPeer(peer, () -> exactRetry.set(owner.acquire(wireRequest))); + var retryEvidence = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + parsedRequest, Objects.requireNonNull(exactRetry.get())); + assertThat(firstEvidence.state()).isEqualTo(State.PENDING); + assertThat(retryEvidence.state()).isEqualTo(State.PENDING); + assertThat(retryEvidence.originalLeaseEvidence().canonicalJson()) + .isEqualTo(firstEvidence.originalLeaseEvidence().canonicalJson()); + assertThat(exactRetry.get().getOriginalLeaseEvidenceUtf8List()) + .containsExactlyElementsOf(first.get().getOriginalLeaseEvidenceUtf8List()); + assertThat(firstEvidence.originalLeaseEvidence().carrier().get("callerWorkload")) + .isEqualTo(CALLER_WORKLOAD); + var currentSources = fixture.readCurrent(fixture.readCommittedCandidate()); + assertThat(firstEvidence.originalLeaseEvidence().carrier()) + .containsAllEntriesOf(expectedLeaseSourceFields(fixture, currentSources)); + assertThat(fixture.leaseAllocationState(originalRequestId, accountId)) + .isEqualTo(allocationAfterFirst); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAcquire); + assertThat(fixture.leaseOperationCount()).isEqualTo(1L); + + Candidate mismatchedCaller = candidateWithAccount(candidate, UUID.randomUUID()); + var mismatchedRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + requestId, originalJwt, mismatchedCaller, target, BigInteger.ONE); + assertThatThrownBy(() -> withPeer(peer, () -> owner.acquire(mismatchedRequest))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(fixture.leaseAllocationState(originalRequestId, accountId)) + .isEqualTo(allocationAfterFirst); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAcquire); + assertThat(fixture.leaseOperationCount()).isEqualTo(1L); + // Revoking tenant eligibility prevents new admission; it must not prevent the same + // authenticated original caller from retaining and recovering its cleanup obligation. + fixture.disableTenantGameplay(fixture.readCurrentEntitlement()); + var sourceImageAfterEntitlementChange = + fixture.sourceAndIssuanceImageForAuthenticatedAcquire(); + byte[] originalBytes = originalLease.canonicalJson().getBytes(StandardCharsets.UTF_8); + var readWire = + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(originalJwt, originalBytes); + var parsedRead = AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(readWire); + var pendingRead = new AtomicReference(); + withPeer(peer, () -> pendingRead.set(owner.read(readWire))); + assertThat( + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( + parsedRead, pendingRead.get()) + .state()) + .isEqualTo(State.PENDING); + assertThatThrownBy(() -> withPeer(peer, () -> owner.acquire(wireRequest))) + .isInstanceOf(StatusRuntimeException.class); + + var finalizeWire = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest( + originalJwt, originalBytes, UUID.randomUUID()); + assertThatThrownBy(() -> withPeer(peer, () -> owner.finalizeLease(finalizeWire))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(fixture.readLeaseOperation(originalLease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + + var abortWire = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortRequest(originalJwt, originalBytes, null); + var parsedAbort = AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(abortWire); + var abortResponse = new AtomicReference(); + withPeer(peer, () -> abortResponse.set(owner.abort(abortWire))); + var aborted = + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortResponse( + parsedAbort, abortResponse.get()); + assertThat(aborted.state()).isEqualTo(State.ABORTED); + assertThat(aborted.orphanCleanupId()).isNotNull(); + assertThat(aborted.bindingDecisionId()).isNull(); + assertThat(aborted.originalLeaseEvidence().canonicalJson()) + .isEqualTo(originalLease.canonicalJson()); + withPeer(peer, () -> pendingRead.set(owner.read(readWire))); + var retainedAbort = + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse(parsedRead, pendingRead.get()); + assertThat(retainedAbort.state()).isEqualTo(State.ABORTED); + assertThat(retainedAbort.orphanCleanupId()).isEqualTo(aborted.orphanCleanupId()); + assertThat(retainedAbort.originalLeaseEvidence().canonicalJson()) + .isEqualTo(originalLease.canonicalJson()); + assertThat(fixture.leaseAllocationState(originalRequestId, accountId)) + .isEqualTo(allocationAfterFirst); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageAfterEntitlementChange); + assertThat(fixture.leaseOperationCount()).isEqualTo(1L); + } + } + + @Test + void authenticatedMtlsOwnerComposesAllFourRpcMethodsWithOriginalCommitAndAck() throws Exception { + try (PhysicalRedisFixture redis = PhysicalRedisFixture.start()) { + Fixture fixture = newFixture(redis.client()); + var issuanceIdentity = fixture.committedCandidate.identity(); + CallerIdentity recoveryCaller = + new CallerIdentity(issuanceIdentity.callerWorkload(), issuanceIdentity.callerContextId()); + // This is the exact JWT recovered from the real committed issuance, never a replacement. + RecoveredCredential recovered = + fixture.responseRecoveryOwner.recoverInitialLoginResponse( + issuanceIdentity.requestId(), issuanceIdentity.accountId(), recoveryCaller); + String originalJwt = new String(recovered.compactJwtBytes(), StandardCharsets.US_ASCII); + Candidate candidate = admissionCandidate(fixture); + UUID accountRequestId = UUID.randomUUID(); + UUID worldInitialAdmissionRequestId = UUID.randomUUID(); + assertThat(worldInitialAdmissionRequestId).isNotEqualTo(accountRequestId); + assertThat(issuanceIdentity.requestId()) + .isNotEqualTo(accountRequestId) + .isNotEqualTo(worldInitialAdmissionRequestId); + Target target = admissionTarget(candidate, worldInitialAdmissionRequestId); + assertThat(target.initialAdmissionRequestId()) + .isEqualTo(worldInitialAdmissionRequestId.toString()); + + // Both Game Session reverse reads stay at a controlled remote boundary. Provisional + // evidence is nevertheless produced and validated by the canonical closed wire codec using + // the exact acquired lease; this does not stand in for a Game Session owner or CAS. + CanonicalGameplayAdmissionDecisionReadClient decisionClient = + controlledPublishedTargetClient(candidate, target, accountRequestId); + controlProvisionalDecisionRead(decisionClient, candidate, target); + AccountGameplayAdmissionCallerVerifier callerVerifier = + new AccountGameplayAdmissionCallerVerifier( + fixture.signerFixture.trustedJwksSource(), + fixture.committedIssuanceOwner, + Clock.systemUTC()); + AccountGameplayAdmissionLeaseOwner owner = + new AccountGameplayAdmissionLeaseOwner( + callerVerifier, decisionClient, TEST_NAMESPACE, fixture.dataSource); + + Path pkiDirectory = Files.createTempDirectory(temporaryDirectory, "gameplay-admission-mtls-"); + var pki = + LoopbackMtlsTestPki.create( + pkiDirectory, + "Gameplay admission Account test CA", + new LoopbackMtlsTestPki.IdentitySpec("account-server", ACCOUNT_WORKLOAD, true), + new LoopbackMtlsTestPki.IdentitySpec("game-session-client", CALLER_WORKLOAD, false), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role-client", + "spiffe://firemud/ns/test/sa/world-management-service", + false)); + Server server = + AccountGameplayAdmissionLeaseManualFactory.createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account-server")), + pki.trustManagerFactory(), + owner, + TEST_NAMESPACE); + ManagedChannel gameSessionChannel = null; + ManagedChannel wrongRoleChannel = null; + boolean serverStarted = false; + try { + server.start(); + serverStarted = true; + int port = server.getPort(); + String targetAddress = "127.0.0.1:" + port; + var channelFactory = new GrpcChannelFactory(); + gameSessionChannel = + channelFactory.buildChannel( + targetAddress, + port, + pki.clientProperties(pkiDirectory, pki.identity("game-session-client")), + false); + var stub = + AccountGameplayAdmissionLeaseServiceGrpc.newBlockingStub(gameSessionChannel) + .withMaxInboundMessageSize( + AccountGameplayAdmissionLeaseGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(ACCOUNT_WORKLOAD)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(ACCOUNT_WORKLOAD)); + + wrongRoleChannel = + channelFactory.buildChannel( + targetAddress, + port, + pki.clientProperties(pkiDirectory, pki.identity("wrong-role-client")), + false); + var wrongRoleStub = + AccountGameplayAdmissionLeaseServiceGrpc.newBlockingStub(wrongRoleChannel) + .withMaxInboundMessageSize( + AccountGameplayAdmissionLeaseGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(ACCOUNT_WORKLOAD)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(ACCOUNT_WORKLOAD)); + UUID accountId = fixture.account.getAccountUuid(); + var sourceImageBeforeAnyRpc = fixture.sourceAndIssuanceImageForAuthenticatedAcquire(); + var allocatorBeforeAnyRpc = fixture.leaseAllocationState(accountRequestId, accountId); + assertThat(allocatorBeforeAnyRpc).isEqualTo(new LeaseAllocationState(0L, 0L, null, null)); + assertThatThrownBy( + () -> + wrongRoleStub + .withDeadlineAfter(5, TimeUnit.SECONDS) + .acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest.getDefaultInstance())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThatThrownBy( + () -> + ClientCalls.blockingUnaryCall( + wrongRoleStub.getChannel(), + malformedAcquireMethod(), + wrongRoleStub.getCallOptions().withDeadlineAfter(5, TimeUnit.SECONDS), + new byte[] {0x0f})) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThat(fixture.leaseOperationCount()).isZero(); + assertThat(fixture.leaseAllocationState(accountRequestId, accountId)) + .isEqualTo(allocatorBeforeAnyRpc); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAnyRpc); + + var sourceImageBeforeAcquire = fixture.sourceAndIssuanceImageForAuthenticatedAcquire(); + var sourceImageBeforeFreshCommit = fixture.sourceAndIssuanceImageForAuthenticatedCommit(); + var allocatorBeforeAcquire = fixture.leaseAllocationState(accountRequestId, accountId); + assertThat(allocatorBeforeAcquire).isEqualTo(new LeaseAllocationState(0L, 0L, null, null)); + var acquireWire = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + accountRequestId, originalJwt, candidate, target, BigInteger.ONE); + var parsedAcquire = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(acquireWire); + var firstResponse = + stub.withDeadlineAfter(5, TimeUnit.SECONDS).acquireGameplayAdmissionLease(acquireWire); + var first = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + parsedAcquire, firstResponse); + assertThat(first.state()).isEqualTo(State.PENDING); + AccountGameplayAdmissionLeaseEvidence originalLease = first.originalLeaseEvidence(); + byte[] originalLeaseBytes = originalLease.canonicalJson().getBytes(StandardCharsets.UTF_8); + UUID originalLeaseRequestId = + UUID.fromString((String) originalLease.carrier().get("requestId")); + UUID originalLeaseId = UUID.fromString((String) originalLease.carrier().get("leaseId")); + long originalFence = originalLease.leaseFence().longValueExact(); + assertThat(originalLeaseRequestId).isEqualTo(accountRequestId); + var allocationAfterAcquire = + fixture.leaseAllocationState(originalLeaseRequestId, accountId); + assertThat(allocationAfterAcquire.allocationCount()).isEqualTo(1L); + assertThat(allocationAfterAcquire.fenceCount()).isEqualTo(1L); + assertThat(allocationAfterAcquire.allocation()) + .isEqualTo( + new LeaseAllocationRow( + accountId, accountRequestId, originalLeaseId, originalFence)); + assertThat(allocationAfterAcquire.fence()) + .isEqualTo(new LeaseFenceRow(accountId, originalFence)); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAcquire); + + var retryResponse = + stub.withDeadlineAfter(5, TimeUnit.SECONDS).acquireGameplayAdmissionLease(acquireWire); + var retry = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + parsedAcquire, retryResponse); + assertThat(retry.state()).isEqualTo(State.PENDING); + assertThat(retry.originalLeaseEvidence().canonicalJson()) + .isEqualTo(originalLease.canonicalJson()); + assertThat(fixture.leaseAllocationState(originalLeaseRequestId, accountId)) + .isEqualTo(allocationAfterAcquire); + assertThat(fixture.leaseOperationCount()).isEqualTo(1L); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAcquire); + + var readPendingWire = + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(originalJwt, originalLeaseBytes); + var parsedReadPending = + AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(readPendingWire); + var readPendingResponse = + stub.withDeadlineAfter(5, TimeUnit.SECONDS).readGameplayAdmissionLease(readPendingWire); + var readPending = + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( + parsedReadPending, readPendingResponse); + assertThat(readPending.state()).isEqualTo(State.PENDING); + assertThat(readPending.originalLeaseEvidence().canonicalJson()) + .isEqualTo(originalLease.canonicalJson()); + + UUID decisionId = UUID.randomUUID(); + var finalizeWire = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest( + originalJwt, originalLeaseBytes, decisionId); + var parsedFinalize = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(finalizeWire); + var finalizedResponse = + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .finalizeGameplayAdmissionLease(finalizeWire); + var finalized = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( + parsedFinalize, finalizedResponse); + assertThat(finalized.state()).isEqualTo(State.COMMITTED); + assertThat(finalized.bindingDecisionId()).isEqualTo(decisionId); + var originalAck = finalized.originalAckReceipt(); + assertThat(originalAck).isNotNull(); + assertThat(originalAck.requestId()).isEqualTo(accountRequestId); + assertThat(originalAck.accountId()).isEqualTo(accountId); + assertThat(originalAck.leaseId()).isEqualTo(originalLeaseId); + assertThat(originalAck.leaseFence()).isEqualTo(originalFence); + assertThat(originalAck.bindingDecisionId()).isEqualTo(decisionId); + assertThat(originalAck.committedBeforeMs()) + .isPositive() + .isLessThan(originalAck.expiresAtMs()); + assertThat(originalAck.finalizationXid()).matches("[1-9][0-9]{0,19}"); + assertThat(originalAck.receiptXid()).matches("[1-9][0-9]{0,19}"); + assertThat(originalAck.receiptXid()).isNotEqualTo(originalAck.finalizationXid()); + assertThat(fixture.readLeaseOperation(originalLease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + assertThat(fixture.leaseAllocationState(originalLeaseRequestId, accountId)) + .isEqualTo(allocationAfterAcquire); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedCommit()) + .isEqualTo(sourceImageBeforeFreshCommit); + assertThat(fixture.originalAckReceiptImage(accountRequestId)) + .isEqualTo( + List.of( + (short) 1, + accountRequestId, + accountId, + originalLeaseId, + originalFence, + originalLease.sha256(), + decisionId, + originalAck.expiresAtMs(), + originalAck.finalizationXid(), + originalAck.committedBeforeMs(), + originalAck.receiptXid())); + var durableReceiptImage = fixture.originalAckReceiptImage(accountRequestId); + + // PostgreSQL 18 supports the fresh receipt COMMIT above. Retained receipt reads + // intentionally + // remain on their PG16 contract, so these genuine owner calls must fail closed without + // restamping or replacing the committed operation and its durable original receipt. + assertThatThrownBy( + () -> + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .finalizeGameplayAdmissionLease(finalizeWire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + var readCommittedWire = + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(originalJwt, originalLeaseBytes); + assertThatThrownBy( + () -> + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .readGameplayAdmissionLease(readCommittedWire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + var abortCommittedWire = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortRequest( + originalJwt, originalLeaseBytes, decisionId); + assertThatThrownBy( + () -> + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .abortGameplayAdmissionLease(abortCommittedWire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(fixture.readLeaseOperation(originalLease).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + assertThat(fixture.originalAckReceiptImage(accountRequestId)) + .isEqualTo(durableReceiptImage); + assertThat(fixture.leaseAllocationState(originalLeaseRequestId, accountId)) + .isEqualTo(allocationAfterAcquire); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedCommit()) + .isEqualTo(sourceImageBeforeFreshCommit); + + UUID abortRequestId = UUID.randomUUID(); + var abortPublished = controlledPublishedTarget(candidate, target, abortRequestId); + when(decisionClient.readPublishedRealmAdmissionOwner(eq(abortPublished.selector()))) + .thenReturn(abortPublished); + var allocatorBeforeAbort = fixture.leaseAllocationState(abortRequestId, accountId); + var sourceImageBeforeAbort = fixture.sourceAndIssuanceImageForAuthenticatedAcquire(); + assertThat(allocatorBeforeAbort) + .isEqualTo(new LeaseAllocationState(1L, 1L, null, new LeaseFenceRow(accountId, 1L))); + var abortAcquireWire = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + abortRequestId, originalJwt, candidate, target, BigInteger.ONE); + var parsedAbortAcquire = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(abortAcquireWire); + var abortAcquireResponse = + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .acquireGameplayAdmissionLease(abortAcquireWire); + var abortAcquire = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + parsedAbortAcquire, abortAcquireResponse); + assertThat(abortAcquire.state()).isEqualTo(State.PENDING); + AccountGameplayAdmissionLeaseEvidence abortedLease = abortAcquire.originalLeaseEvidence(); + UUID abortedLeaseId = UUID.fromString((String) abortedLease.carrier().get("leaseId")); + long abortedLeaseFence = abortedLease.leaseFence().longValueExact(); + byte[] abortedLeaseBytes = abortedLease.canonicalJson().getBytes(StandardCharsets.UTF_8); + var allocationAfterAbortAcquire = fixture.leaseAllocationState(abortRequestId, accountId); + assertThat(allocationAfterAbortAcquire.allocationCount()).isEqualTo(2L); + assertThat(allocationAfterAbortAcquire.fenceCount()).isEqualTo(1L); + assertThat(allocationAfterAbortAcquire.allocation()) + .isEqualTo( + new LeaseAllocationRow( + accountId, abortRequestId, abortedLeaseId, abortedLeaseFence)); + assertThat(allocationAfterAbortAcquire.fence()).isEqualTo(new LeaseFenceRow(accountId, 2L)); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAbort); + + var abortWire = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortRequest( + originalJwt, abortedLeaseBytes, null); + var parsedAbort = AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(abortWire); + var abortedResponse = + stub.withDeadlineAfter(5, TimeUnit.SECONDS).abortGameplayAdmissionLease(abortWire); + var aborted = + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortResponse(parsedAbort, abortedResponse); + assertThat(aborted.state()).isEqualTo(State.ABORTED); + assertThat(aborted.bindingDecisionId()).isNull(); + assertThat(aborted.orphanCleanupId()).isNotNull(); + assertThat(aborted.originalLeaseEvidence().canonicalJson()) + .isEqualTo(abortedLease.canonicalJson()); + var retainedAbortBeforeFinalize = fixture.readLeaseOperation(abortedLease); + assertThat(retainedAbortBeforeFinalize.state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.ABORTED); + assertThat(retainedAbortBeforeFinalize.orphanCleanupId()) + .isEqualTo(aborted.orphanCleanupId()); + UUID abortDecisionId = UUID.randomUUID(); + AtomicInteger abortDecisionReads = new AtomicInteger(); + doAnswer( + invocation -> { + abortDecisionReads.incrementAndGet(); + throw Status.UNAVAILABLE + .withDescription("Aborted Game Session decision is no longer readable") + .asRuntimeException(); + }) + .when(decisionClient) + .read(eq(abortDecisionId), any()); + var abortFinalizeWire = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest( + originalJwt, abortedLeaseBytes, abortDecisionId); + var parsedAbortFinalize = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(abortFinalizeWire); + long operationCountBeforeAbortFinalize = fixture.leaseOperationCount(); + var allocatorBeforeAbortFinalize = fixture.leaseAllocationState(abortRequestId, accountId); + var sourceImageBeforeAbortFinalize = + fixture.sourceAndIssuanceImageForAuthenticatedAcquire(); + var abortedFinalizeResponse = + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .finalizeGameplayAdmissionLease(abortFinalizeWire); + var abortedFinalize = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( + parsedAbortFinalize, abortedFinalizeResponse); + assertThat(abortedFinalize.state()).isEqualTo(State.ABORTED); + assertThat(abortedFinalize.bindingDecisionId()).isNull(); + assertThat(abortedFinalize.orphanCleanupId()).isEqualTo(aborted.orphanCleanupId()); + assertThat(abortedFinalize.originalAckReceipt()).isNull(); + assertThat(abortedFinalize.originalLeaseEvidence().canonicalJson()) + .isEqualTo(abortedLease.canonicalJson()); + assertThat(abortDecisionReads.get()).isZero(); + assertThat(fixture.readLeaseOperation(abortedLease)).isEqualTo(retainedAbortBeforeFinalize); + assertThat(fixture.leaseOperationCount()).isEqualTo(operationCountBeforeAbortFinalize); + assertThat(fixture.leaseAllocationState(abortRequestId, accountId)) + .isEqualTo(allocatorBeforeAbortFinalize); + assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) + .isEqualTo(sourceImageBeforeAbortFinalize); + + TokenIdentity tokenIdentity = fixture.tokenIdentity(fixture.committedCandidate); + UUID revocationRequestId = UUID.randomUUID(); + fixture.inSerializableTransaction( + () -> + fixture.tokenFences.beginRevocationIntent( + tokenIdentity, + revocationRequestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + tokenIdentity, revocationRequestId))); + assertThatThrownBy( + () -> + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .finalizeGameplayAdmissionLease(abortFinalizeWire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(abortDecisionReads.get()).isZero(); + assertThat(fixture.readLeaseOperation(abortedLease)).isEqualTo(retainedAbortBeforeFinalize); + assertThat(fixture.leaseOperationCount()).isEqualTo(operationCountBeforeAbortFinalize); + assertThat(fixture.leaseAllocationState(abortRequestId, accountId)) + .isEqualTo(allocatorBeforeAbortFinalize); + } finally { + if (wrongRoleChannel != null) { + wrongRoleChannel.shutdownNow(); + assertThat(wrongRoleChannel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + if (gameSessionChannel != null) { + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + if (serverStarted) { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + + @Test + void tenantEntitlementWriterWaitsForCurrentSourceLocksUntilOriginalPhysicalCommit() + throws Exception { + Fixture fixture = newFixture(); + PreparedAdmission prepared = fixture.prepareAdmission(); + DemoTenantEntitlementSnapshot currentEntitlement = fixture.readCurrentEntitlement(); + CandidateRow candidateBefore = fixture.readCandidateRow(prepared.candidate()); + UUID decisionId = UUID.randomUUID(); + CountDownLatch originalCommitReached = new CountDownLatch(1); + CountDownLatch allowOriginalCommit = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + CountDownLatch writerCompleted = new CountDownLatch(1); + AtomicInteger originalBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + var commitBarrierDataSource = + holdOriginalCommitBeforePhysicalCommit( + fixture.dataSource, originalCommitReached, allowOriginalCommit, originalBackendPid); + + try { + Future + originalCommit = + executor.submit( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) + .executeWithCurrentSources( + prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); + assertThat(originalCommitReached.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(originalBackendPid.get()).isPositive(); + + Future tenantWriter = + executor.submit( + () -> { + writerStarted.countDown(); + try { + fixture.disableTenantGameplay(currentEntitlement); + return null; + } finally { + writerCompleted.countDown(); + } + }); + assertThat(writerStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + int blockedWriterPid = + awaitBackendBlockedBy(fixture.dsl, originalBackendPid.get(), 3, TimeUnit.SECONDS); + assertThat(blockedWriterPid).isPositive(); + assertThat(blockedWriterPid).isNotEqualTo(originalBackendPid.get()); + assertThat(tenantWriter.isDone()).isFalse(); + assertThat(writerCompleted.getCount()).isEqualTo(1L); + + allowOriginalCommit.countDown(); + var acknowledgement = originalCommit.get(5, TimeUnit.SECONDS); + assertThat(acknowledgement.evidence()).isEqualTo(prepared.lease()); + assertThat(acknowledgement.decisionId()).isEqualTo(decisionId); + assertThat(acknowledgement.committedBeforeMs()) + .isLessThan(Long.parseLong((String) prepared.lease().carrier().get("expiresAt"))); + tenantWriter.get(5, TimeUnit.SECONDS); + assertThat(writerCompleted.getCount()).isZero(); + + assertThat(fixture.readLeaseOperation(prepared.lease()).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + DemoTenantEntitlementSnapshot disabled = fixture.readCurrentEntitlement(); + assertThat(disabled.tenantAuthorityGeneration()) + .isGreaterThan(currentEntitlement.tenantAuthorityGeneration()); + assertThat(disabled.gameplayAvailable()).isFalse(); + assertThat(disabled.allowNewGameplayBindings()).isFalse(); + assertThat(fixture.readCandidateRow(prepared.candidate())) + .usingRecursiveComparison() + .isEqualTo(candidateBefore); + } finally { + allowOriginalCommit.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); + } + } + + @Test + void accountAuthorityWriterWaitsForOriginalPhysicalCommitAndInvalidatesOldLease() + throws Exception { + Fixture fixture = newFixture(); + PreparedAdmission prepared = fixture.prepareAdmission(); + CandidateRow candidateBefore = fixture.readCandidateRow(prepared.candidate()); + CountDownLatch originalCommitReached = new CountDownLatch(1); + CountDownLatch allowOriginalCommit = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + CountDownLatch writerCompleted = new CountDownLatch(1); + AtomicInteger originalBackendPid = new AtomicInteger(); + UUID decisionId = UUID.randomUUID(); + ExecutorService executor = Executors.newFixedThreadPool(2); + var commitBarrierDataSource = + holdOriginalCommitBeforePhysicalCommit( + fixture.dataSource, originalCommitReached, allowOriginalCommit, originalBackendPid); + + try { + Future + originalCommit = + executor.submit( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) + .executeWithCurrentSources( + prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); + assertThat(originalCommitReached.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(originalBackendPid.get()).isPositive(); + + Future accountWriter = + executor.submit( + () -> { + writerStarted.countDown(); + try { + fixture.inSerializableTransaction( + () -> { + Account updated = + fixture.accounts.findById(fixture.account.getId()).orElseThrow(); + updated.setPasswordHash("authority-writer-updated-password-hash"); + fixture.accounts.save(updated); + return null; + }); + return null; + } finally { + writerCompleted.countDown(); + } + }); + assertThat(writerStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + int blockedWriterPid = + awaitBackendBlockedBy(fixture.dsl, originalBackendPid.get(), 3, TimeUnit.SECONDS); + assertThat(blockedWriterPid).isPositive(); + assertThat(blockedWriterPid).isNotEqualTo(originalBackendPid.get()); + assertThat(accountWriter.isDone()).isFalse(); + assertThat(writerCompleted.getCount()).isEqualTo(1L); + + allowOriginalCommit.countDown(); + var acknowledgement = originalCommit.get(5, TimeUnit.SECONDS); + assertThat(acknowledgement.evidence()).isEqualTo(prepared.lease()); + assertThat(acknowledgement.evidence().canonicalJson()) + .isEqualTo(prepared.lease().canonicalJson()); + assertThat(acknowledgement.decisionId()).isEqualTo(decisionId); + assertThat(acknowledgement.finalizationXid()).matches("[1-9][0-9]{0,19}"); + assertThat(acknowledgement.committedBeforeMs()) + .isLessThan(Long.parseLong((String) prepared.lease().carrier().get("expiresAt"))); + accountWriter.get(5, TimeUnit.SECONDS); + assertThat(writerCompleted.getCount()).isZero(); + + assertThat(fixture.accounts.findById(fixture.account.getId()).orElseThrow().getPasswordHash()) + .isEqualTo("authority-writer-updated-password-hash"); + assertThat(fixture.readCandidateRow(prepared.candidate())) + .usingRecursiveComparison() + .isEqualTo(candidateBefore); + assertThat(fixture.readLeaseOperation(prepared.lease()).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + assertThatThrownBy(() -> fixture.readCurrent(prepared.candidate())) + .isInstanceOf(IllegalStateException.class); + } finally { + allowOriginalCommit.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); + } + } + + @Test + void tokenRevocationWriterWaitsForOriginalPhysicalCommitAndInvalidatesOldLease() + throws Exception { + Fixture fixture = newFixture(); + PreparedAdmission prepared = fixture.prepareAdmission(); + CandidateRow candidateBefore = fixture.readCandidateRow(prepared.candidate()); + TokenIdentity identity = fixture.tokenIdentity(prepared.candidate()); + UUID revocationRequestId = UUID.randomUUID(); + CountDownLatch originalCommitReached = new CountDownLatch(1); + CountDownLatch allowOriginalCommit = new CountDownLatch(1); + CountDownLatch writerStarted = new CountDownLatch(1); + CountDownLatch writerCompleted = new CountDownLatch(1); + AtomicInteger originalBackendPid = new AtomicInteger(); + AtomicReference revocation = new AtomicReference<>(); + UUID decisionId = UUID.randomUUID(); + ExecutorService executor = Executors.newFixedThreadPool(2); + var commitBarrierDataSource = + holdOriginalCommitBeforePhysicalCommit( + fixture.dataSource, originalCommitReached, allowOriginalCommit, originalBackendPid); + + try { + Future + originalCommit = + executor.submit( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) + .executeWithCurrentSources( + prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); + assertThat(originalCommitReached.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(originalBackendPid.get()).isPositive(); + + Future tokenWriter = + executor.submit( + () -> { + writerStarted.countDown(); + try { + revocation.set( + fixture.inSerializableTransaction( + () -> + fixture.tokenFences.beginRevocationIntent( + identity, + revocationRequestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, revocationRequestId)))); + return null; + } finally { + writerCompleted.countDown(); + } + }); + assertThat(writerStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + int blockedWriterPid = + awaitBackendBlockedBy(fixture.dsl, originalBackendPid.get(), 3, TimeUnit.SECONDS); + assertThat(blockedWriterPid).isPositive(); + assertThat(blockedWriterPid).isNotEqualTo(originalBackendPid.get()); + assertThat(tokenWriter.isDone()).isFalse(); + assertThat(writerCompleted.getCount()).isEqualTo(1L); + + allowOriginalCommit.countDown(); + var acknowledgement = originalCommit.get(5, TimeUnit.SECONDS); + assertThat(acknowledgement.evidence()).isEqualTo(prepared.lease()); + assertThat(acknowledgement.evidence().canonicalJson()) + .isEqualTo(prepared.lease().canonicalJson()); + assertThat(acknowledgement.decisionId()).isEqualTo(decisionId); + assertThat(acknowledgement.finalizationXid()).matches("[1-9][0-9]{0,19}"); + assertThat(acknowledgement.committedBeforeMs()) + .isLessThan(Long.parseLong((String) prepared.lease().carrier().get("expiresAt"))); + tokenWriter.get(5, TimeUnit.SECONDS); + assertThat(writerCompleted.getCount()).isZero(); + + assertThat(revocation.get()).isNotNull(); + assertThat(revocation.get().state()) + .isEqualTo(AccountGameplayTokenIdentityFence.State.PENDING); + assertThat(revocation.get().tokenIdentityFence()).isEqualTo(2L); + assertThat(fixture.readCandidateRow(prepared.candidate())) + .usingRecursiveComparison() + .isEqualTo(candidateBefore); + assertThat(fixture.readLeaseOperation(prepared.lease()).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED); + assertThatThrownBy(() -> fixture.readCurrent(prepared.candidate())) + .isInstanceOf(IllegalStateException.class); + } finally { + allowOriginalCommit.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow(); + } + } + + @Test + void tenantEntitlementOwnerUpdateRefusesRetainedOriginalLeaseWithoutChangingIssuance() + throws Exception { + Fixture fixture = newFixture(); + PreparedAdmission prepared = fixture.prepareAdmission(); + CandidateRow retainedCandidateBefore = fixture.readCandidateRow(prepared.candidate()); + + DemoTenantEntitlementSnapshot active = fixture.readCurrentEntitlement(); + fixture.disableTenantGameplay(active); + DemoTenantEntitlementSnapshot disabled = fixture.readCurrentEntitlement(); + assertThat(disabled.gameplayAvailable()).isFalse(); + assertThat(disabled.allowNewGameplayBindings()).isFalse(); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) + .executeWithCurrentSources( + prepared.lease(), UUID.randomUUID(), TEST_NAMESPACE, prepared.candidate())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("membership source tenantAuthorityGeneration current equality"); + + assertThat(fixture.readCandidateRow(prepared.candidate())) + .usingRecursiveComparison() + .isEqualTo(retainedCandidateBefore); + assertThat(fixture.readLeaseOperation(prepared.lease()).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + } + + @Test + void changedSqlTokenIdentityFenceRefusesRetainedOriginalLeaseAndCommittedCandidate() + throws Exception { + Fixture fixture = newFixture(); + PreparedAdmission prepared = fixture.prepareAdmission(); + CandidateRow retainedCandidateBefore = fixture.readCandidateRow(prepared.candidate()); + TokenIdentity identity = fixture.tokenIdentity(prepared.candidate()); + UUID revocationRequestId = UUID.randomUUID(); + var pendingRevocation = + fixture.inSerializableTransaction( + () -> + fixture.tokenFences.beginRevocationIntent( + identity, + revocationRequestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, revocationRequestId))); + assertThat(pendingRevocation.state()) + .isEqualTo(AccountGameplayTokenIdentityFence.State.PENDING); + assertThat(pendingRevocation.tokenIdentityFence()).isEqualTo(2L); + + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) + .executeWithCurrentSources( + prepared.lease(), UUID.randomUUID(), TEST_NAMESPACE, prepared.candidate())) + .isInstanceOf(IllegalStateException.class); + + assertThat(fixture.readCandidateRow(prepared.candidate())) + .usingRecursiveComparison() + .isEqualTo(retainedCandidateBefore); + assertThat(fixture.readLeaseOperation(prepared.lease()).state()) + .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); + } + + private Fixture newFixture() throws Exception { + return newFixture(null); + } + + private Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exception { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + if (schema.length() > 63) throw new IllegalStateException("Generated schema name is too long"); + runOwnedSchemas.add(schema); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); + return new Fixture(schema, dataSource, dsl, manager, temporaryDirectory, redisClient); + } + + private static int awaitBackendBlockedBy( + DSLContext observerDsl, int blockingBackendPid, long timeout, TimeUnit unit) + throws InterruptedException { + long deadline = System.nanoTime() + unit.toNanos(timeout); + do { + Record waiter = + observerDsl.fetchOne( + "SELECT pid FROM pg_stat_activity WHERE datname = current_database() " + + "AND pid <> pg_backend_pid() AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)) AND query LIKE '%account_%' " + + "ORDER BY pid LIMIT 1", + blockingBackendPid); + if (waiter != null) return waiter.get("pid", Integer.class); + Thread.sleep(10); + } while (System.nanoTime() < deadline); + return -1; + } + + private static DataSource holdOriginalCommitBeforePhysicalCommit( + DataSource delegate, + CountDownLatch commitReached, + CountDownLatch allowCommit, + AtomicInteger backendPid) { + return new DelegatingDataSource(delegate) { + @SuppressFBWarnings( + value = "ODR_OPEN_DATABASE_RESOURCE", + justification = + "The returned proxy owns this physical connection and delegates close; " + + "construction failure closes the connection before rethrowing.") + @Override + public Connection getConnection() throws SQLException { + Connection physical = super.getConnection(); + try { + return (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("commit") && method.getParameterCount() == 0) { + backendPid.set( + DSL.using(physical, SQLDialect.POSTGRES) + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + commitReached.countDown(); + try { + if (!allowCommit.await(5, TimeUnit.SECONDS)) { + throw new SQLException( + "Original COMMIT barrier was not released", "57014"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new SQLException( + "Original COMMIT barrier was interrupted", interrupted); + } + } + if (method.getName().equals("close") && method.getParameterCount() == 0) { + physical.close(); + return null; + } + try { + return method.invoke(physical, arguments); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + }); + } catch (RuntimeException | Error constructionFailure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + constructionFailure.addSuppressed(closeFailure); + } + throw constructionFailure; + } + } + }; + } + + private static DataSource captureAdmissionClockReads( + DataSource delegate, AdmissionClockCapture capture) { + DelegatingDataSource recordingDataSource = + new DelegatingDataSource(delegate) { + @SuppressFBWarnings( + value = "ODR_OPEN_DATABASE_RESOURCE", + justification = + "The returned proxy owns this physical connection and delegates close; " + + "construction failure closes the connection before rethrowing.") + @Override + public Connection getConnection() throws SQLException { + Connection physical = super.getConnection(); + try { + return (Connection) + java.lang.reflect.Proxy.newProxyInstance( + Connection.class.getClassLoader(), + new Class[] {Connection.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("prepareStatement") + && arguments != null + && arguments.length > 0 + && arguments[0] instanceof String sql) { + PreparedStatement statement = + (PreparedStatement) invokeJdbc(method, physical, arguments); + Connection enlistedConnection = (Connection) proxy; + if (isAdmissionDatabaseClockQuery(sql)) { + capture.clockConnection.set(enlistedConnection); + capture.clockReadUsedEnlistedConnection.set( + isEnlistedConnection(capture.dataSource, enlistedConnection)); + return captureClockResult(statement, capture); + } + if (isAdmissionLeaseInsert(sql)) { + capture.operationInsertConnection.set(enlistedConnection); + capture.operationInsertUsedEnlistedConnection.set( + isEnlistedConnection(capture.dataSource, enlistedConnection)); + } + return statement; + } + if (method.getName().equals("createStatement")) { + Statement statement = (Statement) invokeJdbc(method, physical, arguments); + return captureClockStatement(statement, (Connection) proxy, capture); + } + return invokeJdbc(method, physical, arguments); + }); + } catch (RuntimeException | Error constructionFailure) { + try { + physical.close(); + } catch (SQLException closeFailure) { + constructionFailure.addSuppressed(closeFailure); + } + throw constructionFailure; + } + } + }; + capture.dataSource = recordingDataSource; + return recordingDataSource; + } + + private static PreparedStatement captureClockResult( + PreparedStatement statement, AdmissionClockCapture capture) { + AtomicBoolean clockResultPending = new AtomicBoolean(); + return (PreparedStatement) + java.lang.reflect.Proxy.newProxyInstance( + PreparedStatement.class.getClassLoader(), + new Class[] {PreparedStatement.class}, + (proxy, method, arguments) -> { + Object result = invokeJdbc(method, statement, arguments); + if (method.getName().equals("executeQuery") && result instanceof ResultSet rows) { + return captureClockRows(rows, capture); + } + if (method.getName().equals("execute") && Boolean.TRUE.equals(result)) { + clockResultPending.set(true); + } + if (method.getName().equals("getResultSet") + && clockResultPending.getAndSet(false) + && result instanceof ResultSet rows) { + return captureClockRows(rows, capture); + } + return result; + }); + } + + private static Statement captureClockStatement( + Statement statement, Connection connection, AdmissionClockCapture capture) { + AtomicBoolean clockResultPending = new AtomicBoolean(); + return (Statement) + java.lang.reflect.Proxy.newProxyInstance( + Statement.class.getClassLoader(), + new Class[] {Statement.class}, + (proxy, method, arguments) -> { + boolean clockQuery = false; + if (arguments != null + && arguments.length > 0 + && arguments[0] instanceof String sql + && method.getName().startsWith("execute")) { + clockQuery = isAdmissionDatabaseClockQuery(sql); + if (clockQuery) { + capture.clockConnection.set(connection); + capture.clockReadUsedEnlistedConnection.set( + isEnlistedConnection(capture.dataSource, connection)); + } else if (isAdmissionLeaseInsert(sql)) { + capture.operationInsertConnection.set(connection); + capture.operationInsertUsedEnlistedConnection.set( + isEnlistedConnection(capture.dataSource, connection)); + } + } + Object result = invokeJdbc(method, statement, arguments); + if (clockQuery && result instanceof ResultSet rows) { + return captureClockRows(rows, capture); + } + if (clockQuery && method.getName().equals("execute") && Boolean.TRUE.equals(result)) { + clockResultPending.set(true); + } + if (method.getName().equals("getResultSet") + && clockResultPending.getAndSet(false) + && result instanceof ResultSet rows) { + return captureClockRows(rows, capture); + } + return result; + }); + } + + private static ResultSet captureClockRows(ResultSet rows, AdmissionClockCapture capture) { + return (ResultSet) + java.lang.reflect.Proxy.newProxyInstance( + ResultSet.class.getClassLoader(), + new Class[] {ResultSet.class}, + (proxy, method, arguments) -> { + Object value = invokeJdbc(method, rows, arguments); + boolean columnRead = + method.getName().startsWith("get") + && arguments != null + && arguments.length > 0 + && (arguments[0] instanceof Integer || arguments[0] instanceof String); + if (columnRead && value instanceof Number number) { + capture.databaseMillis.set(number.longValue()); + } else if (columnRead + && value instanceof String text + && text.matches("[1-9][0-9]*")) { + capture.databaseMillis.set(Long.parseLong(text)); + } + return value; + }); + } + + private static boolean isAdmissionDatabaseClockQuery(String sql) { + return sql.toLowerCase(Locale.ROOT) + .replaceAll("\\s+", "") + .startsWith("selectfloor(extract(epochfromclock_timestamp())*1000)::bigint"); + } + + private static boolean isAdmissionLeaseInsert(String sql) { + String normalizedSql = sql.toLowerCase(Locale.ROOT).replaceAll("\\s+", ""); + return normalizedSql.startsWith("insert") + && normalizedSql.contains("account_gameplay_admission_lease_operations"); + } + + private static boolean isEnlistedConnection(DataSource dataSource, Connection connection) { + Object resource = TransactionSynchronizationManager.getResource(dataSource); + return resource instanceof ConnectionHolder holder && holder.getConnection() == connection; + } + + private static Object invokeJdbc( + java.lang.reflect.Method method, Object target, Object[] arguments) throws Throwable { + try { + return method.invoke(target, arguments); + } catch (java.lang.reflect.InvocationTargetException failure) { + throw failure.getCause(); + } + } + + private static final class AdmissionClockCapture { + private final AtomicLong databaseMillis = new AtomicLong(); + private final AtomicReference clockConnection = new AtomicReference<>(); + private final AtomicReference operationInsertConnection = new AtomicReference<>(); + private final AtomicBoolean clockReadUsedEnlistedConnection = new AtomicBoolean(); + private final AtomicBoolean operationInsertUsedEnlistedConnection = new AtomicBoolean(); + private DataSource dataSource; + } + + private static Candidate admissionCandidate(Fixture fixture) { + var identity = fixture.committedCandidate.identity(); + var authority = fixture.committedCandidate.authoritySnapshot(); + return new Candidate( + identity.accountId(), + fixture.tenantUuid, + UUID.randomUUID(), + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 71L, + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + ACCOUNT_ISSUER, + BigInteger.valueOf(authority.issuerGeneration()), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + } + + private static Candidate candidateWithAccount(Candidate candidate, UUID accountId) { + return new Candidate( + accountId, + candidate.tenantId(), + candidate.playableStateNamespaceId(), + candidate.characterId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + candidate.sessionId(), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + candidate.issuerIndexPartitionCapacity()); + } + + private static Target admissionTarget(Candidate candidate, UUID requestId) { + UUID realmId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID holdId = UUID.randomUUID(); + UUID holdFence = UUID.randomUUID(); + long catalogRevision = 1L; + long pointerVersion = 1L; + long activeWorldEpoch = 1L; + String requestDigest = "c".repeat(64); + String pointerDigest = "d".repeat(64); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + TEST_NAMESPACE, + candidate.tenantId(), + "world", + realmId, + candidate.playableStateNamespaceId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + versionId, + activeWorldEpoch, + requestId.toString(), + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + catalogRevision, + null); + var hold = new WorldCanonicalInitialAdmissionHold.HoldIdentity(holdRequest, holdId, holdFence); + return new Target( + TEST_NAMESPACE, + "tenant", + candidate.tenantId(), + "world", + "World", + realmId, + "realm", + "Realm", + 11L, + candidate.runtimeGameInstanceId(), + candidate.playableStateNamespaceId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + versionId, + 99L, + catalogRevision, + pointerVersion, + pointerDigest, + activeWorldEpoch, + requestId.toString(), + requestDigest, + OriginKind.NO_PRIOR_POINTER, + null, + holdId, + holdFence, + hold.holdBindingDigest(), + 101L, + "sha256:" + "a".repeat(64), + OwnerProofOutcome.COMMITTED, + false, + Instant.parse("2026-10-25T00:00:00Z"), + "PRESEEDED_ONLY"); + } + + private static CanonicalGameplayAdmissionDecisionReadClient controlledPublishedTargetClient( + Candidate candidate, Target target, UUID requestId) { + var published = controlledPublishedTarget(candidate, target, requestId); + var decisionClient = mock(CanonicalGameplayAdmissionDecisionReadClient.class); + when(decisionClient.readPublishedRealmAdmissionOwner(any())).thenReturn(published); + return decisionClient; + } + + private static PublishedRealmEvidence controlledPublishedTarget( + Candidate candidate, Target target, UUID requestId) { + var selector = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + requestId, + candidate.accountId(), + TEST_NAMESPACE, + target.canonicalTenantId(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.catalogRevision(), + target.pointerVersion(), + target.activeWorldEpoch()); + var published = mock(PublishedRealmEvidence.class); + when(published.selector()).thenReturn(selector); + when(published.currentTarget()).thenReturn(target); + return published; + } + + private static void controlProvisionalDecisionRead( + CanonicalGameplayAdmissionDecisionReadClient decisionClient, + Candidate candidate, + Target target) { + when(decisionClient.read(any(), any())) + .thenAnswer( + invocation -> { + UUID decisionId = invocation.getArgument(0); + AccountGameplayAdmissionLeaseEvidence expectedLease = invocation.getArgument(1); + var wireRead = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toRequest( + decisionId, expectedLease); + var parsedRead = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(wireRead); + var controlledWireEvidence = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + parsedRead, + decisionId, + expectedLease, + BigInteger.ONE, + null, + null, + candidate, + target); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromResponse( + parsedRead, controlledWireEvidence); + }); + } + + private static MethodDescriptor + malformedAcquireMethod() { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName( + AccountGameplayAdmissionLeaseServiceGrpc.getAcquireGameplayAdmissionLeaseMethod() + .getFullMethodName()) + .setRequestMarshaller( + new MethodDescriptor.Marshaller() { + @Override + public InputStream stream(byte[] value) { + return new ByteArrayInputStream(value); + } + + @Override + public byte[] parse(InputStream value) { + throw new UnsupportedOperationException("Request-only raw test marshaller"); + } + }) + .setResponseMarshaller( + AccountGameplayAdmissionLeaseServiceGrpc.getAcquireGameplayAdmissionLeaseMethod() + .getResponseMarshaller()) + .build(); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable invocation) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + + private static Map expectedLeaseSourceFields( + Fixture fixture, AccountGameplayAdmissionCurrentSources.Current current) { + var snapshot = current.snapshot(); + var candidate = current.currentCommittedCandidate(); + var tuple = snapshot.authorityTuple(); + Optional accountCutoff = + tuple + .accountSecurityCutoff() + .map( + cutoff -> + new AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); + Map authorityTuple = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple( + Long.parseLong(tuple.issuerAuthGeneration()), + Long.parseLong(tuple.accountAuthorityGeneration()), + accountCutoff)); + authorityTuple.put("tenantAuthorityGeneration", tuple.tenantAuthorityGeneration()); + authorityTuple.put("membershipAuthorityGeneration", tuple.membershipAuthorityGeneration()); + authorityTuple.put("privateRealmGrantVersions", tuple.privateRealmGrantVersions()); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + Map mapped = new LinkedHashMap<>(); + cutoffs.forEach( + (tenantId, cutoff) -> + mapped.put( + tenantId, + Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + authorityTuple.put("tenantBillingCutoff", Map.copyOf(mapped)); + }); + + Map membershipBaseline = + Map.of( + "membershipLifecycleState", snapshot.membershipLifecycleState(), + "membershipVersion", snapshot.membershipVersion(), + "membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration()); + List> outboxCheckpoints = + snapshot.checkpoints().stream() + .map( + checkpoint -> + Map.of( + "outboxStreamKey", checkpoint.outboxStreamKey(), + "outboxSequence", checkpoint.outboxSequence())) + .toList(); + TokenIdentity tokenIdentity = fixture.tokenIdentity(candidate); + var activeFence = fixture.tokenFences.requireActiveReadback(tokenIdentity); + assertThat(activeFence.state()).isEqualTo(AccountGameplayTokenIdentityFence.State.ACTIVE); + assertThat(activeFence.tokenIdentityFence()).isEqualTo(1L); + var identity = candidate.identity(); + Map tokenEvidence = + Map.ofEntries( + Map.entry("accountId", identity.accountId().toString()), + Map.entry("operationId", identity.operationId().toString()), + Map.entry("issuanceRequestId", identity.requestId().toString()), + Map.entry("tokenJti", identity.tokenJti().toString()), + Map.entry("tokenSHA256", candidate.tokenSha256()), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", snapshot.issuanceFence()), + Map.entry("tokenIdentityFence", Long.toString(activeFence.tokenIdentityFence())), + Map.entry("tokenProfile", GameSessionAccountDelegationProfile.PROFILE), + Map.entry("issuedAt", Long.toString(identity.issuedAtEpochSecond())), + Map.entry("notBefore", Long.toString(identity.notBeforeEpochSecond())), + Map.entry("expiresAt", Long.toString(identity.expiresAtEpochSecond()))); + return Map.of( + "authorityTuple", Map.copyOf(authorityTuple), + "issuanceFence", snapshot.issuanceFence(), + "membershipBaseline", membershipBaseline, + "outboxCheckpoints", outboxCheckpoints, + "tokenIdentityEvidence", tokenEvidence); + } + + private record PreparedAdmission( + AccountGameplayAdmissionLeaseEvidence lease, CommittedCandidateVerificationData candidate) {} + + private record CandidateRow( + String status, UUID tokenJti, String tokenHash, String proofSha256, byte[] proofBytes) {} + + private record LeaseAllocationRow( + UUID accountId, UUID requestId, UUID leaseId, long leaseFence) {} + + private record LeaseFenceRow(UUID accountId, long lastFence) {} + + private record LeaseAllocationState( + long allocationCount, long fenceCount, LeaseAllocationRow allocation, LeaseFenceRow fence) {} + + private static final class Fixture { + private final String schema; + private final DriverManagerDataSource dataSource; + private final DSLContext dsl; + private final DataSourceTransactionManager manager; + private final TransactionTemplate transaction; + private final TransactionTemplate serializable; + private final Path temporaryDirectory; + private final AccountAuthorityGenerationRepository generations; + private final AccountAuthorityOutboxRepository authorityOutbox; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountRepository accounts; + private final FreshTenantIdentityAssociationRepository freshTenants; + private final AccountMembershipPairAuthorityRepository membershipPairs; + private final AccountTenantMembershipRepository memberships; + private final AccountTenantMembershipRoleSnapshotRepository membershipRoles; + private final AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox; + private final AccountTenantAuthorityEventRepository tenantAuthorityEvents; + private final AccountDemoTenantEntitlementRepository demoEntitlements; + private final AccountJoinOperationRepository joinOperations; + private final AccountCanonicalFirstJoinTerminalCoordinator joinTerminal; + private final AccountGameplayAdmissionLeaseRepository leases; + private final AccountGameplayTokenIdentityFenceRepository tokenFences; + private final AccountGameplayDelegationIssuanceRepository issuance; + private AccountGameplayDelegationCommitSignerFixture signerFixture; + private AccountGameplayDelegationCommittedIssuanceOwner committedIssuanceOwner; + private AccountGameplayDelegationResponseRecoveryOwner responseRecoveryOwner; + private final UUID tenantUuid = UUID.randomUUID(); + private final UUID joinRequestId = UUID.randomUUID(); + private final String callerBinding = "current-source-fixture-" + UUID.randomUUID(); + private final FreshTenantCreationEvidence tenantEvidence; + private final VerifiedTenantProvenance tenantProvenance; + private final CanonicalJoinScopeV2 joinScope; + private final Account account; + private final IssuerAccountSourceSnapshot issuanceSource; + private final CommittedCandidateVerificationData committedCandidate; + + private Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + DataSourceTransactionManager manager, + Path temporaryDirectory, + AccountGameplayDelegationRedisClient redisClient) + throws Exception { + this.schema = schema; + this.dataSource = dataSource; + this.dsl = dsl; + this.manager = manager; + this.transaction = new TransactionTemplate(manager); + this.serializable = new TransactionTemplate(manager); + this.serializable.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + this.temporaryDirectory = temporaryDirectory; + this.generations = new AccountAuthorityGenerationRepository(dsl); + this.authorityOutbox = new AccountAuthorityOutboxRepository(dsl); + this.sourceEvidence = + new AccountAuthoritySourceEvidenceRepository(dsl, generations, authorityOutbox); + this.accounts = new AccountRepository(dsl, sourceEvidence); + this.freshTenants = new FreshTenantIdentityAssociationRepository(dsl, TEST_NAMESPACE); + this.membershipPairs = new AccountMembershipPairAuthorityRepository(dsl); + this.memberships = + new AccountTenantMembershipRepository(dsl, accounts, freshTenants, membershipPairs); + this.membershipRoles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + this.tenantEntitlementOutbox = new AccountTenantEntitlementOutboxRepository(dsl); + this.tenantAuthorityEvents = + new AccountTenantAuthorityEventRepository( + dsl, authorityOutbox, tenantEntitlementOutbox, freshTenants, generations); + this.demoEntitlements = + new AccountDemoTenantEntitlementRepository( + dsl, freshTenants, generations, tenantEntitlementOutbox, tenantAuthorityEvents); + var retainedAssociations = mock(ApprovedLegacyTenantAssociationRepository.class); + var retainedResolver = + new AccountTenantIdentityResolver(retainedAssociations, TEST_NAMESPACE); + var connectScopes = new AccountConnectScopeRepository(dsl, retainedResolver, freshTenants); + this.joinOperations = new AccountJoinOperationRepository(dsl, connectScopes); + var membershipEvents = + new AccountMembershipAuthorityEventProducer( + joinOperations, + accounts, + membershipPairs, + memberships, + membershipRoles, + generations, + authorityOutbox, + sourceEvidence, + tenantAuthorityEvents, + demoEntitlements); + this.joinTerminal = + new AccountCanonicalFirstJoinTerminalCoordinator( + accounts, + joinOperations, + memberships, + membershipRoles, + authorityOutbox, + membershipPairs, + new AccountAuditOutboxRepository(dsl), + membershipEvents); + this.leases = new AccountGameplayAdmissionLeaseRepository(dsl); + this.tokenFences = new AccountGameplayTokenIdentityFenceRepository(dsl); + this.tenantEvidence = freshTenantEvidence(tenantUuid); + this.tenantProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenantEvidence.operationId(), + tenantEvidence.evidenceDigest()); + Account newAccount = new Account(); + String suffix = UUID.randomUUID().toString().replace("-", ""); + newAccount.setUsername("current-source-" + suffix); + newAccount.setEmail("current-source-" + suffix + "@example.test"); + newAccount.setPasswordHash("integration-fixture-password-hash"); + newAccount.setRole("player"); + this.account = transaction.execute(status -> accounts.save(newAccount)); + this.joinScope = canonicalJoinScope(account.getAccountUuid(), tenantUuid); + establishTenantEntitlementAndMembership(connectScopes); + + AccountAuthEvidenceBundleRepository bundles = + new AccountAuthEvidenceBundleRepository(dsl, generations, authorityOutbox); + this.issuance = new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence, bundles); + this.issuanceSource = + transaction.execute( + status -> + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid())); + this.committedCandidate = createCommittedIssuanceCandidate(bundles, redisClient); + } + + private void establishTenantEntitlementAndMembership( + AccountConnectScopeRepository connectScopes) { + transaction.execute( + status -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initialize(AuthorityScope.membership(account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), joinScope, tenantProvenance); + joinOperations.insertCanonicalIntent( + joinRequestId.toString(), joinScope, callerBinding); + return null; + }); + DemoTenantEntitlementSnapshot entitlement = + transaction.execute( + status -> + demoEntitlements.provision( + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest + .entitlementRequest(tenantUuid, tenantEvidence), + tenantEvidence)); + transaction.execute( + status -> { + joinOperations.bindCanonicalPolicyEvidence( + joinRequestId.toString(), + joinScope, + callerBinding, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + joinTerminal.commitCanonicalFirstJoin( + joinScope, joinRequestId.toString(), callerBinding); + return null; + }); + } + + private CommittedCandidateVerificationData createCommittedIssuanceCandidate( + AccountAuthEvidenceBundleRepository bundles, + AccountGameplayDelegationRedisClient redisClient) + throws Exception { + long now = Math.floorDiv(System.currentTimeMillis(), 1_000L); + Optional cutoff = + issuanceSource + .account() + .accountSecurityCutoff() + .map( + value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + AccountAuthoritySnapshot authority = + new AccountAuthoritySnapshot( + account.getAccountUuid(), + issuanceSource.issuer().generation(), + issuanceSource.issuer().sourceVersion(), + issuanceSource.account().generation(), + issuanceSource.account().sourceVersion(), + issuanceSource.issuanceFence().value(), + issuanceSource.issuanceFence().sourceVersion(), + cutoff); + var pending = + new AccountGameplayDelegationIssuanceRepository.PendingIntent( + operationId, + requestId, + CALLER_WORKLOAD, + callerContextId, + tokenJti, + now, + now, + now + 120L, + authority, + AccountGameplayCredentialRequestBindingFixture.binding()); + transaction.execute(status -> issuance.beginPending(pending)); + + var transactionalIssuance = + AccountPostgresIntegrationFixture.transactionalIssuanceOwner(issuance, manager); + Path keyringRoot = + Files.createDirectories(temporaryDirectory.resolve("response-key-" + UUID.randomUUID())); + writeResponseKeyring(keyringRoot); + var responseRepository = + new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, + sourceEvidence, + bundles, + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(keyringRoot.toString()))); + var responseService = + new AccountGameplayDelegationResponseEnvelopeService(responseRepository); + this.signerFixture = + AccountGameplayDelegationCommitSignerFixture.create( + temporaryDirectory, + transactionalIssuance, + responseService, + manager, + Clock.systemUTC()); + signerFixture.observeDatabaseFailures(dsl); + AccountGameplayDelegationRedisClient currentRedisClient = redisClient; + if (currentRedisClient == null) { + var redisHarness = + new RedisHarness(account.getAccountUuid(), issuanceSource, getClass().getClassLoader()); + currentRedisClient = redisHarness.client(); + } + var registry = + new AccountGameplayDelegationTokenRegistry( + transactionalIssuance, + manager, + currentRedisClient, + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + 30_000L); + var authorityProjection = + new AccountGameplayDelegationAuthorityProjection( + sourceEvidence, manager, currentRedisClient); + var commitService = + new AccountGameplayDelegationIssuanceCommitService( + signerFixture.signer(), + registry, + authorityProjection, + transactionalIssuance, + manager, + Clock.systemUTC()); + var result = commitService.commitPendingCandidate(requestId); + assertThat(result.outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + this.committedIssuanceOwner = + new AccountGameplayDelegationCommittedIssuanceOwner( + transactionalIssuance, signerFixture.signer(), registry, manager, Clock.systemUTC()); + this.responseRecoveryOwner = + new AccountGameplayDelegationResponseRecoveryOwner( + responseRepository, committedIssuanceOwner, manager); + return transaction.execute( + status -> issuance.readCurrentCommittedCandidateByJti(tokenJti).orElseThrow()); + } + + private AccountGameplayAdmissionCurrentSources.Current readCurrent( + CommittedCandidateVerificationData expectedCandidate) { + return serializable.execute( + status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Expected writable SERIALIZABLE Account transaction"); + } + Object resource = TransactionSynchronizationManager.getResource(dataSource); + if (!(resource instanceof ConnectionHolder holder)) { + throw new IllegalStateException("Expected the manager-enlisted Account connection"); + } + Connection connection = holder.getConnection(); + DSLContext exactDsl = DSL.using(connection, SQLDialect.POSTGRES); + try { + Integer backendBefore = + exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + var current = + AccountGameplayAdmissionCurrentSources.bind(exactDsl, TEST_NAMESPACE) + .readCurrentPublicProductionNew( + tenantUuid, expectedCandidate.identity().tokenJti(), expectedCandidate); + Integer backendAfter = + exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + assertThat(backendAfter).isEqualTo(backendBefore); + assertThat(connection.getAutoCommit()).isFalse(); + assertThat(connection.isReadOnly()).isFalse(); + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + return current; + } catch (SQLException failure) { + throw new IllegalStateException( + "Could not verify the enlisted Account connection", failure); + } + }); + } + + private PreparedAdmission prepareAdmission() { + CommittedCandidateVerificationData candidate = readCommittedCandidate(); + var current = readCurrent(candidate); + return new PreparedAdmission(beginPendingAdmissionLease(current), candidate); + } + + private AccountGameplayAdmissionLeaseEvidence beginPendingAdmissionLease( + AccountGameplayAdmissionCurrentSources.Current current) { + return inSerializableTransaction( + () -> { + UUID requestId = UUID.randomUUID(); + UUID leaseId = UUID.randomUUID(); + var allocation = leases.allocate(account.getAccountUuid(), requestId, leaseId); + long evaluatedAt = currentDatabaseMillisOnEnlistedConnection(); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", TEST_NAMESPACE); + carrier.put("callerWorkload", CALLER_WORKLOAD); + carrier.put("requestId", allocation.requestId().toString()); + carrier.put("leaseId", allocation.leaseId().toString()); + carrier.put("leaseFence", Long.toString(allocation.leaseFence())); + carrier.put("leaseKind", "NEW_BINDING"); + carrier.put("bindingScope", bindingScope()); + carrier.putAll(current.leaseSourceFields()); + carrier.put("evaluatedAt", Long.toString(evaluatedAt)); + carrier.put("expiresAt", Long.toString(evaluatedAt + 14_000L)); + var evidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + leases.beginPending(evidence); + return evidence; + }); + } + + private Map bindingScope() { + return Map.ofEntries( + Map.entry("accountId", account.getAccountUuid().toString()), + Map.entry("tenantId", tenantUuid.toString()), + Map.entry("realmId", UUID.randomUUID().toString()), + Map.entry("worldSlug", "world"), + Map.entry("realmSlug", "realm"), + Map.entry("playableStateNamespaceId", UUID.randomUUID().toString()), + Map.entry("playableStateScope", "SHARED"), + Map.entry("gameInstanceId", UUID.randomUUID().toString()), + Map.entry("characterId", UUID.randomUUID().toString()), + Map.entry("sessionId", UUID.randomUUID().toString()), + Map.entry("bindingGeneration", "1"), + Map.entry("catalogRevision", "1"), + Map.entry("pointerVersion", "1"), + Map.entry("regionId", UUID.randomUUID().toString()), + Map.entry("regionEpoch", "1")); + } + + private CommittedCandidateVerificationData readCommittedCandidate() { + return transaction.execute( + status -> + issuance + .readCurrentCommittedCandidateByJti(committedCandidate.identity().tokenJti()) + .orElseThrow()); + } + + private TokenIdentity tokenIdentity(CommittedCandidateVerificationData candidate) { + var identity = candidate.identity(); + return new TokenIdentity( + identity.accountId(), + identity.operationId(), + identity.requestId(), + candidate.tokenSha256(), + identity.tokenJti(), + identity.notBeforeEpochSecond(), + 1L, + candidate.authoritySnapshot().issuanceFence()); + } + + private DemoTenantEntitlementSnapshot readCurrentEntitlement() { + return transaction.execute(status -> demoEntitlements.readCurrent(tenantUuid)); + } + + private void disableTenantGameplay(DemoTenantEntitlementSnapshot current) { + var request = + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + current.entitlementVersion(), + current.tenantAuthorityGeneration(), + current.tenantAuthoritySourceVersion(), + false, + false, + false, + false, + current.quotas()); + transaction.execute(status -> demoEntitlements.provision(request, tenantEvidence)); + } + + private AccountGameplayAdmissionLeaseOperation readLeaseOperation( + AccountGameplayAdmissionLeaseEvidence evidence) { + return inSerializableTransaction( + () -> + leases + .findByRequest( + account.getAccountUuid(), + UUID.fromString((String) evidence.carrier().get("requestId")), + CALLER_WORKLOAD) + .orElseThrow()); + } + + private CandidateRow readCandidateRow(CommittedCandidateVerificationData candidate) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status, token_jti, token_hash, commit_proof_sha256, " + + "commit_proof_canonical_bytes " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + candidate.identity().requestId()), + "The retained committed candidate row is absent"); + return new CandidateRow( + row.get("status", String.class), + row.get("token_jti", UUID.class), + row.get("token_hash", String.class), + row.get("commit_proof_sha256", String.class), + row.get("commit_proof_canonical_bytes", byte[].class)); + } + + private long leaseOperationCount() { + return Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM account_gameplay_admission_lease_operations"), + "The Account lease operation count query must return a row") + .get(0, Long.class); + } + + private LeaseAllocationState leaseAllocationState(UUID requestId, UUID accountId) { + long allocationCount = + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM account_gameplay_admission_lease_allocations"), + "The Account lease allocation count query must return a row") + .get(0, Long.class); + long fenceCount = + Objects.requireNonNull( + dsl.fetchOne("SELECT count(*) FROM account_gameplay_admission_lease_fences"), + "The Account lease fence count query must return a row") + .get(0, Long.class); + Record allocationRecord = + dsl.fetchOne( + "SELECT account_uuid, request_id, lease_id, lease_fence " + + "FROM account_gameplay_admission_lease_allocations WHERE request_id = ?", + requestId); + Record fenceRecord = + dsl.fetchOne( + "SELECT account_uuid, last_fence " + + "FROM account_gameplay_admission_lease_fences WHERE account_uuid = ?", + accountId); + LeaseAllocationRow allocation = + allocationRecord == null + ? null + : new LeaseAllocationRow( + allocationRecord.get("account_uuid", UUID.class), + allocationRecord.get("request_id", UUID.class), + allocationRecord.get("lease_id", UUID.class), + allocationRecord.get("lease_fence", Long.class)); + LeaseFenceRow fence = + fenceRecord == null + ? null + : new LeaseFenceRow( + fenceRecord.get("account_uuid", UUID.class), + fenceRecord.get("last_fence", Long.class)); + return new LeaseAllocationState(allocationCount, fenceCount, allocation, fence); + } + + private List originalAckReceiptImage(UUID requestId) { + Record receipt = + dsl.fetchOne( + "SELECT schema_version, request_id, account_uuid, lease_id, lease_fence, " + + "evidence_sha256, binding_decision_id, expires_at_ms, finalization_xid, " + + "committed_before_ms, receipt_xid " + + "FROM account_gameplay_admission_original_commit_ack_receipts " + + "WHERE request_id = ?", + requestId); + if (receipt == null) return List.of(); + return List.of( + receipt.get("schema_version", Short.class), + receipt.get("request_id", UUID.class), + receipt.get("account_uuid", UUID.class), + receipt.get("lease_id", UUID.class), + receipt.get("lease_fence", Long.class), + receipt.get("evidence_sha256", String.class), + receipt.get("binding_decision_id", UUID.class), + receipt.get("expires_at_ms", Long.class), + receipt.get("finalization_xid", String.class), + receipt.get("committed_before_ms", Long.class), + receipt.get("receipt_xid", String.class)); + } + + private List sourceAndIssuanceImage() { + List image = new ArrayList<>(); + for (Record tableRow : + dsl.fetch( + "SELECT tablename FROM pg_tables WHERE schemaname = current_schema() " + + "AND tablename <> 'account_gameplay_admission_lease_operations' " + + "ORDER BY tablename")) { + String table = tableRow.get("tablename", String.class).replace("\"", "\"\""); + Record state = + dsl.fetchOne( + "SELECT count(*)::bigint, " + + "COALESCE(string_agg(xmin::text, ',' ORDER BY xmin::text), '') " + + "FROM \"" + + table + + "\""); + image.add( + table + + ":" + + Objects.requireNonNull(state).get(0, Long.class) + + ":" + + state.get(1, String.class)); + } + return List.copyOf(image); + } + + /** Adds only the two legitimate allocator-table exclusions to the original strict image. */ + private List sourceAndIssuanceImageForAuthenticatedAcquire() { + return sourceAndIssuanceImage().stream() + .filter( + tableImage -> + !tableImage.startsWith("account_gameplay_admission_lease_allocations:") + && !tableImage.startsWith("account_gameplay_admission_lease_fences:")) + .toList(); + } + + /** Also excludes only the durable ACK table legitimately written by fresh finalization. */ + private List sourceAndIssuanceImageForAuthenticatedCommit() { + return sourceAndIssuanceImage().stream() + .filter( + tableImage -> + !tableImage.startsWith("account_gameplay_admission_lease_allocations:") + && !tableImage.startsWith("account_gameplay_admission_lease_fences:") + && !tableImage.startsWith( + "account_gameplay_admission_original_commit_ack_receipts:")) + .toList(); + } + + private long currentDatabaseMillisOnEnlistedConnection() { + Object resource = TransactionSynchronizationManager.getResource(dataSource); + if (!(resource instanceof ConnectionHolder holder)) { + throw new IllegalStateException("Expected the manager-enlisted Account connection"); + } + DSLContext exactDsl = DSL.using(holder.getConnection(), SQLDialect.POSTGRES); + Long databaseMillis = + exactDsl + .fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + if (databaseMillis == null || databaseMillis <= 0L) { + throw new IllegalStateException("PostgreSQL millisecond clock readback is unavailable"); + } + return databaseMillis; + } + + private T inSerializableTransaction(java.util.function.Supplier operation) { + return serializable.execute(status -> operation.get()); + } + + private static FreshTenantCreationEvidence freshTenantEvidence(UUID tenantUuid) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String sourceTenantKey = + "fresh-" + UUID.randomUUID().toString().replace("-", "").substring(0, 30); + String requestDigest = + GameTenantCreationDigest.requestDigest( + TEST_NAMESPACE, requestId, sourceTenantKey, "Admission proof tenant", null); + long sourceGameRowId = + Math.max(1L, UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE); + String provenanceKind = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + TEST_NAMESPACE, + requestId, + operationId, + requestDigest, + tenantUuid, + sourceGameRowId, + sourceTenantKey, + provenanceKind)); + } + + private static void writeResponseKeyring(Path root) throws Exception { + byte[] key = new byte[32]; + for (int index = 0; index < key.length; index++) key[index] = (byte) (index + 1); + String encoded = Base64.getUrlEncoder().withoutPadding().encodeToString(key); + Files.writeString( + root.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive integration-key " + encoded + "\n", + StandardCharsets.US_ASCII); + } + } + + /** Run-owned local primary/replica used only for the authenticated Account-owner case. */ + private static final class PhysicalRedisFixture implements AutoCloseable { + private static final int REDIS_PORT = 6379; + private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); + private static final String PRIMARY_ALIAS = "account-gameplay-admission-primary"; + + private final Network network = Network.newNetwork(); + private final GenericContainer primary = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(network) + .withNetworkAliases(PRIMARY_ALIAS) + .withExposedPorts(REDIS_PORT) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + private final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(network) + .dependsOn(primary) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + PRIMARY_ALIAS, + Integer.toString(REDIS_PORT)); + + private RedisClient bootstrapClient; + private LettuceAccountCoordinationPinnedConnectionProvider accountProvider; + private AccountGameplayDelegationRedisClient accountClient; + + private static PhysicalRedisFixture start() throws InterruptedException { + assumeTrue( + DockerClientFactory.instance().isDockerAvailable(), + "Docker is unavailable; authenticated Account-owner Redis proof is skipped"); + PhysicalRedisFixture fixture = new PhysicalRedisFixture(); + try { + fixture.startOwnedRedis(); + return fixture; + } catch (RuntimeException | InterruptedException startFailure) { + fixture.close(); + throw startFailure; + } + } + + private void startOwnedRedis() throws InterruptedException { + primary.start(); + replica.start(); + int primaryPort = primary.getMappedPort(REDIS_PORT); + bootstrapClient = redisClient("127.0.0.1", primaryPort, null); + try (var connection = bootstrapClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + configureAccountUser(commands); + awaitLocalAndReplicaAof(commands); + } + + RedisURI accountUri = + RedisURI.Builder.redis("127.0.0.1", primaryPort) + .withAuthentication( + AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY, ACCOUNT_PASSWORD) + .build(); + accountUri.setTimeout(Duration.ofSeconds(5)); + accountProvider = new LettuceAccountCoordinationPinnedConnectionProvider(accountUri); + ClassLoader classLoader = PhysicalRedisFixture.class.getClassLoader(); + accountClient = + new AccountGameplayDelegationRedisClient( + accountProvider, + RedisScriptCatalog.loadInstalled(classLoader), + new AcknowledgementRequirements(1, 1, 5_000), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + classLoader); + } + + private AccountGameplayDelegationRedisClient client() { + return Objects.requireNonNull(accountClient, "Owned Account Redis client is unavailable"); + } + + private static RedisClient redisClient(String host, int port, String password) { + RedisURI.Builder uri = RedisURI.Builder.redis(host, port); + if (password != null) { + uri.withAuthentication( + AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY, password); + } + RedisClient client = RedisClient.create(uri.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static void configureAccountUser(RedisCommands commands) { + commands.aclSetuser( + AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY, + new AclSetuserArgs() + .reset() + .on() + .addPassword(ACCOUNT_PASSWORD) + .keyPattern("session:auth:token:*") + .keyPattern("session:auth:generation:issuer:*") + .keyPattern("session:auth:generation:account:*") + .keyPattern("session:auth:generation:tenant:*") + .keyPattern("session:auth:generation:membership:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRETIME) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.TYPE)); + commands.dispatch( + TestAclSetuser.INSTANCE, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY) + .add("+waitaof")); + } + + private static void awaitLocalAndReplicaAof(RedisCommands commands) + throws InterruptedException { + byte[] probeKey = + ("test-only:account-gameplay-admission-aof-probe:" + UUID.randomUUID()) + .getBytes(StandardCharsets.US_ASCII); + commands.set(probeKey, "test-only-replication-probe".getBytes(StandardCharsets.US_ASCII)); + long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos(); + try { + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add(1).add(1).add(500)); + if (hasAofCounts(counts, 1, 1)) return; + Thread.sleep(50); + } + throw new IllegalStateException("Test Account Coordination Redis replica lacks AOF proof"); + } finally { + commands.del(List.of(probeKey).toArray(byte[][]::new)); + } + } + + private static boolean hasAofCounts(List counts, long local, long replicas) { + return counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long localCount + && localCount >= local + && counts.get(1) instanceof Long replicaCount + && replicaCount >= replicas; + } + + @Override + public void close() { + RuntimeException cleanupFailure = null; + if (accountProvider != null) { + try { + accountProvider.close(); + } catch (RuntimeException failure) { + cleanupFailure = failure; + } + } + if (bootstrapClient != null) { + try { + bootstrapClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } catch (RuntimeException failure) { + if (cleanupFailure == null) cleanupFailure = failure; + else cleanupFailure.addSuppressed(failure); + } + } + if (replica.isRunning()) { + try { + replica.stop(); + } catch (RuntimeException failure) { + if (cleanupFailure == null) cleanupFailure = failure; + else cleanupFailure.addSuppressed(failure); + } + } + if (primary.isRunning()) { + try { + primary.stop(); + } catch (RuntimeException failure) { + if (cleanupFailure == null) cleanupFailure = failure; + else cleanupFailure.addSuppressed(failure); + } + } + try { + network.close(); + } catch (RuntimeException failure) { + if (cleanupFailure == null) cleanupFailure = failure; + else cleanupFailure.addSuppressed(failure); + } + if (cleanupFailure != null) throw cleanupFailure; + } + } + + private enum TestWaitAof implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclSetuser implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } + + private static final class RedisHarness { + private final UUID accountId; + private final byte[][] authorityProjectionBytes; + private final AtomicReference pendingRecord = new AtomicReference<>(); + private final AtomicLong absoluteExpiryMillis = new AtomicLong(); + private final StatefulRedisConnection connection = + mock(StatefulRedisConnection.class); + private final RedisCommands commands = mock(RedisCommands.class); + private final AccountGameplayDelegationRedisClient client; + + private RedisHarness( + UUID accountId, IssuerAccountSourceSnapshot source, ClassLoader resourceClassLoader) + throws Exception { + this.accountId = accountId; + authorityProjectionBytes = + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(source); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.isOpen()).thenReturn(true); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()) + .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer(invocation -> sha1(invocation.getArgument(0))); + when(commands.evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + invocation -> { + byte[][] keys = (byte[][]) invocation.getRawArguments()[2]; + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + if (arguments.length == 2) pendingRecord.set(arguments[0].clone()); + else if (arguments.length == 3) pendingRecord.set(arguments[1].clone()); + else throw new AssertionError("Unexpected token registry script arguments"); + absoluteExpiryMillis.set( + Long.parseLong( + new String(arguments[arguments.length - 1], StandardCharsets.US_ASCII))); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER)) { + authorityProjectionBytes[0] = arguments[0].clone(); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { + if (arguments.length == 3 && arguments[2].length > 0) { + authorityProjectionBytes[1] = arguments[2].clone(); + } + } + return 1L; + }); + when(commands.get(any(byte[].class))) + .thenAnswer( + invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = pendingRecord.get(); + return value == null ? null : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) return authorityProjectionBytes[0].clone(); + if ((AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(key)) return authorityProjectionBytes[1].clone(); + return null; + }); + when(commands.pexpiretime(any(byte[].class))) + .thenAnswer(invocation -> absoluteExpiryMillis.get()); + when(commands.pttl(any(byte[].class))).thenReturn(-1L); + doAnswer(invocation -> List.of(1L, 1L)) + .when(commands) + .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + client = + new AccountGameplayDelegationRedisClient( + provider, + RedisScriptCatalog.loadInstalled(resourceClassLoader), + new AcknowledgementRequirements(1, 1, 1_000), + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + resourceClassLoader); + } + + private AccountGameplayDelegationRedisClient client() { + return client; + } + } + + private static String sha1(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(bytes)); + } + + private static CanonicalJoinScopeV2 canonicalJoinScope(UUID accountId, UUID tenantId) { + return new CanonicalJoinScopeV2( + "current-source-scope-" + UUID.randomUUID(), + accountId, + tenantId, + UUID.randomUUID(), + "tenant", + "world", + "production", + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + 7L, + 3L, + "2099-01-01T00:00:00Z", + "2099-01-01T00:02:00Z"); + } + + private static DemoTenantEntitlementRequest entitlementRequest( + UUID tenantUuid, FreshTenantCreationEvidence tenantEvidence) { + return new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantUuid, + tenantEvidence.creationRequestId(), + tenantEvidence.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index 3f9823683d..537621aa6b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -57,10 +57,68 @@ static void stopPostgres() { POSTGRES.stop(); } + @Test + void pendingLeaseWindowUsesDatabaseClockAndPreservesLifetime() { + var context = context(); + long databaseTimeBefore = + context + .dsl() + .fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + var evidence = pending(context, 15000); + long databaseTimeAfter = + context + .dsl() + .fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + long evaluatedAt = Long.parseLong((String) evidence.carrier().get("evaluatedAt")); + + assertThat(evaluatedAt).isBetween(databaseTimeBefore, databaseTimeAfter); + assertThat(Long.parseLong((String) evidence.carrier().get("expiresAt"))) + .isEqualTo(evaluatedAt + 15000); + } + private static final String TENANT = "22222222-2222-4222-8222-222222222222"; private static final String OTHER = "33333333-3333-4333-8333-333333333333"; private static final String RECEIPTS = "account_gameplay_admission_original_commit_ack_receipts"; + @Test + void currentSourceCommitEntryRefusesStorageOnlyLeaseWithoutCurrentPlayerAuthority() { + var context = context(); + var evidence = pending(context, 15000); + var scope = (Map) evidence.carrier().get("bindingScope"); + var token = (Map) evidence.carrier().get("tokenIdentityEvidence"); + UUID account = UUID.fromString((String) scope.get("accountId")); + var expectedIdentity = org.mockito.Mockito.mock(AccountGameplayDelegationPendingIdentity.class); + org.mockito.Mockito.when(expectedIdentity.accountId()).thenReturn(account); + org.mockito.Mockito.when(expectedIdentity.tokenJti()) + .thenReturn(UUID.fromString((String) token.get("tokenJti"))); + var expectedCandidate = + org.mockito.Mockito.mock( + AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData.class); + org.mockito.Mockito.when(expectedCandidate.identity()).thenReturn(expectedIdentity); + org.mockito.Mockito.when(expectedCandidate.authoritySnapshot()) + .thenReturn( + new net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord + .AccountAuthoritySnapshot( + account, 1L, 1L, 1L, 1L, 1L, 1L, java.util.Optional.empty())); + var originalOperation = operation(context, evidence); + var originalSources = sourceSnapshot(context); + + // This controlled candidate is correlation only. The real in-transaction source readers + // must refuse this storage fixture, which has no current player membership/tenant authority. + assertThatThrownBy( + () -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .executeWithCurrentSources( + evidence, UUID.randomUUID(), "test", expectedCandidate)) + .isInstanceOf(IllegalStateException.class); + + assertThat(operation(context, evidence)).isEqualTo(originalOperation); + assertThat(sourceSnapshot(context)).isEqualTo(originalSources); + assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); + } + @Test void coldGenuineAcknowledgedFinalizationPersistsExactProofWithoutAuxiliaryWrites() { var context = context(); @@ -857,8 +915,50 @@ public Connection getConnection() throws SQLException { } private static OriginalCommitAcknowledgement finalized(Context context, long lifetime) { - return new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) - .execute(pending(context, lifetime), UUID.randomUUID()); + var evidence = pending(context, lifetime); + long startedAtNanos = System.nanoTime(); + try { + return new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, UUID.randomUUID()); + } catch (RuntimeException failure) { + try { + long failedAtNanos = System.nanoTime(); + long jvmWallClockMs = Instant.now().toEpochMilli(); + Long databaseWallClockMs = null; + Throwable databaseClockFailure = null; + try { + databaseWallClockMs = + context + .dsl() + .fetchSingle( + "SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint AS database_now_ms") + .get("database_now_ms", Long.class); + } catch (Throwable diagnosticFailure) { + databaseClockFailure = diagnosticFailure; + } + String diagnosticMessage = + "Original COMMIT failure timing: evaluatedAtMs=" + + evidence.carrier().get("evaluatedAt") + + "; expiresAtMs=" + + evidence.carrier().get("expiresAt") + + "; jvmWallClockMs=" + + jvmWallClockMs + + "; dbWallClockMs=" + + (databaseWallClockMs == null ? "unavailable" : databaseWallClockMs) + + "; monotonicElapsedNanos=" + + (failedAtNanos - startedAtNanos); + IllegalStateException diagnostic = new IllegalStateException(diagnosticMessage); + if (databaseClockFailure != null) { + diagnostic.addSuppressed( + new IllegalStateException( + "Database wall-clock read failed: " + databaseClockFailure.getClass().getName())); + } + failure.addSuppressed(diagnostic); + } catch (Throwable ignoredDiagnosticFailure) { + // Timing diagnostics must never replace the original finalization failure. + } + throw failure; + } } private static AccountGameplayAdmissionLeaseEvidence pending(Context context, long lifetime) { @@ -882,15 +982,20 @@ private static AccountGameplayAdmissionLeaseEvidence pending(Context context, lo new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); var allocation = repository.allocate(accountId, UUID.randomUUID(), UUID.randomUUID()); - var evidence = evidence(allocation, lifetime); + long databaseNow = + context + .dsl() + .fetchSingle( + "SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + var evidence = evidence(allocation, lifetime, databaseNow); repository.beginPending(evidence); return evidence; }); } private static AccountGameplayAdmissionLeaseEvidence evidence( - AccountGameplayAdmissionLeaseRepository.Allocation allocation, long lifetime) { - long now = Instant.now().toEpochMilli(); + AccountGameplayAdmissionLeaseRepository.Allocation allocation, long lifetime, long now) { String account = allocation.accountId().toString(); Map carrier = new LinkedHashMap<>(); carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java index dcab9b5d8b..ce664a8c7f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java @@ -301,6 +301,11 @@ public AccountGameplayDelegationSigner signer() { return signer; } + /** Exposes only this test fixture's pinned public JWKS source for exact-token verification. */ + public AccountJwtJwksTrustedSource trustedJwksSource() { + return trustedJwksSource; + } + /** Prepares the real signer-produced pending candidate without exposing its compact JWT. */ public void preparePendingCandidate(UUID requestId) { signer.signPendingCandidate(requestId); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwnerTest.java new file mode 100644 index 0000000000..5dfb19ec2c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwnerTest.java @@ -0,0 +1,112 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import javax.sql.DataSource; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameplayAdmissionLeaseOwnerTest { + private static final String NAMESPACE = "firemud"; + + private final AccountGameplayAdmissionCallerVerifier callerVerifier = + mock(AccountGameplayAdmissionCallerVerifier.class); + private final CanonicalGameplayAdmissionDecisionReadClient decisionClient = + mock(CanonicalGameplayAdmissionDecisionReadClient.class); + private final DataSource dataSource = mock(DataSource.class); + private final AccountGameplayAdmissionLeaseOwner owner = + new AccountGameplayAdmissionLeaseOwner(callerVerifier, decisionClient, NAMESPACE, dataSource); + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void everyPurposeRejectsMissingPeerBeforeParsingOrOwnerAccess() { + withPeer( + null, + () -> { + assertStatus( + Status.Code.UNAUTHENTICATED, + () -> owner.acquire(AcquireGameplayAdmissionLeaseRequest.getDefaultInstance())); + assertStatus( + Status.Code.UNAUTHENTICATED, + () -> + owner.finalizeLease(FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance())); + assertStatus( + Status.Code.UNAUTHENTICATED, + () -> owner.read(ReadGameplayAdmissionLeaseRequest.getDefaultInstance())); + assertStatus( + Status.Code.UNAUTHENTICATED, + () -> owner.abort(AbortGameplayAdmissionLeaseRequest.getDefaultInstance())); + }); + + verifyNoInteractions(callerVerifier, decisionClient, dataSource); + } + + @Test + void everyPurposeRejectsWrongWorkloadBeforeParsingOrOwnerAccess() { + GrpcPeerIdentity wrongPeer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/account-service").orElseThrow(); + withPeer( + wrongPeer, + () -> { + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> owner.acquire(AcquireGameplayAdmissionLeaseRequest.getDefaultInstance())); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> + owner.finalizeLease(FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance())); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> owner.read(ReadGameplayAdmissionLeaseRequest.getDefaultInstance())); + assertStatus( + Status.Code.PERMISSION_DENIED, + () -> owner.abort(AbortGameplayAdmissionLeaseRequest.getDefaultInstance())); + }); + + verifyNoInteractions(callerVerifier, decisionClient, dataSource); + } + + @Test + void ambientAccountTransactionIsRejectedBeforeCredentialOrRemoteReads() { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service") + .orElseThrow(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + withPeer( + peer, + () -> + assertStatus( + Status.Code.FAILED_PRECONDITION, + () -> owner.acquire(AcquireGameplayAdmissionLeaseRequest.getDefaultInstance()))); + + verifyNoInteractions(callerVerifier, decisionClient, dataSource); + } + + private static void assertStatus(Status.Code expected, Runnable invocation) { + StatusRuntimeException failure = assertThrows(StatusRuntimeException.class, invocation::run); + assertEquals(expected, failure.getStatus().getCode()); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable invocation) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java new file mode 100644 index 0000000000..d03c64a286 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java @@ -0,0 +1,724 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountGameplayAdmissionCallerVerifierTest { + private static final Instant NOW = Instant.parse("2026-10-26T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final String ENVIRONMENT = "staging"; + private static final String CLUSTER = "cluster-admission-test"; + private static final String NAMESPACE = "firemud"; + private static final String CLUSTER_UID = "66666666-6666-4666-8666-666666666666"; + private static final String NAMESPACE_UID = "77777777-7777-4777-8777-777777777777"; + private static final String CONFIG_MAP_UID = "88888888-8888-4888-8888-888888888888"; + private static final String SECRET_UID = "99999999-9999-4999-8999-999999999999"; + private static final String API_BINDING_DIGEST = "a".repeat(64); + private static final String API_CA_DIGEST = "b".repeat(64); + private static final String OPERATION_DIGEST = "1".repeat(64); + private static final String GENERATION_REQUEST_DIGEST = "2".repeat(64); + private static final String GENERATION_RECEIPT_DIGEST = "3".repeat(64); + private static final String SNAPSHOT_DIGEST = "4".repeat(64); + private static final String CONFIG_MAP_SNAPSHOT_DIGEST = "6".repeat(64); + private static final String KID = "account-admission-test"; + private static final String GAME_SESSION_WORKLOAD = + "spiffe://firemud/ns/firemud/sa/game-session-service"; + private static final SourceIdentity JWKS_SOURCE_IDENTITY = + new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + "api-r1", + "https://kubernetes.test:6443", + API_CA_DIGEST); + private static final UUID ACCOUNT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID REQUEST_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TOKEN_JTI = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static KeyPair signingPair; + private static KeyPair mismatchedPair; + + @BeforeAll + static void generateRsaPairs() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + signingPair = generator.generateKeyPair(); + mismatchedPair = generator.generateKeyPair(); + } + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void verifiesSignedInitialCallerAgainstExactCommittedCandidate() throws Exception { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + CommittedCandidateVerificationData committed = + fixture.candidate(compactJwt, ACCOUNT_ID, false, false); + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenReturn(committed); + + AccountGameplayAdmissionCallerVerifier.VerifiedCaller verified = + fixture.verifier.verifyPresentedCompactToken(compactJwt); + + assertSame(committed, verified.committedCandidate()); + assertEquals(ACCOUNT_ID, verified.identity().accountId()); + assertEquals(TOKEN_JTI, verified.identity().tokenJti()); + assertEquals(GameSessionAccountDelegationProfile.PROFILE, verified.tokenProfile()); + assertEquals(1L, verified.tokenIdentityFence()); + assertFalse(verified.toString().contains(compactJwt)); + verify(fixture.currentIssuanceOwner).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void reusesJwksCacheForSamePinAndStillReadsCurrentIssuanceForEachVerification() throws Exception { + Fixture fixture = new Fixture(); + MutableClock clock = new MutableClock(NOW); + AccountJwtJwksTrustedSource source = trustedSource(JWKS_SOURCE_IDENTITY, fixture.jwksJson); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + CommittedCandidateVerificationData committed = + fixture.candidate(compactJwt, ACCOUNT_ID, false, false); + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenReturn(committed); + AccountGameplayAdmissionCallerVerifier verifier = fixture.verifierWith(source, clock); + + verifier.verifyPresentedCompactToken(compactJwt); + verifier.verifyPresentedCompactToken(compactJwt); + + verify(source, times(2)).sourceIdentity(); + verify(source, times(1)).load(); + verify(fixture.currentIssuanceOwner, times(2)) + .requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void refreshesJwksCacheAfterMaximumAge() throws Exception { + Fixture fixture = new Fixture(); + MutableClock clock = new MutableClock(NOW); + AccountJwtJwksTrustedSource source = trustedSource(JWKS_SOURCE_IDENTITY, fixture.jwksJson); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + CommittedCandidateVerificationData committed = + fixture.candidate(compactJwt, ACCOUNT_ID, false, false); + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenReturn(committed); + AccountGameplayAdmissionCallerVerifier verifier = fixture.verifierWith(source, clock); + + verifier.verifyPresentedCompactToken(compactJwt); + clock.advanceSeconds(31); + verifier.verifyPresentedCompactToken(compactJwt); + + verify(source, times(2)).load(); + verify(fixture.currentIssuanceOwner, times(2)) + .requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void replacesJwksCacheWhenTrustedSourceIdentityChanges() throws Exception { + Fixture fixture = new Fixture(); + MutableClock clock = new MutableClock(NOW); + SourceIdentity rotatedIdentity = + new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "api-r2", + "https://kubernetes.test:6443", + API_CA_DIGEST); + AtomicReference activeIdentity = new AtomicReference<>(JWKS_SOURCE_IDENTITY); + AtomicReference activeJwks = new AtomicReference<>(fixture.jwksJson); + AccountJwtJwksTrustedSource source = mock(AccountJwtJwksTrustedSource.class); + when(source.sourceIdentity()).thenAnswer(invocation -> activeIdentity.get()); + when(source.load()) + .thenAnswer( + invocation -> + new PublicJwksSnapshot( + activeIdentity.get(), activeJwks.get().getBytes(StandardCharsets.UTF_8))); + String oldToken = fixture.signedToken(signingPair, fixture.initialClaims()); + CommittedCandidateVerificationData oldCandidate = + fixture.candidate(oldToken, ACCOUNT_ID, false, false); + Map rotatedClaims = fixture.initialClaims(); + String rotatedToken = fixture.signedToken(mismatchedPair, rotatedClaims); + CommittedCandidateVerificationData rotatedCandidate = + fixture.candidate(rotatedToken, ACCOUNT_ID, false, false); + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenReturn(oldCandidate, rotatedCandidate); + AccountGameplayAdmissionCallerVerifier verifier = fixture.verifierWith(source, clock); + + verifier.verifyPresentedCompactToken(oldToken); + activeIdentity.set(rotatedIdentity); + activeJwks.set("{\"keys\":[" + jwkJson(mismatchedPair, KID) + "]}"); + + assertUnavailable(verifier, oldToken); + assertSame( + rotatedCandidate, verifier.verifyPresentedCompactToken(rotatedToken).committedCandidate()); + + verify(source, times(3)).sourceIdentity(); + verify(source, times(2)).load(); + verify(fixture.currentIssuanceOwner, times(2)) + .requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + + @Test + void rejectsBadSignatureAndWrongInitialProfileBeforeCurrentnessLookup() throws Exception { + Fixture fixture = new Fixture(); + String badSignature = fixture.signedToken(mismatchedPair, fixture.initialClaims()); + + assertUnavailable(fixture.verifier, badSignature); + verify(fixture.currentIssuanceOwner, never()) + .requireCurrentActiveCommittedCandidateByJti(any()); + + Map tenantBoundClaims = fixture.initialClaims(); + tenantBoundClaims.put("tenantId", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + String wrongProfile = fixture.signedToken(signingPair, tenantBoundClaims); + + assertUnavailable(fixture.verifier, wrongProfile); + verify(fixture.currentIssuanceOwner, never()) + .requireCurrentActiveCommittedCandidateByJti(any()); + } + + @Test + void rejectsCandidateHashIdentityAndAuthorityMismatchWithoutRetainingCredentialDetails() + throws Exception { + for (CandidateMismatch mismatch : CandidateMismatch.values()) { + Fixture fixture = new Fixture(); + String compactJwt = fixture.signedToken(signingPair, fixture.initialClaims()); + CommittedCandidateVerificationData mismatchedCandidate = + fixture.candidate( + compactJwt, + mismatch == CandidateMismatch.IDENTITY ? OTHER_ACCOUNT_ID : ACCOUNT_ID, + mismatch == CandidateMismatch.HASH, + mismatch == CandidateMismatch.AUTHORITY); + when(fixture.currentIssuanceOwner.requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI)) + .thenReturn(mismatchedCandidate); + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> fixture.verifier.verifyPresentedCompactToken(compactJwt)); + + assertNull(failure.getCause()); + assertEquals("Account gameplay caller verification is unavailable", failure.getMessage()); + assertFalse(failure.toString().contains(compactJwt)); + verify(fixture.currentIssuanceOwner).requireCurrentActiveCommittedCandidateByJti(TOKEN_JTI); + } + } + + @Test + void refusesAmbientTransactionBeforeTrustedSourceOrCurrentnessReads() { + Fixture fixture = new Fixture(); + TransactionSynchronizationManager.setActualTransactionActive(true); + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> fixture.verifier.verifyPresentedCompactToken("credential-not-retained")); + + assertNull(failure.getCause()); + verifyNoInteractions( + fixture.materializerTrust, + fixture.configMapClient, + fixture.desiredStateRepository, + fixture.publicationRepository, + fixture.currentIssuanceOwner); + } + + private static void assertUnavailable( + AccountGameplayAdmissionCallerVerifier verifier, String compactJwt) { + IllegalStateException failure = + assertThrows( + IllegalStateException.class, () -> verifier.verifyPresentedCompactToken(compactJwt)); + assertNull(failure.getCause()); + assertEquals("Account gameplay caller verification is unavailable", failure.getMessage()); + assertFalse(failure.toString().contains(compactJwt)); + } + + private static AccountJwtJwksTrustedSource trustedSource( + SourceIdentity identity, String jwksJson) { + AccountJwtJwksTrustedSource source = mock(AccountJwtJwksTrustedSource.class); + when(source.sourceIdentity()).thenReturn(identity); + when(source.load()) + .thenReturn(new PublicJwksSnapshot(identity, jwksJson.getBytes(StandardCharsets.UTF_8))); + return source; + } + + private static final class MutableClock extends Clock { + private Instant instant; + + private MutableClock(Instant instant) { + this.instant = instant; + } + + private void advanceSeconds(long seconds) { + instant = instant.plusSeconds(seconds); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return instant; + } + } + + private enum CandidateMismatch { + HASH, + IDENTITY, + AUTHORITY + } + + private static final class Fixture { + private final AccountJwtJwksConfigMapClient configMapClient = + mock(AccountJwtJwksConfigMapClient.class); + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtSignerDesiredStateRepository desiredStateRepository = + mock(AccountJwtSignerDesiredStateRepository.class); + private final AccountJwtJwksPublicationRepository publicationRepository = + mock(AccountJwtJwksPublicationRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final AccountGameplayDelegationCommittedIssuanceOwner currentIssuanceOwner = + mock(AccountGameplayDelegationCommittedIssuanceOwner.class); + private final Binding materializerBinding; + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding; + private final TrustFence trustFence; + private final BindingIdentity apiIdentity; + private final String jwksJson; + private final String generationMarkerJson; + private final GenerationRequest generationRequest; + private final GenerationResult generationResult; + private final EnrollmentIdentity enrollmentIdentity; + private final DesiredState desiredState; + private final PublicationEvidence publicationEvidence; + private final ConfigMapSnapshot configMapSnapshot; + private final AccountJwtJwksTrustedSource trustedJwksSource; + private final AccountGameplayAdmissionCallerVerifier verifier; + + private Fixture() { + String expectedPeer = "spiffe://firemud/ns/firemud/sa/jwt-signer-materializer"; + String trustDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "materializer-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + expectedPeer, + List.of("c".repeat(64))); + materializerBinding = + new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + expectedPeer, + List.of("c".repeat(64)), + "materializer-r1", + trustDigest); + accountBinding = materializerBinding.accountBinding(); + trustFence = new TrustFence(CLUSTER_UID, NAMESPACE_UID, trustDigest, "materializer-r1"); + apiIdentity = + new BindingIdentity( + API_BINDING_DIGEST, + "api-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.test:6443", + "kubernetes.test", + API_CA_DIGEST, + "system:serviceaccount:firemud:account-service"); + String jwk = jwkJson(signingPair, KID); + jwksJson = "{\"keys\":[" + jwk + "]}"; + String publicFingerprint = fingerprint((RSAPublicKey) signingPair.getPublic()); + UUID generationOperationId = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + String publicJwkJson = jwk; + String generation = "1"; + String secretResourceVersion = "10"; + generationRequest = + new GenerationRequest( + GenerationPhase.GENERATION_RECORDED, + generationOperationId, + OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + 2L, + accountBinding, + trustFence, + AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME, + generation, + KID, + "RS256", + "MATERIALIZE_PENDING", + List.of("pending"), + Optional.empty(), + Optional.empty(), + SECRET_UID, + secretResourceVersion, + GENERATION_RECEIPT_DIGEST, + publicFingerprint, + publicJwkJson, + "11"); + generationResult = + new GenerationResult( + generationOperationId, + accountBinding, + OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + 2L, + trustFence, + AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME, + SECRET_UID, + secretResourceVersion, + "11", + generation, + KID, + "RS256", + publicFingerprint, + publicJwkJson, + GENERATION_RECEIPT_DIGEST); + enrollmentIdentity = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + trustDigest, + "materializer-r1", + API_BINDING_DIGEST, + "api-r1", + CONFIG_MAP_UID, + "40", + CONFIG_MAP_SNAPSHOT_DIGEST); + desiredState = + new DesiredState( + accountBinding, + 2L, + Optional.empty(), + Optional.empty(), + Optional.of(generationOperationId), + Optional.empty(), + Optional.of(enrollmentIdentity)); + generationMarkerJson = + markerJson( + generationOperationId, + OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + GENERATION_RECEIPT_DIGEST, + materializerBinding, + apiIdentity, + generation, + KID, + publicFingerprint); + PrepublicationIntent intent = + PrepublicationIntent.create( + generationResult, + generationRequest, + API_BINDING_DIGEST, + "api-r1", + CONFIG_MAP_UID, + "41", + SNAPSHOT_DIGEST, + jwksJson, + generationMarkerJson); + PublicationReceipt receipt = PublicationReceipt.create(intent, "42"); + publicationEvidence = new PublicationEvidence(intent, Optional.of(receipt), Optional.empty()); + configMapSnapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + jwksJson, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + generationMarkerJson, + "operator.note", + "retained")); + + when(transactionManager.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + when(materializerTrust.current()).thenReturn(Optional.of(materializerBinding)); + when(configMapClient.identity()).thenReturn(apiIdentity); + when(configMapClient.observe()).thenReturn(configMapSnapshot); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(desiredState)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(generationRequest); + when(desiredStateRepository.readCurrentGenerationResult(eq(accountBinding), eq(trustFence))) + .thenReturn(generationResult); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(publicationEvidence)); + trustedJwksSource = + new AccountJwtJwksTrustedSource( + configMapClient, + materializerTrust, + desiredStateRepository, + publicationRepository, + transactionManager); + verifier = + new AccountGameplayAdmissionCallerVerifier( + trustedJwksSource, currentIssuanceOwner, CLOCK); + } + + private AccountGameplayAdmissionCallerVerifier verifierWith( + AccountJwtJwksTrustedSource source, Clock clock) { + return new AccountGameplayAdmissionCallerVerifier(source, currentIssuanceOwner, clock); + } + + private Map initialClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", GameSessionAccountDelegationProfile.ISSUER); + claims.put("sub", ACCOUNT_ID.toString()); + claims.put("jti", TOKEN_JTI.toString()); + claims.put("accountId", ACCOUNT_ID.toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", NOW.getEpochSecond()); + claims.put("nbf", NOW.getEpochSecond()); + claims.put("exp", NOW.plusSeconds(120L).getEpochSecond()); + claims.put("tokenGeneration", "1"); + claims.put("authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1L, 1L)); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", "1"); + return claims; + } + + private CommittedCandidateVerificationData candidate( + String compactJwt, UUID identityAccountId, boolean wrongHash, boolean wrongAuthority) { + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + identityAccountId, + GAME_SESSION_WORKLOAD, + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + "d".repeat(64), + TOKEN_JTI, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120L).getEpochSecond()); + UUID authorityAccountId = identityAccountId; + AccountAuthoritySnapshot authoritySnapshot = + wrongAuthority + ? new AccountAuthoritySnapshot( + authorityAccountId, + 1L, + 1L, + 2L, + 2L, + 2L, + 2L, + Optional.of( + new AccountSecurityCutoff( + "2", "account:auth-authority:v1:account/" + authorityAccountId, "1"))) + : new AccountAuthoritySnapshot( + authorityAccountId, 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty()); + CommittedCandidateVerificationData candidate = mock(CommittedCandidateVerificationData.class); + when(candidate.identity()).thenReturn(identity); + when(candidate.authoritySnapshot()).thenReturn(authoritySnapshot); + when(candidate.signerKid()).thenReturn(KID); + when(candidate.tokenSha256()).thenReturn(wrongHash ? "0".repeat(64) : sha256(compactJwt)); + return candidate; + } + + private String signedToken(KeyPair keyPair, Map claims) throws Exception { + String header = + base64Url(JSON.writeValueAsBytes(Map.of("alg", "RS256", "kid", KID, "typ", "JWT"))); + String payload = base64Url(JSON.writeValueAsBytes(claims)); + String input = header + "." + payload; + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(input.getBytes(StandardCharsets.US_ASCII)); + return input + "." + base64Url(signature.sign()); + } + } + + private static String markerJson( + UUID operationId, + String operationDigest, + String requestDigest, + String receiptDigest, + Binding binding, + BindingIdentity api, + String generation, + String kid, + String publicFingerprint) { + return "{\"schemaVersion\":1,\"phase\":\"PREPUBLISHED\",\"operationId\":\"" + + operationId + + "\",\"operationDigest\":\"" + + operationDigest + + "\",\"generationRequestDigest\":\"" + + requestDigest + + "\",\"generationReceiptDigest\":\"" + + receiptDigest + + "\",\"binding\":{\"environmentId\":\"" + + binding.environmentId() + + "\",\"clusterId\":\"" + + binding.clusterId() + + "\",\"namespace\":\"" + + binding.namespace() + + "\",\"expectedClusterIncarnationUid\":\"" + + binding.expectedClusterIncarnationUid() + + "\",\"expectedNamespaceUid\":\"" + + binding.expectedNamespaceUid() + + "\",\"trustBindingDigest\":\"" + + binding.bindingDigest() + + "\",\"trustConfigRevision\":\"" + + binding.configRevision() + + "\",\"apiBindingDigest\":\"" + + api.bindingDigest() + + "\",\"apiConfigRevision\":\"" + + api.configRevision() + + "\"},\"publicConfigMap\":{\"name\":\"jwt-jwks\"}," + + "\"expectedDurableActive\":{\"present\":false}," + + "\"expectedPublishedActive\":{\"present\":false}," + + "\"pending\":{\"generation\":\"" + + generation + + "\",\"kid\":\"" + + kid + + "\",\"algorithm\":\"RS256\",\"publicKeyFingerprint\":\"" + + publicFingerprint + + "\"}}"; + } + + private static String jwkJson(KeyPair keyPair, String kid) { + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + String json = + "{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\"" + + kid + + "\",\"key_ops\":[\"verify\"],\"n\":\"" + + base64Url(unsigned(publicKey.getModulus())) + + "\",\"e\":\"" + + base64Url(unsigned(publicKey.getPublicExponent())) + + "\"}"; + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (java.io.IOException malformedJwk) { + throw new IllegalStateException( + "Generated test JWK could not be canonicalized", malformedJwk); + } + } + + private static String fingerprint(RSAPublicKey publicKey) { + String canonicalRsaPublicJwk = + "{\"e\":\"" + + base64Url(unsigned(publicKey.getPublicExponent())) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsigned(publicKey.getModulus())) + + "\"}"; + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(canonicalRsaPublicJwk.getBytes(StandardCharsets.US_ASCII))); + } catch (Exception unavailable) { + throw new IllegalStateException(unavailable); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] encoded = value.toByteArray(); + return encoded.length > 1 && encoded[0] == 0 + ? Arrays.copyOfRange(encoded, 1, encoded.length) + : encoded; + } + + private static String base64Url(byte[] value) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (Exception unavailable) { + throw new IllegalStateException(unavailable); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java new file mode 100644 index 0000000000..1dea26640e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java @@ -0,0 +1,534 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.CALLS_REAL_METHODS; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountGameplayAdmissionLeaseGrpcServiceTest { + private static final String NAMESPACE = "game-session-admission-test"; + private static final UUID REQUEST_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + 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 OTHER_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION_ID = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID HOLD_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID DECISION_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final String HIGH = "9007199254740993"; + private static final String JWT = "header.transient-test-payload.signature"; + + private final AccountGameplayAdmissionLeaseOwner owner = + mock(AccountGameplayAdmissionLeaseOwner.class); + private final AccountGameplayAdmissionLeaseGrpcService service = + AccountGameplayAdmissionLeaseManualFactory.createUnregisteredReceiver(owner, NAMESPACE); + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesTheExactPeerBeforeInspectingEachOfTheFourRequests() { + for (Call call : callsWithDefaultRequests()) { + assertCode(call, null, Status.Code.UNAUTHENTICATED); + assertCode(call, peer(NAMESPACE, "world-management-service"), Status.Code.PERMISSION_DENIED); + assertCode(call, peer("other", "game-session-service"), Status.Code.PERMISSION_DENIED); + + SessionContext.setContext("123", List.of(), Map.of()); + assertCode(call, peer(NAMESPACE, "game-session-service"), Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "instance"); + assertCode(call, peer(NAMESPACE, "game-session-service"), Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + verifyNoInteractions(owner); + } + + @Test + void rejectsNullOversizedAndClosedShapeRequestsBeforeCallingOwner() { + assertCode( + observer -> service.acquireGameplayAdmissionLease(null, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + assertCode( + observer -> service.finalizeGameplayAdmissionLease(null, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + assertCode( + observer -> service.readGameplayAdmissionLease(null, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + assertCode( + observer -> service.abortGameplayAdmissionLease(null, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + + var oversizedAcquire = + AcquireGameplayAdmissionLeaseRequest.newBuilder() + .addPresentedInitialGsaCompactJwt( + "x" + .repeat( + AccountGameplayAdmissionLeaseGrpcCodec.MAX_ACQUIRE_REQUEST_WIRE_BYTES + 1)) + .build(); + ByteString oversizedOriginalBytes = + ByteString.copyFrom( + new byte + [AccountGameplayAdmissionLeaseGrpcCodec.MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES + 1]); + var oversizedFinalize = + FinalizeGameplayAdmissionLeaseRequest.newBuilder() + .addOriginalLeaseEvidenceUtf8(oversizedOriginalBytes) + .build(); + var oversizedRead = + ReadGameplayAdmissionLeaseRequest.newBuilder() + .addOriginalLeaseEvidenceUtf8(oversizedOriginalBytes) + .build(); + var oversizedAbort = + AbortGameplayAdmissionLeaseRequest.newBuilder() + .addOriginalLeaseEvidenceUtf8(oversizedOriginalBytes) + .build(); + assertCode( + observer -> service.acquireGameplayAdmissionLease(oversizedAcquire, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + assertCode( + observer -> service.finalizeGameplayAdmissionLease(oversizedFinalize, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + assertCode( + observer -> service.readGameplayAdmissionLease(oversizedRead, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + assertCode( + observer -> service.abortGameplayAdmissionLease(oversizedAbort, observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.INVALID_ARGUMENT); + + var malformedAcquire = + AcquireGameplayAdmissionLeaseRequest.newBuilder().addSchemaVersion(1).build(); + var malformedFinalize = FinalizeGameplayAdmissionLeaseRequest.newBuilder().build(); + var malformedRead = ReadGameplayAdmissionLeaseRequest.newBuilder().build(); + var malformedAbort = AbortGameplayAdmissionLeaseRequest.newBuilder().build(); + for (Call call : + List.of( + observer -> service.acquireGameplayAdmissionLease(malformedAcquire, observer), + observer -> service.finalizeGameplayAdmissionLease(malformedFinalize, observer), + observer -> service.readGameplayAdmissionLease(malformedRead, observer), + observer -> service.abortGameplayAdmissionLease(malformedAbort, observer))) { + assertCode(call, peer(NAMESPACE, "game-session-service"), Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(owner); + } + + @Test + void manualFactoryExposesExactlyTheFourPurposeSpecificMethodsWithoutSpringRegistration() { + assertThat(service.bindService().getServiceDescriptor().getMethods()) + .extracting(method -> method.getFullMethodName()) + .containsExactlyInAnyOrder( + "account.v1.AccountGameplayAdmissionLeaseService/AcquireGameplayAdmissionLease", + "account.v1.AccountGameplayAdmissionLeaseService/FinalizeGameplayAdmissionLease", + "account.v1.AccountGameplayAdmissionLeaseService/ReadGameplayAdmissionLease", + "account.v1.AccountGameplayAdmissionLeaseService/AbortGameplayAdmissionLease"); + } + + @Test + void rejectsAmbientTransactionBeforeParsing() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + observer -> + service.acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest.getDefaultInstance(), observer), + peer(NAMESPACE, "game-session-service"), + Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(owner); + } + + @Test + void rejectsForeignTargetNamespaceForAcquisitionAndAllOriginalLeaseMethods() { + var foreignAcquisition = acquisition("other"); + var foreignLease = lease("other"); + byte[] originalBytes = foreignLease.canonicalJson().getBytes(StandardCharsets.UTF_8); + var foreignFinalize = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest(JWT, originalBytes, DECISION_ID); + var foreignRead = AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(JWT, originalBytes); + var foreignAbort = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortRequest(JWT, originalBytes, null); + var peer = peer(NAMESPACE, "game-session-service"); + + assertCode( + observer -> service.acquireGameplayAdmissionLease(foreignAcquisition, observer), + peer, + Status.Code.PERMISSION_DENIED); + assertCode( + observer -> service.finalizeGameplayAdmissionLease(foreignFinalize, observer), + peer, + Status.Code.PERMISSION_DENIED); + assertCode( + observer -> service.readGameplayAdmissionLease(foreignRead, observer), + peer, + Status.Code.PERMISSION_DENIED); + assertCode( + observer -> service.abortGameplayAdmissionLease(foreignAbort, observer), + peer, + Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } + + @Test + void unexpectedParserRuntimeFailureTerminatesTheObserverWithoutCallingOwner() { + var request = acquisition(NAMESPACE); + // Fault injection checks the handler boundary, not a reproduced malformed-wire vector. + for (RuntimeException parserFailure : + List.of( + new NullPointerException("private parser detail " + JWT), + new IllegalStateException("private parser detail " + JWT))) { + try (var codec = + mockStatic(AccountGameplayAdmissionLeaseGrpcCodec.class, CALLS_REAL_METHODS)) { + codec + .when(() -> AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(request)) + .thenThrow(parserFailure); + var failed = new Capture(); + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> service.acquireGameplayAdmissionLease(request, failed)); + assertThat(failed.code()).isEqualTo(Status.Code.INTERNAL); + assertThat(failed.description) + .isEqualTo("Account gameplay admission lease operation denied or unavailable") + .doesNotContain(JWT, "private parser detail"); + assertThat(failed.failureHadCause).isFalse(); + assertThat(failed.errors).isEqualTo(1); + assertThat(failed.responses).isZero(); + assertThat(failed.completed).isFalse(); + codec.verify(() -> AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(request)); + } + } + verifyNoInteractions(owner); + } + + @Test + void ownerFailureIsSanitizedAndObserverCallbackFailureIsNotReclassified() { + var request = acquisition(NAMESPACE); + when(owner.acquire(any())) + .thenThrow( + Status.FAILED_PRECONDITION + .withDescription("private token detail") + .asRuntimeException()); + var failed = new Capture(); + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> service.acquireGameplayAdmissionLease(request, failed)); + assertThat(failed.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(failed.description) + .isEqualTo("Account gameplay admission lease operation denied or unavailable"); + assertThat(failed.description).doesNotContain("private token detail"); + verify(owner).acquire(request); + + doReturn(AccountGameplayAdmissionLeaseResponse.getDefaultInstance()).when(owner).acquire(any()); + var callbackFailure = new IllegalStateException("observer failure"); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(AccountGameplayAdmissionLeaseResponse value) { + throw callbackFailure; + } + + @Override + public void onError(Throwable failure) { + throw new AssertionError("callback must not be converted to an owner error", failure); + } + + @Override + public void onCompleted() { + throw new AssertionError("completion must not follow failed onNext"); + } + }; + assertThatThrownBy( + () -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> service.acquireGameplayAdmissionLease(request, observer))) + .isSameAs(callbackFailure); + } + + private List callsWithDefaultRequests() { + return List.of( + observer -> + service.acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest.getDefaultInstance(), observer), + observer -> + service.finalizeGameplayAdmissionLease( + FinalizeGameplayAdmissionLeaseRequest.getDefaultInstance(), observer), + observer -> + service.readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest.getDefaultInstance(), observer), + observer -> + service.abortGameplayAdmissionLease( + AbortGameplayAdmissionLeaseRequest.getDefaultInstance(), observer)); + } + + private void assertCode(Call call, GrpcPeerIdentity peer, Status.Code expected) { + var observer = new Capture(); + withPeer(peer, () -> call.invoke(observer)); + assertThat(observer.code()).isEqualTo(expected); + } + + private static void withPeer(GrpcPeerIdentity peer, Runnable action) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static AcquireGameplayAdmissionLeaseRequest acquisition(String namespace) { + Target target = target(namespace); + return AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + REQUEST_ID, JWT, candidate(), target, new BigInteger(HIGH)); + } + + private static Candidate candidate() { + return new Candidate( + ACCOUNT_ID, + TENANT_ID, + OTHER_ID, + OTHER_ID, + "SHARED", + OTHER_ID, + 71, + OTHER_ID, + OTHER_ID, + new BigInteger(HIGH), + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + new BigInteger(HIGH), + new BigInteger(HIGH), + new BigInteger(HIGH)); + } + + private static Target target(String namespace) { + var ownerRequest = + new WorldCanonicalInitialAdmissionHold.Request( + namespace, + TENANT_ID, + "world", + OTHER_ID, + OTHER_ID, + "SHARED", + OTHER_ID, + VERSION_ID, + new BigInteger(HIGH).longValueExact(), + REQUEST_ID.toString(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + new BigInteger(HIGH).longValueExact(), + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity(ownerRequest, HOLD_ID, HOLD_FENCE); + return new Target( + namespace, + "tenant", + TENANT_ID, + "world", + "World", + OTHER_ID, + "realm", + "Realm", + 11, + 71, + OTHER_ID, + "SHARED", + OTHER_ID, + VERSION_ID, + 99, + new BigInteger(HIGH).longValueExact(), + new BigInteger(HIGH).longValueExact(), + "d".repeat(64), + new BigInteger(HIGH).longValueExact(), + REQUEST_ID.toString(), + "c".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + HOLD_ID, + HOLD_FENCE, + hold.holdBindingDigest(), + 101, + "sha256:" + "a".repeat(64), + OwnerProofOutcome.COMMITTED, + false, + Instant.parse("2026-10-25T00:00:00Z"), + "PRESEEDED_ONLY"); + } + + private static AccountGameplayAdmissionLeaseEvidence lease(String namespace) { + Map value = new LinkedHashMap<>(); + String peerUri = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", namespace); + value.put("callerWorkload", peerUri); + value.put("requestId", REQUEST_ID.toString()); + value.put("leaseId", TENANT_ID.toString()); + value.put("leaseFence", HIGH); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", ACCOUNT_ID.toString()); + scope.put("tenantId", TENANT_ID.toString()); + scope.put("realmId", OTHER_ID.toString()); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateNamespaceId", OTHER_ID.toString()); + scope.put("playableStateScope", "SHARED"); + scope.put("gameInstanceId", OTHER_ID.toString()); + scope.put("characterId", OTHER_ID.toString()); + scope.put("sessionId", OTHER_ID.toString()); + scope.put("bindingGeneration", HIGH); + scope.put("catalogRevision", HIGH); + scope.put("pointerVersion", HIGH); + scope.put("regionId", OTHER_ID.toString()); + scope.put("regionEpoch", HIGH); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), HIGH), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), HIGH), + "privateRealmGrantVersions", List.of())); + value.put("issuanceFence", HIGH); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT_ID.toString(), HIGH), + "membershipAuthorityGeneration", + HIGH)); + List> checkpoints = new ArrayList<>(); + for (String suffix : + List.of( + "account/" + ACCOUNT_ID, + "issuer/firemud-account-service", + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, + "tenant/" + TENANT_ID)) { + checkpoints.add( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : HIGH)); + } + value.put("outboxCheckpoints", checkpoints); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("operationId", OTHER_ID.toString()), + Map.entry("issuanceRequestId", OTHER_ID.toString()), + Map.entry("tokenJti", OTHER_ID.toString()), + Map.entry("tokenSHA256", jwtSha256(JWT)), + Map.entry("tokenGeneration", HIGH), + Map.entry("issuanceFence", HIGH), + Map.entry("tokenIdentityFence", HIGH), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", "999"), + Map.entry("notBefore", "999"), + Map.entry("expiresAt", "1300"))); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + private static String jwtSha256(String jwt) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(jwt.getBytes(StandardCharsets.UTF_8))); + } catch (Exception unavailable) { + throw new IllegalStateException("SHA-256 unavailable"); + } + } + + private interface Call { + void invoke(StreamObserver observer); + } + + private static final class Capture + implements StreamObserver { + private Status.Code code; + private String description; + private boolean failureHadCause; + private int errors; + private int responses; + private boolean completed; + + @Override + public void onNext(AccountGameplayAdmissionLeaseResponse value) { + responses++; + } + + @Override + public void onError(Throwable failure) { + failureHadCause = failure.getCause() != null; + errors++; + Status status = Status.fromThrowable(failure); + code = status.getCode(); + description = status.getDescription(); + } + + @Override + public void onCompleted() { + completed = true; + } + + private Status.Code code() { + return code; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuardTest.java new file mode 100644 index 0000000000..a64c5a8619 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseWorkloadGuardTest.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; + +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class AccountGameplayAdmissionLeaseWorkloadGuardTest { + private static final String NAMESPACE = "game-session-admission-test"; + private final AccountGameplayAdmissionLeaseWorkloadGuard guard = + new AccountGameplayAdmissionLeaseWorkloadGuard(NAMESPACE); + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void authenticatesBeforeStartingAnyOfTheFourAllowedHandlers() { + for (MethodDescriptor method : leaseMethods()) { + Invocation missing = invoke(method, null); + assertThat(missing.nextStarts()).isZero(); + assertThat(missing.status().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(missing.status().getDescription()) + .isEqualTo("Exact same-namespace Game Session workload required"); + assertThat(missing.status().getCause()).isNull(); + + Invocation wrongService = invoke(method, peer(NAMESPACE, "account-service")); + assertThat(wrongService.nextStarts()).isZero(); + assertThat(wrongService.status().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + + Invocation wrongNamespace = invoke(method, peer("other", "game-session-service")); + assertThat(wrongNamespace.nextStarts()).isZero(); + assertThat(wrongNamespace.status().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + } + + @Test + void onlyTheFourExactGeneratedLeaseDescriptorsReachTheNextHandler() { + for (MethodDescriptor method : leaseMethods()) { + Invocation accepted = invoke(method, peer(NAMESPACE, "game-session-service")); + assertThat(accepted.nextStarts()).isEqualTo(1); + assertThat(accepted.status()).isNull(); + } + + MethodDescriptor otherPurpose = AccountServiceGrpc.getGetProfileMethod(); + Invocation rejected = invoke(otherPurpose, peer(NAMESPACE, "game-session-service")); + assertThat(rejected.nextStarts()).isZero(); + assertThat(rejected.status().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(rejected.status().getDescription()) + .isEqualTo("Account gameplay admission lease method required"); + assertThat(rejected.status().getCause()).isNull(); + } + + @Test + void rejectsEndUserAndGenericInternalSessionContextsBeforeStartingHandler() { + for (boolean internal : List.of(false, true)) { + if (internal) { + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-session-service", "instance"); + } else { + SessionContext.setContext("123", List.of(), Map.of()); + } + Invocation rejected = + invoke( + AccountGameplayAdmissionLeaseServiceGrpc.getReadGameplayAdmissionLeaseMethod(), + peer(NAMESPACE, "game-session-service")); + assertThat(rejected.nextStarts()).isZero(); + assertThat(rejected.status().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + } + } + + private static List> leaseMethods() { + return List.of( + AccountGameplayAdmissionLeaseServiceGrpc.getAcquireGameplayAdmissionLeaseMethod(), + AccountGameplayAdmissionLeaseServiceGrpc.getFinalizeGameplayAdmissionLeaseMethod(), + AccountGameplayAdmissionLeaseServiceGrpc.getReadGameplayAdmissionLeaseMethod(), + AccountGameplayAdmissionLeaseServiceGrpc.getAbortGameplayAdmissionLeaseMethod()); + } + + private Invocation invoke(MethodDescriptor method, GrpcPeerIdentity peer) { + return invokeTyped(method, peer); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private Invocation invokeTyped(MethodDescriptor method, GrpcPeerIdentity peer) { + ServerCall call = mock(ServerCall.class); + org.mockito.Mockito.when(call.getMethodDescriptor()).thenReturn(method); + AtomicInteger starts = new AtomicInteger(); + ServerCallHandler next = + (ignoredCall, ignoredHeaders) -> { + starts.incrementAndGet(); + return new ServerCall.Listener() {}; + }; + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run(() -> guard.interceptCall(call, new Metadata(), next)); + org.mockito.ArgumentCaptor status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call, org.mockito.Mockito.atMostOnce()) + .close(status.capture(), any(Metadata.class)); + return new Invocation(starts.get(), status.getAllValues().isEmpty() ? null : status.getValue()); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private record Invocation(int nextStarts, Status status) {} +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java index f7203482ba..9ff5ae2fbd 100644 --- a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java @@ -140,6 +140,7 @@ public enum ScriptCategory { TICK_LOCK, TIMER_QUEUE, SESSION_CAS, + SESSION_ACCOUNT_INDEX, SESSION_TO_REGION_BRIDGE, MAINTENANCE, CACHE, diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java new file mode 100644 index 0000000000..97799f0d09 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodec.java @@ -0,0 +1,1128 @@ +package net.firedevops.firemud.common.account.admission; + +import com.google.protobuf.ByteString; +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.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseState; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionOriginalAckReceiptEvidence; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; +import net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence; + +/** + * Closed schema-1 transport mapping for Account's exact original public-production NEW lease. + * + *

Parsed values establish shape, unchanged bytes, and request/result consistency only. They do + * not authenticate the presented JWT, establish current Account authority, prove physical COMMIT or + * receipt durability, or authorize Game Session admission. + */ +public final class AccountGameplayAdmissionLeaseGrpcCodec { + public static final int MAX_ACQUIRE_REQUEST_WIRE_BYTES = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES + + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + + 1024; + public static final int MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES = + AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + + 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = + AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 8 * 1024; + + private static final int SCHEMA_VERSION = 1; + private static final BigInteger UINT64_MAX = + BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private AccountGameplayAdmissionLeaseGrpcCodec() {} + + /** Parsed acquisition request. Its GSA credential is transient and redacted from diagnostics. */ + public static final class AcquireRequest { + private final UUID requestId; + private final String presentedInitialGsACompactJwt; + private final Candidate expectedCandidate; + private final Target expectedTarget; + private final BigInteger bindingGeneration; + + private AcquireRequest( + UUID requestId, + String presentedInitialGsACompactJwt, + Candidate expectedCandidate, + Target expectedTarget, + BigInteger bindingGeneration) { + this.requestId = requestId; + this.presentedInitialGsACompactJwt = presentedInitialGsACompactJwt; + this.expectedCandidate = expectedCandidate; + this.expectedTarget = expectedTarget; + this.bindingGeneration = bindingGeneration; + } + + public UUID requestId() { + return requestId; + } + + public String presentedInitialGsACompactJwt() { + return presentedInitialGsACompactJwt; + } + + public Candidate expectedCandidate() { + return expectedCandidate; + } + + public Target expectedTarget() { + return expectedTarget; + } + + public BigInteger bindingGeneration() { + return bindingGeneration; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest[redacted]"; + } + } + + /** One exact original-operation request; construction is restricted to this codec. */ + public static final class OriginalLeaseRequest { + private final OriginalLeasePurpose purpose; + private final String presentedInitialGsACompactJwt; + private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; + private final byte[] originalLeaseEvidenceUtf8; + private final UUID bindingDecisionId; + + private OriginalLeaseRequest( + OriginalLeasePurpose purpose, + String presentedInitialGsACompactJwt, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + byte[] originalLeaseEvidenceUtf8, + UUID bindingDecisionId) { + this.purpose = purpose; + this.presentedInitialGsACompactJwt = presentedInitialGsACompactJwt; + this.originalLeaseEvidence = originalLeaseEvidence; + this.originalLeaseEvidenceUtf8 = originalLeaseEvidenceUtf8.clone(); + this.bindingDecisionId = bindingDecisionId; + } + + public String presentedInitialGsACompactJwt() { + return presentedInitialGsACompactJwt; + } + + public AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence() { + return originalLeaseEvidence; + } + + public byte[] originalLeaseEvidenceUtf8() { + return originalLeaseEvidenceUtf8.clone(); + } + + /** Null means that the decision identity is unknown, never that no decision exists. */ + public UUID bindingDecisionId() { + return bindingDecisionId; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest[redacted]"; + } + } + + /** Complete original-operation response shape with a redacted, typed receipt carrier. */ + public static final class OperationEvidence { + private final AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence; + private final State state; + private final UUID bindingDecisionId; + private final UUID orphanCleanupId; + private final OriginalAckReceiptEvidence originalAckReceipt; + + private OperationEvidence( + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence originalAckReceipt) { + this.originalLeaseEvidence = originalLeaseEvidence; + this.state = state; + this.bindingDecisionId = bindingDecisionId; + this.orphanCleanupId = orphanCleanupId; + this.originalAckReceipt = originalAckReceipt; + } + + public AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence() { + return originalLeaseEvidence; + } + + public State state() { + return state; + } + + public UUID bindingDecisionId() { + return bindingDecisionId; + } + + public UUID orphanCleanupId() { + return orphanCleanupId; + } + + public OriginalAckReceiptEvidence originalAckReceipt() { + return originalAckReceipt; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence[state=" + state + "]"; + } + } + + /** Typed Common carrier for original-ACK receipt fields; it proves no receipt durability. */ + public static final class OriginalAckReceiptEvidence { + private final int schemaVersion; + private final UUID requestId; + private final UUID accountId; + private final UUID leaseId; + private final long leaseFence; + private final String evidenceSha256; + private final UUID bindingDecisionId; + private final long expiresAtMs; + private final String finalizationXid; + private final long committedBeforeMs; + private final String receiptXid; + + private OriginalAckReceiptEvidence( + int schemaVersion, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence, + String evidenceSha256, + UUID bindingDecisionId, + long expiresAtMs, + String finalizationXid, + long committedBeforeMs, + String receiptXid) { + this.schemaVersion = schemaVersion; + this.requestId = Objects.requireNonNull(requestId, "requestId"); + this.accountId = Objects.requireNonNull(accountId, "accountId"); + this.leaseId = Objects.requireNonNull(leaseId, "leaseId"); + this.leaseFence = leaseFence; + this.evidenceSha256 = Objects.requireNonNull(evidenceSha256, "evidenceSha256"); + this.bindingDecisionId = Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); + this.expiresAtMs = expiresAtMs; + this.finalizationXid = Objects.requireNonNull(finalizationXid, "finalizationXid"); + this.committedBeforeMs = committedBeforeMs; + this.receiptXid = Objects.requireNonNull(receiptXid, "receiptXid"); + validateReceiptShape(this); + } + + /** + * Builds a shape-only typed receipt from Account DTO fields; this does not prove durability. + */ + public static OriginalAckReceiptEvidence fromFields( + int schemaVersion, + UUID requestId, + UUID accountId, + UUID leaseId, + long leaseFence, + String evidenceSha256, + UUID bindingDecisionId, + long expiresAtMs, + String finalizationXid, + long committedBeforeMs, + String receiptXid) { + return new OriginalAckReceiptEvidence( + schemaVersion, + requestId, + accountId, + leaseId, + leaseFence, + evidenceSha256, + bindingDecisionId, + expiresAtMs, + finalizationXid, + committedBeforeMs, + receiptXid); + } + + public int schemaVersion() { + return schemaVersion; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public UUID leaseId() { + return leaseId; + } + + public long leaseFence() { + return leaseFence; + } + + public String evidenceSha256() { + return evidenceSha256; + } + + public UUID bindingDecisionId() { + return bindingDecisionId; + } + + public long expiresAtMs() { + return expiresAtMs; + } + + public String finalizationXid() { + return finalizationXid; + } + + public long committedBeforeMs() { + return committedBeforeMs; + } + + public String receiptXid() { + return receiptXid; + } + + @Override + public String toString() { + return "AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence[redacted]"; + } + } + + public enum State { + PENDING, + COMMITTED, + ABORTED + } + + /** + * Serializes an expected acquisition request through the same closed parser used by receivers. + */ + public static AcquireGameplayAdmissionLeaseRequest toAcquireRequest( + UUID requestId, + String presentedInitialGsACompactJwt, + Candidate expectedCandidate, + Target expectedTarget, + BigInteger bindingGeneration) { + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(expectedCandidate, "expectedCandidate"); + Objects.requireNonNull(expectedTarget, "expectedTarget"); + Objects.requireNonNull(bindingGeneration, "bindingGeneration"); + var request = + AcquireGameplayAdmissionLeaseRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addRequestUuid(requestId.toString()) + .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) + .addExpectedCandidate( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toCandidate(expectedCandidate)) + .addExpectedTarget( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetEvidence(expectedTarget)) + .addBindingGeneration(positiveDecimal(bindingGeneration)) + .build(); + requireWireSize(request.getSerializedSize(), MAX_ACQUIRE_REQUEST_WIRE_BYTES, "acquire request"); + parseAcquireRequest(request); + return request; + } + + /** Parses an acquisition request; expected values remain Account comparison inputs only. */ + public static AcquireRequest parseAcquireRequest(AcquireGameplayAdmissionLeaseRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize(request.getSerializedSize(), MAX_ACQUIRE_REQUEST_WIRE_BYTES, "acquire request"); + requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "acquire request"); + requireSchema(one(request.getSchemaVersionList(), "acquire.schemaVersion")); + UUID requestId = highEntropyUuid(one(request.getRequestUuidList(), "acquire.requestId")); + String compactJwt = + compactJwt(one(request.getPresentedInitialGsaCompactJwtList(), "acquire.presentedJwt")); + CanonicalGameplayAdmissionCandidate candidateMessage = + one(request.getExpectedCandidateList(), "acquire.expectedCandidate"); + Candidate candidate = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseCandidate(candidateMessage); + if (!CanonicalGameplayAdmissionDecisionReadGrpcCodec.toCandidate(candidate) + .equals(candidateMessage)) { + throw invalid("Acquire candidate is not its exact existing closed encoding"); + } + CanonicalPlayableTargetEvidence targetMessage = + one(request.getExpectedTargetList(), "acquire.expectedTarget"); + Target target = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetEvidence(targetMessage); + if (!CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetEvidence(target) + .equals(targetMessage)) { + throw invalid("Acquire target is not its exact existing closed encoding"); + } + requireAcquireCandidateMatchesTarget(candidate, target); + BigInteger generation = + AccountJwtExactValues.positiveDecimalCounter( + one(request.getBindingGenerationList(), "acquire.bindingGeneration")); + return new AcquireRequest(requestId, compactJwt, candidate, target, generation); + } + + public static FinalizeGameplayAdmissionLeaseRequest toFinalizeRequest( + String presentedInitialGsACompactJwt, + byte[] originalLeaseEvidenceUtf8, + UUID bindingDecisionId) { + Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); + byte[] leaseBytes = requireOriginalLeaseEvidenceBytes(originalLeaseEvidenceUtf8); + var request = + FinalizeGameplayAdmissionLeaseRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)) + .addBindingDecisionUuid(highEntropyUuid(bindingDecisionId).toString()) + .build(); + requireWireSize( + request.getSerializedSize(), MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, "finalize request"); + parseFinalizeRequest(request); + return request; + } + + public static OriginalLeaseRequest parseFinalizeRequest( + FinalizeGameplayAdmissionLeaseRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, "finalize request"); + requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "finalize request"); + requireSchema(one(request.getSchemaVersionList(), "finalize.schemaVersion")); + String compactJwt = + compactJwt(one(request.getPresentedInitialGsaCompactJwtList(), "finalize.presentedJwt")); + byte[] leaseBytes = + one(request.getOriginalLeaseEvidenceUtf8List(), "finalize.originalLeaseEvidenceUtf8") + .toByteArray(); + AccountGameplayAdmissionLeaseEvidence evidence = parseFreshNewLease(leaseBytes); + requirePresentedJwtMatchesLease(evidence, compactJwt); + UUID decisionId = + highEntropyUuid(one(request.getBindingDecisionUuidList(), "finalize.decisionId")); + return new OriginalLeaseRequest( + OriginalLeasePurpose.FINALIZE, compactJwt, evidence, leaseBytes, decisionId); + } + + public static ReadGameplayAdmissionLeaseRequest toReadRequest( + String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { + byte[] leaseBytes = requireOriginalLeaseEvidenceBytes(originalLeaseEvidenceUtf8); + var request = + ReadGameplayAdmissionLeaseRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)) + .build(); + requireWireSize( + request.getSerializedSize(), MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, "read request"); + parseReadRequest(request); + return request; + } + + public static OriginalLeaseRequest parseReadRequest(ReadGameplayAdmissionLeaseRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, "read request"); + requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "read request"); + requireSchema(one(request.getSchemaVersionList(), "read.schemaVersion")); + String compactJwt = + compactJwt(one(request.getPresentedInitialGsaCompactJwtList(), "read.presentedJwt")); + byte[] leaseBytes = + one(request.getOriginalLeaseEvidenceUtf8List(), "read.originalLeaseEvidenceUtf8") + .toByteArray(); + AccountGameplayAdmissionLeaseEvidence evidence = parseFreshNewLease(leaseBytes); + requirePresentedJwtMatchesLease(evidence, compactJwt); + return new OriginalLeaseRequest( + OriginalLeasePurpose.READ, compactJwt, evidence, leaseBytes, null); + } + + public static AbortGameplayAdmissionLeaseRequest toAbortRequest( + String presentedInitialGsACompactJwt, + byte[] originalLeaseEvidenceUtf8, + UUID bindingDecisionId) { + byte[] leaseBytes = requireOriginalLeaseEvidenceBytes(originalLeaseEvidenceUtf8); + var builder = + AbortGameplayAdmissionLeaseRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addPresentedInitialGsaCompactJwt(compactJwt(presentedInitialGsACompactJwt)) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)); + if (bindingDecisionId != null) { + builder.addBindingDecisionUuid(highEntropyUuid(bindingDecisionId).toString()); + } + var request = builder.build(); + requireWireSize( + request.getSerializedSize(), MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, "abort request"); + parseAbortRequest(request); + return request; + } + + public static OriginalLeaseRequest parseAbortRequest(AbortGameplayAdmissionLeaseRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES, "abort request"); + requireNoUnknownFields(request.getUnknownFields().asMap().isEmpty(), "abort request"); + requireSchema(one(request.getSchemaVersionList(), "abort.schemaVersion")); + String compactJwt = + compactJwt(one(request.getPresentedInitialGsaCompactJwtList(), "abort.presentedJwt")); + byte[] leaseBytes = + one(request.getOriginalLeaseEvidenceUtf8List(), "abort.originalLeaseEvidenceUtf8") + .toByteArray(); + AccountGameplayAdmissionLeaseEvidence evidence = parseFreshNewLease(leaseBytes); + requirePresentedJwtMatchesLease(evidence, compactJwt); + String decisionText = optional(request.getBindingDecisionUuidList(), "abort.decisionId"); + UUID decisionId = decisionText == null ? null : highEntropyUuid(decisionText); + return new OriginalLeaseRequest( + OriginalLeasePurpose.ABORT, compactJwt, evidence, leaseBytes, decisionId); + } + + /** + * Serializes a complete original-operation response and revalidates it against the acquisition. + */ + public static AccountGameplayAdmissionLeaseResponse toAcquireResponse( + AcquireRequest request, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence originalAckReceipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(originalLeaseEvidence, "originalLeaseEvidence"); + byte[] leaseBytes = canonicalLeaseBytes(originalLeaseEvidence); + AccountGameplayAdmissionLeaseResponse response = + buildResponse( + leaseBytes, + originalLeaseEvidence, + state, + bindingDecisionId, + orphanCleanupId, + originalAckReceipt); + parseAcquireResponse(request, response); + return response; + } + + public static AccountGameplayAdmissionLeaseResponse toFinalizeResponse( + OriginalLeaseRequest request, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence originalAckReceipt) { + requirePurpose(request, OriginalLeasePurpose.FINALIZE); + return toOriginalLeaseResponse( + request, + originalLeaseEvidence, + state, + bindingDecisionId, + orphanCleanupId, + originalAckReceipt); + } + + public static AccountGameplayAdmissionLeaseResponse toReadResponse( + OriginalLeaseRequest request, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence originalAckReceipt) { + requirePurpose(request, OriginalLeasePurpose.READ); + return toOriginalLeaseResponse( + request, + originalLeaseEvidence, + state, + bindingDecisionId, + orphanCleanupId, + originalAckReceipt); + } + + public static AccountGameplayAdmissionLeaseResponse toAbortResponse( + OriginalLeaseRequest request, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence originalAckReceipt) { + requirePurpose(request, OriginalLeasePurpose.ABORT); + return toOriginalLeaseResponse( + request, + originalLeaseEvidence, + state, + bindingDecisionId, + orphanCleanupId, + originalAckReceipt); + } + + public static OperationEvidence parseAcquireResponse( + AcquireRequest request, AccountGameplayAdmissionLeaseResponse response) { + Objects.requireNonNull(request, "request"); + OperationEvidence evidence = parseResponse(response); + requireAcquireLeaseMatchesRequest(request, evidence.originalLeaseEvidence()); + requirePresentedJwtMatchesLease( + evidence.originalLeaseEvidence(), request.presentedInitialGsACompactJwt()); + return evidence; + } + + private static void requireAcquireCandidateMatchesTarget(Candidate candidate, Target target) { + if (!candidate.tenantId().equals(target.canonicalTenantId()) + || !candidate.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !candidate.playableStateScope().equals(target.playableStateScope()) + || !candidate.gameInstanceId().equals(target.canonicalGameInstanceId()) + || candidate.runtimeGameInstanceId() != target.gameInstanceId()) { + throw invalid("Expected candidate differs from its exact target identity"); + } + } + + private static void requireAcquireLeaseMatchesRequest( + AcquireRequest request, AccountGameplayAdmissionLeaseEvidence lease) { + Map carrier = lease.carrier(); + Map scope = object(carrier.get("bindingScope"), "bindingScope"); + Map authorityTuple = object(carrier.get("authorityTuple"), "authorityTuple"); + Candidate candidate = request.expectedCandidate(); + Target target = request.expectedTarget(); + boolean matches = + request.requestId().equals(highEntropyUuid(string(carrier, "requestId"))) + && request + .bindingGeneration() + .equals(positiveCounter(string(scope, "bindingGeneration"))) + && candidate.accountId().toString().equals(string(scope, "accountId")) + && candidate.tenantId().toString().equals(string(scope, "tenantId")) + && target.canonicalTenantId().toString().equals(string(scope, "tenantId")) + && target.realmId().toString().equals(string(scope, "realmId")) + && target.worldSlug().equals(string(scope, "worldSlug")) + && target.realmSlug().equals(string(scope, "realmSlug")) + && candidate + .playableStateNamespaceId() + .toString() + .equals(string(scope, "playableStateNamespaceId")) + && target + .playableStateNamespaceId() + .toString() + .equals(string(scope, "playableStateNamespaceId")) + && candidate.playableStateScope().equals(string(scope, "playableStateScope")) + && target.playableStateScope().equals(string(scope, "playableStateScope")) + && candidate.gameInstanceId().toString().equals(string(scope, "gameInstanceId")) + && target.canonicalGameInstanceId().toString().equals(string(scope, "gameInstanceId")) + && candidate.characterId().toString().equals(string(scope, "characterId")) + && candidate.sessionId().toString().equals(string(scope, "sessionId")) + && Long.toString(target.catalogRevision()).equals(string(scope, "catalogRevision")) + && Long.toString(target.pointerVersion()).equals(string(scope, "pointerVersion")) + && candidate.regionId().toString().equals(string(scope, "regionId")) + && candidate.regionEpoch().toString().equals(string(scope, "regionEpoch")) + && candidate + .issuerAuthGeneration() + .toString() + .equals(string(authorityTuple, "issuerAuthGeneration")); + if (!matches) { + throw invalid("Acquire lease changed an exact expected binding-scope value"); + } + // Target version, private row IDs, and owner-proof fields do not exist in the lease. Account + // must retain their independent fresh-target comparisons at its owning boundary. + } + + private static void requirePresentedJwtMatchesLease( + AccountGameplayAdmissionLeaseEvidence lease, String presentedInitialGsACompactJwt) { + Map tokenIdentity = + object(lease.carrier().get("tokenIdentityEvidence"), "tokenIdentityEvidence"); + if (!compactJwtSha256(presentedInitialGsACompactJwt) + .equals(string(tokenIdentity, "tokenSHA256"))) { + throw invalid("Presented initial GSA credential changed the exact lease token identity"); + } + } + + public static OperationEvidence parseFinalizeResponse( + OriginalLeaseRequest request, AccountGameplayAdmissionLeaseResponse response) { + requirePurpose(request, OriginalLeasePurpose.FINALIZE); + return parseOriginalLeaseResponse(request, response); + } + + public static OperationEvidence parseReadResponse( + OriginalLeaseRequest request, AccountGameplayAdmissionLeaseResponse response) { + requirePurpose(request, OriginalLeasePurpose.READ); + return parseOriginalLeaseResponse(request, response); + } + + public static OperationEvidence parseAbortResponse( + OriginalLeaseRequest request, AccountGameplayAdmissionLeaseResponse response) { + requirePurpose(request, OriginalLeasePurpose.ABORT); + return parseOriginalLeaseResponse(request, response); + } + + private static AccountGameplayAdmissionLeaseResponse toOriginalLeaseResponse( + OriginalLeaseRequest request, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence originalAckReceipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(originalLeaseEvidence, "originalLeaseEvidence"); + if (!request.originalLeaseEvidence().hasSameIdentity(originalLeaseEvidence) + || !request + .originalLeaseEvidence() + .hasSameIdentity(parseFreshNewLease(request.originalLeaseEvidenceUtf8()))) { + throw invalid("Owner readback differs from the exact original lease request"); + } + if (request.purpose == OriginalLeasePurpose.FINALIZE + && bindingDecisionId != null + && !bindingDecisionId.equals(request.bindingDecisionId())) { + throw invalid("Finalization response changed the requested decision identity"); + } + AccountGameplayAdmissionLeaseResponse response = + buildResponse( + request.originalLeaseEvidenceUtf8(), + originalLeaseEvidence, + state, + bindingDecisionId, + orphanCleanupId, + originalAckReceipt); + parseOriginalLeaseResponse(request, response); + return response; + } + + private static OperationEvidence parseOriginalLeaseResponse( + OriginalLeaseRequest request, AccountGameplayAdmissionLeaseResponse response) { + Objects.requireNonNull(request, "request"); + OperationEvidence evidence = parseResponse(response); + byte[] actualLeaseBytes = response.getOriginalLeaseEvidenceUtf8(0).toByteArray(); + if (!Arrays.equals(request.originalLeaseEvidenceUtf8, actualLeaseBytes) + || !request.originalLeaseEvidence().hasSameIdentity(evidence.originalLeaseEvidence())) { + throw invalid("Response changed the complete original lease bytes"); + } + if (request.bindingDecisionId() != null + && evidence.bindingDecisionId() != null + && !request.bindingDecisionId().equals(evidence.bindingDecisionId())) { + throw invalid("Response changed the supplied binding decision identity"); + } + return evidence; + } + + private static AccountGameplayAdmissionLeaseResponse buildResponse( + byte[] originalLeaseEvidenceUtf8, + AccountGameplayAdmissionLeaseEvidence originalLeaseEvidence, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence originalAckReceipt) { + Objects.requireNonNull(originalLeaseEvidenceUtf8, "originalLeaseEvidenceUtf8"); + Objects.requireNonNull(originalLeaseEvidence, "originalLeaseEvidence"); + Objects.requireNonNull(state, "state"); + byte[] canonicalBytes = canonicalLeaseBytes(originalLeaseEvidence); + if (!Arrays.equals(originalLeaseEvidenceUtf8, canonicalBytes) + || !originalLeaseEvidence.hasSameIdentity(parseFreshNewLease(originalLeaseEvidenceUtf8))) { + throw invalid("Response must preserve the complete canonical original lease"); + } + requireFreshNewLease(originalLeaseEvidence); + UUID decisionId = bindingDecisionId == null ? null : highEntropyUuid(bindingDecisionId); + UUID cleanupId = orphanCleanupId == null ? null : highEntropyUuid(orphanCleanupId); + validateOperationState(originalLeaseEvidence, state, decisionId, cleanupId, originalAckReceipt); + + var builder = + AccountGameplayAdmissionLeaseResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(originalLeaseEvidenceUtf8)) + .addState(toWireState(state)); + if (decisionId != null) builder.addBindingDecisionUuid(decisionId.toString()); + if (cleanupId != null) builder.addOrphanCleanupUuid(cleanupId.toString()); + if (originalAckReceipt != null) + builder.addOriginalAckReceipt(toWireReceipt(originalAckReceipt)); + AccountGameplayAdmissionLeaseResponse response = builder.build(); + requireWireSize(response.getSerializedSize(), MAX_RESPONSE_WIRE_BYTES, "lease response"); + return response; + } + + private static OperationEvidence parseResponse(AccountGameplayAdmissionLeaseResponse response) { + Objects.requireNonNull(response, "response"); + requireWireSize(response.getSerializedSize(), MAX_RESPONSE_WIRE_BYTES, "lease response"); + requireNoUnknownFields(response.getUnknownFields().asMap().isEmpty(), "lease response"); + requireSchema(one(response.getSchemaVersionList(), "response.schemaVersion")); + byte[] leaseBytes = + one(response.getOriginalLeaseEvidenceUtf8List(), "response.leaseEvidence").toByteArray(); + AccountGameplayAdmissionLeaseEvidence lease = parseFreshNewLease(leaseBytes); + State state = fromWireState(one(response.getStateValueList(), "response.state")); + String decisionText = + optional(response.getBindingDecisionUuidList(), "response.bindingDecisionId"); + String cleanupText = optional(response.getOrphanCleanupUuidList(), "response.orphanCleanupId"); + UUID decisionId = decisionText == null ? null : highEntropyUuid(decisionText); + UUID cleanupId = cleanupText == null ? null : highEntropyUuid(cleanupText); + AccountGameplayAdmissionOriginalAckReceiptEvidence receiptMessage = + optional(response.getOriginalAckReceiptList(), "response.originalAckReceipt"); + OriginalAckReceiptEvidence receipt = + receiptMessage == null ? null : fromWireReceipt(receiptMessage); + validateOperationState(lease, state, decisionId, cleanupId, receipt); + return new OperationEvidence(lease, state, decisionId, cleanupId, receipt); + } + + private static void validateOperationState( + AccountGameplayAdmissionLeaseEvidence lease, + State state, + UUID bindingDecisionId, + UUID orphanCleanupId, + OriginalAckReceiptEvidence receipt) { + requireFreshNewLease(lease); + switch (state) { + case PENDING -> { + if (bindingDecisionId != null || orphanCleanupId != null || receipt != null) { + throw invalid("PENDING response must not carry terminal evidence"); + } + } + case COMMITTED -> { + if (bindingDecisionId == null || orphanCleanupId != null || receipt == null) { + throw invalid("COMMITTED response requires its decision and complete ACK receipt"); + } + validateReceiptMatches(lease, bindingDecisionId, receipt); + } + case ABORTED -> { + if (orphanCleanupId == null || receipt != null) { + throw invalid("ABORTED response requires pending cleanup and no ACK receipt"); + } + } + } + } + + private static void validateReceiptMatches( + AccountGameplayAdmissionLeaseEvidence lease, + UUID bindingDecisionId, + OriginalAckReceiptEvidence receipt) { + Map carrier = lease.carrier(); + Map scope = object(carrier.get("bindingScope"), "bindingScope"); + UUID requestId = highEntropyUuid(string(carrier, "requestId")); + UUID accountId = canonicalNonNilUuid(string(scope, "accountId")); + UUID leaseId = highEntropyUuid(string(carrier, "leaseId")); + long leaseFence = positiveLong(lease.leaseFence()); + long expiresAtMs = positiveLongDecimal(string(carrier, "expiresAt"), "expiresAt"); + if (receipt.schemaVersion() != 1 + || !receipt.requestId().equals(requestId) + || !receipt.accountId().equals(accountId) + || !receipt.leaseId().equals(leaseId) + || receipt.leaseFence() != leaseFence + || !receipt.evidenceSha256().equals(lease.sha256()) + || !receipt.bindingDecisionId().equals(bindingDecisionId) + || receipt.expiresAtMs() != expiresAtMs + || receipt.committedBeforeMs() >= expiresAtMs) { + throw invalid("Original ACK receipt differs from the exact committed lease operation"); + } + } + + private static AccountGameplayAdmissionOriginalAckReceiptEvidence toWireReceipt( + OriginalAckReceiptEvidence receipt) { + return AccountGameplayAdmissionOriginalAckReceiptEvidence.newBuilder() + .addSchemaVersion(receipt.schemaVersion()) + .addRequestUuid(receipt.requestId().toString()) + .addAccountUuid(receipt.accountId().toString()) + .addLeaseUuid(receipt.leaseId().toString()) + .addLeaseFence(Long.toString(receipt.leaseFence())) + .addEvidenceSha256(receipt.evidenceSha256()) + .addBindingDecisionUuid(receipt.bindingDecisionId().toString()) + .addExpiresAtMs(Long.toString(receipt.expiresAtMs())) + .addFinalizationXid(receipt.finalizationXid()) + .addCommittedBeforeMs(Long.toString(receipt.committedBeforeMs())) + .addReceiptXid(receipt.receiptXid()) + .build(); + } + + private static OriginalAckReceiptEvidence fromWireReceipt( + AccountGameplayAdmissionOriginalAckReceiptEvidence message) { + requireNoUnknownFields(message.getUnknownFields().asMap().isEmpty(), "ACK receipt"); + int schema = one(message.getSchemaVersionList(), "ACK.schemaVersion"); + return new OriginalAckReceiptEvidence( + schema, + highEntropyUuid(one(message.getRequestUuidList(), "ACK.requestId")), + canonicalNonNilUuid(one(message.getAccountUuidList(), "ACK.accountId")), + highEntropyUuid(one(message.getLeaseUuidList(), "ACK.leaseId")), + positiveLongDecimal(one(message.getLeaseFenceList(), "ACK.leaseFence"), "ACK.leaseFence"), + digest(one(message.getEvidenceSha256List(), "ACK.evidenceSha256")), + highEntropyUuid(one(message.getBindingDecisionUuidList(), "ACK.bindingDecisionId")), + positiveLongDecimal( + one(message.getExpiresAtMsList(), "ACK.expiresAtMs"), "ACK.expiresAtMs"), + xid(one(message.getFinalizationXidList(), "ACK.finalizationXid")), + positiveLongDecimal( + one(message.getCommittedBeforeMsList(), "ACK.committedBeforeMs"), + "ACK.committedBeforeMs"), + xid(one(message.getReceiptXidList(), "ACK.receiptXid"))); + } + + private static void validateReceiptShape(OriginalAckReceiptEvidence receipt) { + if (receipt.schemaVersion != 1 + || receipt.requestId.version() != 4 + || receipt.requestId.variant() != 2 + || NIL_UUID.equals(receipt.accountId) + || receipt.leaseId.version() != 4 + || receipt.leaseId.variant() != 2 + || receipt.leaseFence <= 0L + || !receipt.evidenceSha256.matches("[0-9a-f]{64}") + || receipt.bindingDecisionId.version() != 4 + || receipt.bindingDecisionId.variant() != 2 + || receipt.expiresAtMs <= 0L + || receipt.committedBeforeMs <= 0L + || receipt.committedBeforeMs >= receipt.expiresAtMs) { + throw invalid("ACK receipt fields are outside their existing supported form"); + } + requireCanonicalXid(receipt.finalizationXid); + requireCanonicalXid(receipt.receiptXid); + if (receipt.finalizationXid.equals(receipt.receiptXid)) { + throw invalid("ACK receipt XIDs must identify distinct transactions"); + } + } + + private static byte[] canonicalLeaseBytes(AccountGameplayAdmissionLeaseEvidence evidence) { + Objects.requireNonNull(evidence, "originalLeaseEvidence"); + requireFreshNewLease(evidence); + return evidence.canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + private static byte[] requireOriginalLeaseEvidenceBytes(byte[] bytes) { + AccountGameplayAdmissionLeaseEvidence evidence = parseFreshNewLease(bytes); + if (!Arrays.equals(bytes, canonicalLeaseBytes(evidence))) { + throw invalid("Original lease bytes are not the exact canonical UTF-8"); + } + return bytes.clone(); + } + + private static AccountGameplayAdmissionLeaseEvidence parseFreshNewLease(byte[] bytes) { + Objects.requireNonNull(bytes, "originalLeaseEvidenceUtf8"); + if (bytes.length > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES) { + throw invalid("Original lease evidence exceeds its existing byte bound"); + } + String json; + try { + json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Original lease evidence is not strict UTF-8"); + } + AccountGameplayAdmissionLeaseEvidence evidence; + try { + evidence = AccountGameplayAdmissionLeaseEvidence.parseCanonical(json); + } catch (RuntimeException malformed) { + throw invalid("Original lease evidence is malformed"); + } + if (!Arrays.equals(bytes, canonicalLeaseBytesWithoutRecursion(evidence))) { + throw invalid("Original lease bytes are not the exact canonical UTF-8"); + } + requireFreshNewLease(evidence); + return evidence; + } + + private static byte[] canonicalLeaseBytesWithoutRecursion( + AccountGameplayAdmissionLeaseEvidence evidence) { + return evidence.canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + private static void requireFreshNewLease(AccountGameplayAdmissionLeaseEvidence evidence) { + if (evidence.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING + || evidence.carrier().containsKey("resumeEpisodeId") + || evidence.carrier().containsKey("expectedOldBindingGeneration")) { + throw invalid("Only the exact fresh NEW-binding lease form is supported"); + } + } + + private static String compactJwt(String value) { + byte[] utf8 = compactJwtUtf8(value); + Arrays.fill(utf8, (byte) 0); + return value; + } + + private static String compactJwtSha256(String value) { + byte[] utf8 = compactJwtUtf8(value); + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(utf8)); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } finally { + Arrays.fill(utf8, (byte) 0); + } + } + + private static byte[] compactJwtUtf8(String value) { + Objects.requireNonNull(value, "presentedInitialGsACompactJwt"); + if (value.isBlank() || !value.equals(value.trim())) { + throw invalid("Presented initial GSA compact JWT is malformed"); + } + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + if (encoded.remaining() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES) { + throw invalid("Presented initial GSA compact JWT exceeds its existing byte bound"); + } + byte[] utf8 = new byte[encoded.remaining()]; + encoded.get(utf8); + return utf8; + } catch (CharacterCodingException malformed) { + throw invalid("Presented initial GSA compact JWT has invalid text encoding"); + } + } + + private static UUID highEntropyUuid(String value) { + UUID parsed = canonicalNonNilUuid(value); + if (parsed.version() != 4 || parsed.variant() != 2) { + throw invalid("UUID must be a canonical high-entropy UUIDv4"); + } + return parsed; + } + + private static UUID highEntropyUuid(UUID value) { + Objects.requireNonNull(value, "UUID"); + if (NIL_UUID.equals(value) || value.version() != 4 || value.variant() != 2) { + throw invalid("UUID must be a canonical high-entropy UUIDv4"); + } + return value; + } + + private static UUID canonicalNonNilUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || NIL_UUID.equals(parsed)) { + throw invalid("UUID must be canonical and non-nil"); + } + return parsed; + } catch (RuntimeException malformed) { + throw invalid("UUID must be canonical and non-nil"); + } + } + + private static String digest(String value) { + if (value == null || !value.matches("[0-9a-f]{64}")) { + throw invalid("Evidence digest must be lowercase SHA-256 hex"); + } + return value; + } + + private static String xid(String value) { + requireCanonicalXid(value); + return value; + } + + private static void requireCanonicalXid(String value) { + if (value == null || !value.matches("[1-9][0-9]*")) { + throw invalid("Transaction ID must be canonical positive unsigned-64 decimal"); + } + try { + BigInteger xid = new BigInteger(value); + if (xid.signum() <= 0 || xid.compareTo(UINT64_MAX) > 0) { + throw invalid("Transaction ID exceeds its supported unsigned-64 range"); + } + } catch (NumberFormatException malformed) { + throw invalid("Transaction ID must be canonical positive unsigned-64 decimal"); + } + } + + private static long positiveLongDecimal(String value, String field) { + try { + return AccountJwtExactValues.positiveDecimalCounter(value).longValueExact(); + } catch (RuntimeException malformed) { + throw invalid(field + " is outside its canonical positive signed-long range"); + } + } + + private static long positiveLong(BigInteger value) { + try { + long parsed = value.longValueExact(); + if (parsed <= 0L) throw invalid("Lease counter is not a positive signed-long value"); + return parsed; + } catch (ArithmeticException outsideRange) { + throw invalid("Lease counter exceeds its supported signed-long range"); + } + } + + private static BigInteger positiveCounter(String value) { + return AccountJwtExactValues.positiveDecimalCounter(value); + } + + private static String positiveDecimal(BigInteger value) { + if (value.signum() <= 0) throw invalid("Binding generation must be positive"); + return value.toString(); + } + + private static AccountGameplayAdmissionLeaseState toWireState(State state) { + return switch (state) { + case PENDING -> + AccountGameplayAdmissionLeaseState.ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_PENDING; + case COMMITTED -> + AccountGameplayAdmissionLeaseState.ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED; + case ABORTED -> + AccountGameplayAdmissionLeaseState.ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_ABORTED; + }; + } + + private static State fromWireState(int value) { + return switch (value) { + case 1 -> State.PENDING; + case 2 -> State.COMMITTED; + case 3 -> State.ABORTED; + default -> throw invalid("Unsupported original lease operation state"); + }; + } + + private static void requirePurpose(OriginalLeaseRequest request, OriginalLeasePurpose purpose) { + Objects.requireNonNull(request, "request"); + if (request.purpose != purpose) throw invalid("Original lease request has the wrong purpose"); + } + + private static void requireSchema(int schema) { + if (schema != SCHEMA_VERSION) throw invalid("Unsupported Account admission lease schema"); + } + + private static void requireNoUnknownFields(boolean noUnknownFields, String field) { + if (!noUnknownFields) throw invalid("Unknown " + field + " field"); + } + + private static void requireWireSize(int actual, int maximum, String field) { + if (actual > maximum) throw invalid(field + " exceeds its finite wire bound"); + } + + private static Map object(Object value, String field) { + if (!(value instanceof Map map)) throw invalid(field + " must be an object"); + return map; + } + + private static String string(Map object, String field) { + Object value = object.get(field); + if (!(value instanceof String text)) throw invalid(field + " must be canonical text"); + return text; + } + + private static T one(List values, String field) { + if (values.size() != 1 || values.get(0) == null) { + throw invalid(field + " must occur exactly once"); + } + return values.get(0); + } + + private static T optional(List values, String field) { + if (values.size() > 1) throw invalid(field + " must be absent or occur once"); + return values.isEmpty() ? null : Objects.requireNonNull(values.get(0), field); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private enum OriginalLeasePurpose { + FINALIZE, + READ, + ABORT + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java new file mode 100644 index 0000000000..944fd27754 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java @@ -0,0 +1,1011 @@ +package net.firedevops.firemud.common.gamesession; + +import com.google.protobuf.ByteString; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.security.AccountJwtExactValues; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionDecisionStatus; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionOriginKind; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionOwnerProofOutcome; +import net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPublishedRealmAdmissionOwnerReadResponse; + +/** + * Closed, purpose-specific wire mapping for Account-only Game Session owner reads. + * + *

The returned values are structurally verified read evidence. They do not prove current Account + * authority, any external acknowledgement, finalization, or gameplay admission. + */ +public final class CanonicalGameplayAdmissionDecisionReadGrpcCodec { + public static final int MAX_REQUEST_WIRE_BYTES = + AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1024; + public static final int MAX_RESPONSE_WIRE_BYTES = 256 * 1024; + public static final int MAX_PUBLISHED_REALM_REQUEST_WIRE_BYTES = + CanonicalGameplayRosterOwnerReadGrpcCodec.MAX_REQUEST_BYTES + 256; + public static final int MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES = + CanonicalGameplayRosterOwnerReadGrpcCodec.MAX_RESPONSE_BYTES + 1024 * 1024; + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private CanonicalGameplayAdmissionDecisionReadGrpcCodec() {} + + /** Locally retained request identity; construction is restricted to this codec. */ + public static final class RequestEvidence { + private final UUID bindingDecisionId; + private final AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence; + private final byte[] expectedLeaseEvidenceUtf8; + + private RequestEvidence( + UUID bindingDecisionId, + AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence, + byte[] expectedLeaseEvidenceUtf8) { + this.bindingDecisionId = bindingDecisionId; + this.expectedLeaseEvidence = expectedLeaseEvidence; + this.expectedLeaseEvidenceUtf8 = expectedLeaseEvidenceUtf8.clone(); + } + + public UUID bindingDecisionId() { + return bindingDecisionId; + } + + public AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence() { + return expectedLeaseEvidence; + } + + public byte[] expectedLeaseEvidenceUtf8() { + return expectedLeaseEvidenceUtf8.clone(); + } + } + + /** Only codec-created complete readbacks are returned to the Account caller. */ + public static final class Evidence { + private final UUID bindingDecisionId; + private final AccountGameplayAdmissionLeaseEvidence leaseEvidence; + private final BigInteger bindingGeneration; + private final BigInteger expectedOldBindingGeneration; + private final UUID resumeEpisodeId; + private final Candidate candidate; + private final Target targetEvidence; + + private Evidence( + UUID bindingDecisionId, + AccountGameplayAdmissionLeaseEvidence leaseEvidence, + BigInteger bindingGeneration, + BigInteger expectedOldBindingGeneration, + UUID resumeEpisodeId, + Candidate candidate, + Target targetEvidence) { + this.bindingDecisionId = bindingDecisionId; + this.leaseEvidence = leaseEvidence; + this.bindingGeneration = bindingGeneration; + this.expectedOldBindingGeneration = expectedOldBindingGeneration; + this.resumeEpisodeId = resumeEpisodeId; + this.candidate = candidate; + this.targetEvidence = targetEvidence; + } + + public UUID bindingDecisionId() { + return bindingDecisionId; + } + + public AccountGameplayAdmissionLeaseEvidence leaseEvidence() { + return leaseEvidence; + } + + public String originalLeaseEvidenceJson() { + return leaseEvidence.canonicalJson(); + } + + public Status status() { + return Status.PROVISIONAL; + } + + public BigInteger bindingGeneration() { + return bindingGeneration; + } + + public BigInteger expectedOldBindingGeneration() { + return expectedOldBindingGeneration; + } + + public UUID resumeEpisodeId() { + return resumeEpisodeId; + } + + public Candidate candidate() { + return candidate; + } + + public Target targetEvidence() { + return targetEvidence; + } + } + + /** Parsed pre-lease selector; its account identity and counters remain correlation only. */ + public static final class PublishedRealmRequest { + private final CanonicalGameplayRosterOwnerReadEvidence.Request selector; + + private PublishedRealmRequest(CanonicalGameplayRosterOwnerReadEvidence.Request selector) { + this.selector = selector; + } + + public CanonicalGameplayRosterOwnerReadEvidence.Request selector() { + return selector; + } + } + + /** Complete current target tied to the existing validated route proof and policy-set evidence. */ + public static final class PublishedRealmEvidence { + private final CanonicalGameplayRosterOwnerReadEvidence.Request selector; + private final CanonicalGameplayRosterOwnerReadEvidence sourceEvidence; + private final Target currentTarget; + + private PublishedRealmEvidence( + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + CanonicalGameplayRosterOwnerReadEvidence sourceEvidence, + Target currentTarget) { + this.selector = selector; + this.sourceEvidence = sourceEvidence; + this.currentTarget = currentTarget; + } + + public CanonicalGameplayRosterOwnerReadEvidence.Request selector() { + return selector; + } + + public CanonicalGameplayRosterOwnerReadEvidence sourceEvidence() { + return sourceEvidence; + } + + public Target currentTarget() { + return currentTarget; + } + } + + /** Complete CanonicalGameplayBindingIdentity in Account-independent common types. */ + public record Candidate( + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + UUID characterId, + String playableStateScope, + UUID gameInstanceId, + long runtimeGameInstanceId, + UUID sessionId, + UUID regionId, + BigInteger regionEpoch, + String issuerId, + BigInteger issuerAuthGeneration, + BigInteger issuerIndexLayoutVersion, + BigInteger issuerIndexPartitionCount, + BigInteger issuerIndexPartitionCapacity) {} + + /** Complete CanonicalPlayableTarget in Account-independent common types. */ + public record Target( + 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, + OwnerProofOutcome ownerProofOutcome, + boolean positiveDurableAbort, + Instant ownerProofTerminalAt, + String characterCreationPolicy) {} + + public enum OriginKind { + NO_PRIOR_POINTER, + EXPECT_CLOSED + } + + public enum Status { + PROVISIONAL + } + + public enum OwnerProofOutcome { + PENDING, + COMMITTED, + ABORTED + } + + public static GetCanonicalGameplayAdmissionDecisionRequest toRequest( + UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence) { + requireNonNil(bindingDecisionId, "bindingDecisionId"); + Objects.requireNonNull(expectedLeaseEvidence, "expectedLeaseEvidence"); + byte[] leaseBytes = canonicalLeaseBytes(expectedLeaseEvidence); + GetCanonicalGameplayAdmissionDecisionRequest request = + GetCanonicalGameplayAdmissionDecisionRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addBindingDecisionUuid(bindingDecisionId.toString()) + .addExpectedLeaseEvidenceUtf8(ByteString.copyFrom(leaseBytes)) + .build(); + requireWireSize(request.getSerializedSize(), MAX_REQUEST_WIRE_BYTES, "read request"); + return request; + } + + /** Parses the untrusted request only after the GS workload guard has authenticated its peer. */ + public static RequestEvidence parseRequest(GetCanonicalGameplayAdmissionDecisionRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize(request.getSerializedSize(), MAX_REQUEST_WIRE_BYTES, "read request"); + if (!request.getUnknownFields().asMap().isEmpty()) throw invalid("Unknown request field"); + if (one(request.getSchemaVersionList(), "schemaVersion") != SCHEMA_VERSION) { + throw invalid("Unsupported request schema"); + } + UUID bindingDecisionId = uuid(one(request.getBindingDecisionUuidList(), "bindingDecisionId")); + byte[] leaseBytes = + one(request.getExpectedLeaseEvidenceUtf8List(), "expectedLeaseEvidence").toByteArray(); + AccountGameplayAdmissionLeaseEvidence lease = parseLease(leaseBytes); + return new RequestEvidence(bindingDecisionId, lease, leaseBytes); + } + + /** Wraps the existing complete route selector without granting it Account authority. */ + public static GetPublishedRealmAdmissionOwnerReadRequest toPublishedRealmRequest( + CanonicalGameplayRosterOwnerReadEvidence.Request selector) { + Objects.requireNonNull(selector, "selector"); + var request = + GetPublishedRealmAdmissionOwnerReadRequest.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addSelector(CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(selector)) + .build(); + requireWireSize( + request.getSerializedSize(), + MAX_PUBLISHED_REALM_REQUEST_WIRE_BYTES, + "published realm read request"); + return request; + } + + /** Parses one existing selector only after the Account-purpose caller guard has passed. */ + public static PublishedRealmRequest parsePublishedRealmRequest( + GetPublishedRealmAdmissionOwnerReadRequest request) { + Objects.requireNonNull(request, "request"); + requireWireSize( + request.getSerializedSize(), + MAX_PUBLISHED_REALM_REQUEST_WIRE_BYTES, + "published realm read request"); + if (!request.getUnknownFields().asMap().isEmpty() + || one(request.getSchemaVersionList(), "published schemaVersion") != SCHEMA_VERSION) { + throw invalid("Closed schema-1 published realm request required"); + } + GetCanonicalGameplayRosterOwnerReadRequest selectorMessage = + one(request.getSelectorList(), "published selector"); + CanonicalGameplayRosterOwnerReadEvidence.Request selector = + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(selectorMessage); + if (!CanonicalGameplayRosterOwnerReadGrpcCodec.toRequest(selector).equals(selectorMessage)) { + throw invalid("Published realm selector is not its exact existing closed encoding"); + } + return new PublishedRealmRequest(selector); + } + + /** Produces the complete existing source carrier plus the same read's exact current route. */ + public static GetPublishedRealmAdmissionOwnerReadResponse toPublishedRealmResponse( + PublishedRealmRequest request, + CanonicalGameplayRosterOwnerReadEvidence sourceEvidence, + Target currentTarget) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + Objects.requireNonNull(currentTarget, "currentTarget"); + requirePublishedTargetMatchesSource(currentTarget, request.selector(), sourceEvidence); + GetCanonicalGameplayRosterOwnerReadResponse sourceResponse = + CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(request.selector(), sourceEvidence); + GetPublishedRealmAdmissionOwnerReadResponse response = + GetPublishedRealmAdmissionOwnerReadResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addPublishedSource(sourceResponse) + .addCurrentTarget(toTargetEvidence(currentTarget)) + .build(); + requireWireSize( + response.getSerializedSize(), + MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES, + "published realm read response"); + fromPublishedRealmResponse(request, response); + return response; + } + + /** Reuses the existing full source validator and validates the complete route-to-source tuple. */ + public static PublishedRealmEvidence fromPublishedRealmResponse( + PublishedRealmRequest request, GetPublishedRealmAdmissionOwnerReadResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireWireSize( + response.getSerializedSize(), + MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES, + "published realm read response"); + if (!response.getUnknownFields().asMap().isEmpty() + || one(response.getSchemaVersionList(), "published schemaVersion") != SCHEMA_VERSION) { + throw invalid("Closed schema-1 published realm response required"); + } + CanonicalGameplayRosterOwnerReadEvidence sourceEvidence = + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request.selector(), one(response.getPublishedSourceList(), "published source")); + Target currentTarget = + parseTargetEvidence(one(response.getCurrentTargetList(), "current target")); + requirePublishedTargetMatchesSource(currentTarget, request.selector(), sourceEvidence); + return new PublishedRealmEvidence(request.selector(), sourceEvidence, currentTarget); + } + + /** + * Serializes the actual repository readback and binds it to the exact unchanged request bytes. + */ + public static GetCanonicalGameplayAdmissionDecisionResponse toResponse( + RequestEvidence request, + UUID bindingDecisionId, + AccountGameplayAdmissionLeaseEvidence leaseEvidence, + BigInteger bindingGeneration, + BigInteger expectedOldBindingGeneration, + UUID resumeEpisodeId, + Candidate candidate, + Target targetEvidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); + Objects.requireNonNull(leaseEvidence, "leaseEvidence"); + Objects.requireNonNull(bindingGeneration, "bindingGeneration"); + Objects.requireNonNull(candidate, "candidate"); + Objects.requireNonNull(targetEvidence, "targetEvidence"); + if (!request.bindingDecisionId().equals(bindingDecisionId) + || !request.expectedLeaseEvidence().hasSameIdentity(leaseEvidence) + || !Arrays.equals( + request.expectedLeaseEvidenceUtf8(), canonicalLeaseBytes(leaseEvidence))) { + throw invalid("Stored decision differs from the original request"); + } + + GetCanonicalGameplayAdmissionDecisionResponse response = + GetCanonicalGameplayAdmissionDecisionResponse.newBuilder() + .addSchemaVersion(SCHEMA_VERSION) + .addBindingDecisionUuid(bindingDecisionId.toString()) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFrom(request.expectedLeaseEvidenceUtf8())) + .addStatus( + CanonicalGameplayAdmissionDecisionStatus + .CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_PROVISIONAL) + .addBindingGeneration(bindingGeneration.toString()) + .addCandidate(toCandidate(candidate)) + .addTargetEvidence(toTargetEvidence(targetEvidence)) + .build(); + var builder = response.toBuilder(); + if (expectedOldBindingGeneration != null) { + builder.addExpectedOldBindingGeneration(expectedOldBindingGeneration.toString()); + } + if (resumeEpisodeId != null) { + builder.addResumeEpisodeUuid(resumeEpisodeId.toString()); + } + response = builder.build(); + requireWireSize(response.getSerializedSize(), MAX_RESPONSE_WIRE_BYTES, "read response"); + // Apply the same closed validation to producer output, including owner-proof tuple checks. + fromResponse(request, response); + return response; + } + + /** Validates every wire field and returns a complete typed readback, never a caller echo. */ + public static Evidence fromResponse( + RequestEvidence request, GetCanonicalGameplayAdmissionDecisionResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireWireSize(response.getSerializedSize(), MAX_RESPONSE_WIRE_BYTES, "read response"); + if (!response.getUnknownFields().asMap().isEmpty()) throw invalid("Unknown response field"); + if (one(response.getSchemaVersionList(), "schemaVersion") != SCHEMA_VERSION) { + throw invalid("Unsupported response schema"); + } + UUID decisionId = uuid(one(response.getBindingDecisionUuidList(), "bindingDecisionId")); + byte[] leaseBytes = + one(response.getOriginalLeaseEvidenceUtf8List(), "leaseEvidence").toByteArray(); + if (!request.bindingDecisionId().equals(decisionId) + || !Arrays.equals(request.expectedLeaseEvidenceUtf8(), leaseBytes)) { + throw invalid("Response does not contain the exact original decision and lease"); + } + AccountGameplayAdmissionLeaseEvidence lease = parseLease(leaseBytes); + if (!request.expectedLeaseEvidence().hasSameIdentity(lease)) { + throw invalid("Response lease differs from the original request"); + } + if (one(response.getStatusValueList(), "status") + != CanonicalGameplayAdmissionDecisionStatus + .CANONICAL_GAMEPLAY_ADMISSION_DECISION_STATUS_PROVISIONAL_VALUE) { + throw invalid("Only a durable PROVISIONAL decision can be read"); + } + + BigInteger bindingGeneration = + positiveDecimal( + one(response.getBindingGenerationList(), "bindingGeneration"), "bindingGeneration"); + BigInteger expectedOldBindingGeneration = + optional(response.getExpectedOldBindingGenerationList(), "expectedOldBindingGeneration") + == null + ? null + : positiveDecimal( + response.getExpectedOldBindingGeneration(0), "expectedOldBindingGeneration"); + String resumeEpisodeText = optional(response.getResumeEpisodeUuidList(), "resumeEpisodeId"); + UUID resumeEpisodeId = resumeEpisodeText == null ? null : uuid(resumeEpisodeText); + Candidate candidate = parseCandidate(one(response.getCandidateList(), "candidate")); + Target target = parseTargetEvidence(one(response.getTargetEvidenceList(), "targetEvidence")); + + Map carrier = lease.carrier(); + Map scope = map(carrier.get("bindingScope"), "bindingScope"); + Object expectedOldLeaseValue = carrier.get("expectedOldBindingGeneration"); + BigInteger leaseExpectedOld = + expectedOldLeaseValue == null + ? null + : positiveDecimal( + text(expectedOldLeaseValue, "expectedOldBindingGeneration"), + "expectedOldBindingGeneration"); + Object resumeLeaseValue = carrier.get("resumeEpisodeId"); + UUID leaseResume = + resumeLeaseValue == null ? null : uuid(text(resumeLeaseValue, "resumeEpisodeId")); + if (!bindingGeneration.equals( + positiveDecimal( + text(scope.get("bindingGeneration"), "bindingGeneration"), + "lease bindingGeneration")) + || !Objects.equals(expectedOldBindingGeneration, leaseExpectedOld) + || !Objects.equals(resumeEpisodeId, leaseResume) + || (lease.leaseKind() == AccountGameplayAdmissionLeaseEvidence.LeaseKind.RESUME + && (expectedOldBindingGeneration == null || resumeEpisodeId == null)) + || (lease.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.RESUME + && resumeEpisodeId != null)) { + throw invalid("Response generation or resume identity differs from the lease"); + } + validateCandidateAndTargetAgainstLease(candidate, target, lease, scope); + return new Evidence( + decisionId, + lease, + bindingGeneration, + expectedOldBindingGeneration, + resumeEpisodeId, + candidate, + target); + } + + public static Candidate parseCandidate(CanonicalGameplayAdmissionCandidate message) { + if (!message.getUnknownFields().asMap().isEmpty()) throw invalid("Unknown candidate field"); + return new Candidate( + uuid(one(message.getAccountUuidList(), "candidate.accountId")), + uuid(one(message.getTenantUuidList(), "candidate.tenantId")), + uuid( + one(message.getPlayableStateNamespaceUuidList(), "candidate.playableStateNamespaceId")), + uuid(one(message.getCharacterUuidList(), "candidate.characterId")), + text( + one(message.getPlayableStateScopeList(), "candidate.playableStateScope"), + "candidate.playableStateScope"), + uuid(one(message.getGameInstanceUuidList(), "candidate.gameInstanceId")), + positiveLong( + one(message.getRuntimeGameInstanceIdList(), "candidate.runtimeGameInstanceId"), + "candidate.runtimeGameInstanceId"), + uuid(one(message.getSessionUuidList(), "candidate.sessionId")), + uuid(one(message.getRegionUuidList(), "candidate.regionId")), + positiveDecimal( + one(message.getRegionEpochList(), "candidate.regionEpoch"), "candidate.regionEpoch"), + requireAccountIssuer(one(message.getIssuerIdList(), "candidate.issuerId")), + positiveDecimal( + one(message.getIssuerAuthGenerationList(), "candidate.issuerAuthGeneration"), + "candidate.issuerAuthGeneration"), + positiveDecimal( + one(message.getIssuerIndexLayoutVersionList(), "candidate.issuerIndexLayoutVersion"), + "candidate.issuerIndexLayoutVersion"), + positiveDecimal( + one(message.getIssuerIndexPartitionCountList(), "candidate.issuerIndexPartitionCount"), + "candidate.issuerIndexPartitionCount"), + positiveDecimal( + one( + message.getIssuerIndexPartitionCapacityList(), + "candidate.issuerIndexPartitionCapacity"), + "candidate.issuerIndexPartitionCapacity")); + } + + private static Target parseTarget(CanonicalPlayableTargetEvidence message) { + if (!message.getUnknownFields().asMap().isEmpty()) throw invalid("Unknown target field"); + String priorPointer = + optional( + message.getExpectedPriorPointerVersionList(), "target.expectedPriorPointerVersion"); + int originValue = + one(message.getInitialAdmissionOriginKindValueList(), "target.initialAdmissionOriginKind"); + OriginKind origin = + switch (originValue) { + case 1 -> OriginKind.NO_PRIOR_POINTER; + case 2 -> OriginKind.EXPECT_CLOSED; + default -> throw invalid("Unsupported initial-admission origin"); + }; + int outcomeValue = one(message.getOwnerProofOutcomeValueList(), "target.ownerProofOutcome"); + OwnerProofOutcome outcome = + switch (outcomeValue) { + case 1 -> OwnerProofOutcome.PENDING; + case 2 -> OwnerProofOutcome.COMMITTED; + case 3 -> OwnerProofOutcome.ABORTED; + default -> throw invalid("Unsupported initial-admission owner-proof outcome"); + }; + return new Target( + text( + one(message.getTargetNamespaceList(), "target.targetNamespace"), + "target.targetNamespace"), + text(one(message.getTenantSlugList(), "target.tenantSlug"), "target.tenantSlug"), + uuid(one(message.getCanonicalTenantUuidList(), "target.canonicalTenantId")), + text(one(message.getWorldSlugList(), "target.worldSlug"), "target.worldSlug"), + text( + one(message.getWorldDisplayNameList(), "target.worldDisplayName"), + "target.worldDisplayName"), + uuid(one(message.getRealmUuidList(), "target.realmId")), + text(one(message.getRealmSlugList(), "target.realmSlug"), "target.realmSlug"), + text( + one(message.getRealmDisplayNameList(), "target.realmDisplayName"), + "target.realmDisplayName"), + positiveLong( + one(message.getGameSessionTenantIdList(), "target.gameSessionTenantId"), + "target.gameSessionTenantId"), + positiveLong( + one(message.getGameInstanceIdList(), "target.gameInstanceId"), "target.gameInstanceId"), + uuid(one(message.getPlayableStateNamespaceUuidList(), "target.playableStateNamespaceId")), + text( + one(message.getPlayableStateScopeList(), "target.playableStateScope"), + "target.playableStateScope"), + uuid(one(message.getCanonicalGameInstanceUuidList(), "target.canonicalGameInstanceId")), + uuid(one(message.getCanonicalVersionUuidList(), "target.canonicalVersionId")), + positiveLong( + one(message.getRuntimeVersionIdList(), "target.runtimeVersionId"), + "target.runtimeVersionId"), + positiveLongDecimal( + one(message.getCatalogRevisionList(), "target.catalogRevision"), + "target.catalogRevision"), + positiveLongDecimal( + one(message.getPointerVersionList(), "target.pointerVersion"), "target.pointerVersion"), + text( + one( + message.getAdmissionPointerSnapshotDigestList(), + "target.admissionPointerSnapshotDigest"), + "target.admissionPointerSnapshotDigest"), + positiveLongDecimal( + one(message.getActiveWorldEpochList(), "target.activeWorldEpoch"), + "target.activeWorldEpoch"), + text( + one(message.getInitialAdmissionRequestIdList(), "target.initialAdmissionRequestId"), + "target.initialAdmissionRequestId"), + text( + one( + message.getInitialAdmissionRequestDigestList(), + "target.initialAdmissionRequestDigest"), + "target.initialAdmissionRequestDigest"), + origin, + priorPointer == null + ? null + : positiveLongDecimal(priorPointer, "target.expectedPriorPointerVersion"), + uuid(one(message.getHoldUuidList(), "target.holdId")), + uuid(one(message.getHoldFenceUuidList(), "target.holdFence")), + text( + one(message.getHoldBindingDigestList(), "target.holdBindingDigest"), + "target.holdBindingDigest"), + positiveLong( + one(message.getAuditEventIdList(), "target.auditEventId"), "target.auditEventId"), + text( + one(message.getOwnerProofDigestList(), "target.ownerProofDigest"), + "target.ownerProofDigest"), + outcome, + one(message.getPositiveDurableAbortList(), "target.positiveDurableAbort"), + instant(one(message.getOwnerProofTerminalAtList(), "target.ownerProofTerminalAt")), + text( + one(message.getCharacterCreationPolicyList(), "target.characterCreationPolicy"), + "target.characterCreationPolicy")); + } + + public static Target parseTargetEvidence(CanonicalPlayableTargetEvidence message) { + Target target = parseTarget(Objects.requireNonNull(message, "message")); + validateOwnerProofTuple(target); + return target; + } + + public static CanonicalPlayableTargetEvidence toTargetEvidence(Target target) { + return toTarget(Objects.requireNonNull(target, "target")); + } + + private static void validateCandidateAndTargetAgainstLease( + Candidate candidate, + Target target, + AccountGameplayAdmissionLeaseEvidence lease, + Map scope) { + Map carrier = lease.carrier(); + Map authorityTuple = map(carrier.get("authorityTuple"), "authorityTuple"); + requireEqual( + text(carrier.get("targetNamespace"), "targetNamespace"), + target.targetNamespace(), + "targetNamespace"); + requireEqual( + text(scope.get("accountId"), "bindingScope.accountId"), + candidate.accountId().toString(), + "accountId"); + requireEqual( + text(scope.get("tenantId"), "bindingScope.tenantId"), + candidate.tenantId().toString(), + "tenantId"); + requireEqual(candidate.tenantId(), target.canonicalTenantId(), "canonicalTenantId"); + requireEqual( + text(scope.get("realmId"), "bindingScope.realmId"), target.realmId().toString(), "realmId"); + requireEqual( + text(scope.get("worldSlug"), "bindingScope.worldSlug"), target.worldSlug(), "worldSlug"); + requireEqual( + text(scope.get("realmSlug"), "bindingScope.realmSlug"), target.realmSlug(), "realmSlug"); + requireEqual( + text(scope.get("playableStateNamespaceId"), "bindingScope.playableStateNamespaceId"), + candidate.playableStateNamespaceId().toString(), + "playableStateNamespaceId"); + requireEqual( + candidate.playableStateNamespaceId(), + target.playableStateNamespaceId(), + "target playableStateNamespaceId"); + requireEqual( + text(scope.get("playableStateScope"), "bindingScope.playableStateScope"), + candidate.playableStateScope(), + "playableStateScope"); + requireEqual( + candidate.playableStateScope(), target.playableStateScope(), "target playableStateScope"); + requireEqual( + text(scope.get("gameInstanceId"), "bindingScope.gameInstanceId"), + candidate.gameInstanceId().toString(), + "gameInstanceId"); + requireEqual( + candidate.gameInstanceId(), target.canonicalGameInstanceId(), "canonicalGameInstanceId"); + requireEqual( + text(scope.get("characterId"), "bindingScope.characterId"), + candidate.characterId().toString(), + "characterId"); + requireEqual( + text(scope.get("sessionId"), "bindingScope.sessionId"), + candidate.sessionId().toString(), + "sessionId"); + requireEqual( + text(scope.get("regionId"), "bindingScope.regionId"), + candidate.regionId().toString(), + "regionId"); + requireEqual( + positiveDecimal(text(scope.get("regionEpoch"), "bindingScope.regionEpoch"), "regionEpoch"), + candidate.regionEpoch(), + "regionEpoch"); + requireEqual( + positiveLong(target.gameInstanceId(), "target.gameInstanceId"), + candidate.runtimeGameInstanceId(), + "runtimeGameInstanceId"); + requireEqual( + positiveDecimal( + text(authorityTuple.get("issuerAuthGeneration"), "authorityTuple.issuerAuthGeneration"), + "issuerAuthGeneration"), + candidate.issuerAuthGeneration(), + "issuerAuthGeneration"); + requireEqual( + positiveDecimal( + text(scope.get("catalogRevision"), "bindingScope.catalogRevision"), "catalogRevision"), + BigInteger.valueOf(target.catalogRevision()), + "catalogRevision"); + requireEqual( + positiveDecimal( + text(scope.get("pointerVersion"), "bindingScope.pointerVersion"), "pointerVersion"), + BigInteger.valueOf(target.pointerVersion()), + "pointerVersion"); + } + + private static void validateOwnerProofTuple(Target target) { + ownerProofFromTarget(target); + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof ownerProofFromTarget( + Target target) { + if (!target.admissionPointerSnapshotDigest().matches("[0-9a-f]{64}") + || target.ownerProofOutcome() != OwnerProofOutcome.COMMITTED + || target.positiveDurableAbort()) { + throw invalid("Stored playable target is not an exact committed pointer target"); + } + WorldCanonicalInitialAdmissionHold.Request request = + new WorldCanonicalInitialAdmissionHold.Request( + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.activeWorldEpoch(), + target.initialAdmissionRequestId(), + target.initialAdmissionRequestDigest(), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.valueOf( + target.initialAdmissionOriginKind().name()), + target.catalogRevision(), + target.expectedPriorPointerVersion()); + WorldCanonicalInitialAdmissionHold.HoldIdentity hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, target.holdId(), target.holdFence()); + requireEqual(hold.holdBindingDigest(), target.holdBindingDigest(), "holdBindingDigest"); + GameSessionCanonicalInitialAdmissionOwnerProof proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.valueOf( + target.ownerProofOutcome().name()), + target.ownerProofOutcome() == OwnerProofOutcome.COMMITTED + ? target.pointerVersion() + : null, + target.ownerProofOutcome() == OwnerProofOutcome.COMMITTED + ? target.auditEventId() + : null, + target.ownerProofDigest(), + target.positiveDurableAbort(), + target.ownerProofTerminalAt()); + return GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof)); + } + + private static void requirePublishedTargetMatchesSource( + Target target, + CanonicalGameplayRosterOwnerReadEvidence.Request selector, + CanonicalGameplayRosterOwnerReadEvidence sourceEvidence) { + if (!target.targetNamespace().equals(selector.targetNamespace()) + || !target.canonicalTenantId().equals(selector.canonicalTenantUuid()) + || !target.worldSlug().equals(selector.worldSlug()) + || !target.realmId().equals(selector.realmUuid()) + || !target.realmSlug().equals(selector.realmSlug()) + || !target.playableStateNamespaceId().equals(selector.playableStateNamespaceUuid()) + || !target.playableStateScope().equals(selector.playableStateScope()) + || !target.canonicalGameInstanceId().equals(selector.canonicalGameInstanceUuid()) + || !target.canonicalVersionId().equals(selector.canonicalVersionUuid()) + || target.catalogRevision() != selector.expectedCatalogRevision() + || target.pointerVersion() != selector.expectedPointerVersion() + || target.activeWorldEpoch() != selector.expectedActiveWorldEpoch() + || !target + .admissionPointerSnapshotDigest() + .equals(sourceEvidence.admissionPointerSnapshotDigest())) { + throw invalid("Published realm target differs from its exact source selector or pointer"); + } + byte[] targetProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + ownerProofFromTarget(target)); + byte[] sourceProof = + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes( + sourceEvidence.gameSessionOwnerProof()); + if (!Arrays.equals(targetProof, sourceProof)) { + throw invalid("Published realm target changed the exact Game Session owner proof"); + } + var selectedPolicy = sourceEvidence.selectedPolicyEvidence().policy(); + if (!target.characterCreationPolicy().equals(selectedPolicy.entryPolicy().name()) + || !target.worldSlug().equals(selectedPolicy.worldSlug()) + || !target.realmSlug().equals(selectedPolicy.realmSlug())) { + throw invalid("Published realm target differs from the exact sealed policy selector"); + } + } + + public static CanonicalGameplayAdmissionCandidate toCandidate(Candidate identity) { + return CanonicalGameplayAdmissionCandidate.newBuilder() + .addAccountUuid(identity.accountId().toString()) + .addTenantUuid(identity.tenantId().toString()) + .addPlayableStateNamespaceUuid(identity.playableStateNamespaceId().toString()) + .addCharacterUuid(identity.characterId().toString()) + .addPlayableStateScope(identity.playableStateScope()) + .addGameInstanceUuid(identity.gameInstanceId().toString()) + .addRuntimeGameInstanceId(identity.runtimeGameInstanceId()) + .addSessionUuid(identity.sessionId().toString()) + .addRegionUuid(identity.regionId().toString()) + .addRegionEpoch(identity.regionEpoch().toString()) + .addIssuerId(requireAccountIssuer(identity.issuerId())) + .addIssuerAuthGeneration(identity.issuerAuthGeneration().toString()) + .addIssuerIndexLayoutVersion(identity.issuerIndexLayoutVersion().toString()) + .addIssuerIndexPartitionCount(identity.issuerIndexPartitionCount().toString()) + .addIssuerIndexPartitionCapacity(identity.issuerIndexPartitionCapacity().toString()) + .build(); + } + + private static CanonicalPlayableTargetEvidence toTarget(Target target) { + var builder = + CanonicalPlayableTargetEvidence.newBuilder() + .addTargetNamespace(target.targetNamespace()) + .addTenantSlug(target.tenantSlug()) + .addCanonicalTenantUuid(target.canonicalTenantId().toString()) + .addWorldSlug(target.worldSlug()) + .addWorldDisplayName(target.worldDisplayName()) + .addRealmUuid(target.realmId().toString()) + .addRealmSlug(target.realmSlug()) + .addRealmDisplayName(target.realmDisplayName()) + .addGameSessionTenantId(target.gameSessionTenantId()) + .addGameInstanceId(target.gameInstanceId()) + .addPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .addPlayableStateScope(target.playableStateScope()) + .addCanonicalGameInstanceUuid(target.canonicalGameInstanceId().toString()) + .addCanonicalVersionUuid(target.canonicalVersionId().toString()) + .addRuntimeVersionId(target.runtimeVersionId()) + .addCatalogRevision(Long.toString(target.catalogRevision())) + .addPointerVersion(Long.toString(target.pointerVersion())) + .addAdmissionPointerSnapshotDigest(target.admissionPointerSnapshotDigest()) + .addActiveWorldEpoch(Long.toString(target.activeWorldEpoch())) + .addInitialAdmissionRequestId(target.initialAdmissionRequestId()) + .addInitialAdmissionRequestDigest(target.initialAdmissionRequestDigest()) + .addInitialAdmissionOriginKind( + target.initialAdmissionOriginKind() == OriginKind.NO_PRIOR_POINTER + ? CanonicalGameplayAdmissionOriginKind + .CANONICAL_GAMEPLAY_ADMISSION_ORIGIN_KIND_NO_PRIOR_POINTER + : CanonicalGameplayAdmissionOriginKind + .CANONICAL_GAMEPLAY_ADMISSION_ORIGIN_KIND_EXPECT_CLOSED) + .addHoldUuid(target.holdId().toString()) + .addHoldFenceUuid(target.holdFence().toString()) + .addHoldBindingDigest(target.holdBindingDigest()) + .addAuditEventId(target.auditEventId()) + .addOwnerProofDigest(target.ownerProofDigest()) + .addOwnerProofOutcome( + switch (target.ownerProofOutcome()) { + case PENDING -> + CanonicalGameplayAdmissionOwnerProofOutcome + .CANONICAL_GAMEPLAY_ADMISSION_OWNER_PROOF_OUTCOME_PENDING; + case COMMITTED -> + CanonicalGameplayAdmissionOwnerProofOutcome + .CANONICAL_GAMEPLAY_ADMISSION_OWNER_PROOF_OUTCOME_COMMITTED; + case ABORTED -> + CanonicalGameplayAdmissionOwnerProofOutcome + .CANONICAL_GAMEPLAY_ADMISSION_OWNER_PROOF_OUTCOME_ABORTED; + }) + .addPositiveDurableAbort(target.positiveDurableAbort()) + .addOwnerProofTerminalAt(target.ownerProofTerminalAt().toString()) + .addCharacterCreationPolicy(target.characterCreationPolicy()); + if (target.expectedPriorPointerVersion() != null) { + builder.addExpectedPriorPointerVersion(target.expectedPriorPointerVersion().toString()); + } + return builder.build(); + } + + private static AccountGameplayAdmissionLeaseEvidence parseLease(byte[] bytes) { + if (bytes.length > AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES) { + throw invalid("Lease evidence exceeds its existing byte limit"); + } + String text; + try { + text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid("Lease evidence is not UTF-8"); + } + AccountGameplayAdmissionLeaseEvidence evidence = + AccountGameplayAdmissionLeaseEvidence.parseCanonical(text); + if (!Arrays.equals(bytes, canonicalLeaseBytes(evidence))) { + throw invalid("Lease evidence bytes are not the exact canonical UTF-8"); + } + return evidence; + } + + private static byte[] canonicalLeaseBytes(AccountGameplayAdmissionLeaseEvidence evidence) { + return evidence.canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + private static UUID uuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw invalid("UUID is not canonical and non-nil"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid("UUID is malformed"); + } + } + + private static BigInteger positiveDecimal(String value, String field) { + try { + return AccountJwtExactValues.positiveDecimalCounter(value); + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is not canonical positive decimal text"); + } + } + + private static long positiveLongDecimal(String value, String field) { + try { + return positiveDecimal(value, field).longValueExact(); + } catch (ArithmeticException outsideRange) { + throw invalid(field + " exceeds its supported signed-long range"); + } + } + + private static long positiveLong(long value, String field) { + if (value <= 0) throw invalid(field + " must be positive"); + return value; + } + + private static Instant instant(String value) { + try { + Instant parsed = Instant.parse(text(value, "ownerProofTerminalAt")); + if (!parsed.toString().equals(value)) throw invalid("Terminal timestamp is not canonical"); + return parsed; + } catch (RuntimeException malformed) { + throw invalid("Terminal timestamp is not canonical"); + } + } + + private static String text(String value, String field) { + if (value == null || value.isBlank() || !value.equals(value.trim())) { + throw invalid(field + " must be nonblank trimmed text"); + } + return value; + } + + private static String text(Object value, String field) { + if (!(value instanceof String string)) throw invalid(field + " must be text"); + return text(string, field); + } + + private static Map map(Object value, String field) { + if (!(value instanceof Map result)) throw invalid(field + " must be an object"); + return result; + } + + private static void requireEqual(Object expected, Object actual, String field) { + if (!Objects.equals(expected, actual)) + throw invalid(field + " differs from the lease-bound tuple"); + } + + private static void requireNonNil(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) + throw invalid(field + " must be a canonical non-nil UUID"); + } + + private static void requireWireSize(int size, int maximum, String field) { + if (size <= 0 || size > maximum) throw invalid(field + " exceeds its finite wire bound"); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static String requireAccountIssuer(String issuerId) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw invalid( + "Unsupported issuer identity; expected exact Account issuer " + + GameSessionAccountDelegationProfile.ISSUER + + "; legacy UUID issuer identities require explicit recovery"); + } + return issuerId; + } + + private static T one(List values, String field) { + if (values == null || values.size() != 1 || values.getFirst() == null) { + throw invalid(field + " must occur exactly once"); + } + return values.getFirst(); + } + + private static T optional(List values, String field) { + if (values == null || values.size() > 1) throw invalid(field + " must occur at most once"); + return values.isEmpty() ? null : values.getFirst(); + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java new file mode 100644 index 0000000000..207f05a239 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java @@ -0,0 +1,795 @@ +package net.firedevops.firemud.common.account.admission; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseState; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalAckReceiptEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.v1.CanonicalPlayableTargetEvidence; +import org.junit.jupiter.api.Test; + +/** Shape and tuple checks only; these carriers grant no Account or gameplay authority. */ +class AccountGameplayAdmissionLeaseGrpcCodecTest { + private static final String HIGH = "9007199254740993"; + private static final String JWT = "header.payload.signature"; + private static final UUID REQUEST_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + 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 OTHER = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID DECISION_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID CLEANUP_ID = UUID.fromString("88888888-8888-4888-8888-888888888888"); + private static final UUID VERSION_ID = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID HOLD_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); + + @Test + void roundTripsExactAcquireLeaseBytesAndCompleteAckWithoutClaimingAuthority() { + var lease = lease(); + var request = request(lease, candidate(lease), target(lease)); + var receipt = + OriginalAckReceiptEvidence.fromFields( + 1, + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + lease.leaseFence().longValueExact(), + lease.sha256(), + DECISION_ID, + 1_015_000L, + "101", + 1_014_999L, + "102"); + + var response = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireResponse( + request, lease, State.COMMITTED, DECISION_ID, null, receipt); + var decoded = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse(request, response); + + assertThat(response.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(lease.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(decoded.originalLeaseEvidence()).isEqualTo(lease); + assertThat(decoded.state()).isEqualTo(State.COMMITTED); + assertThat(decoded.originalAckReceipt().requestId()).isEqualTo(REQUEST_ID); + assertThat(decoded.originalAckReceipt().evidenceSha256()).isEqualTo(lease.sha256()); + assertThat(request.bindingGeneration()).isEqualTo(new BigInteger(HIGH)); + assertThat(request.toString()).doesNotContain(JWT); + assertThat(response.toString()).doesNotContain(JWT); + assertThat(decoded.toString()).doesNotContain(JWT); + assertThat(candidate(lease).regionEpoch()).isEqualTo(new BigInteger(HIGH)); + assertThat(target(lease).catalogRevision()).isEqualTo(Long.parseLong(HIGH)); + } + + @Test + void correlatesEveryLeaseScopeFieldAndIssuerGenerationToAcquireRequest() { + var lease = lease(); + var wire = wireRequest(lease, candidate(lease), target(lease)); + var candidate = wire.getExpectedCandidate(0); + var target = wire.getExpectedTarget(0); + String next = new BigInteger(HIGH).add(BigInteger.ONE).toString(); + var response = pendingResponse(lease); + + List mismatches = + List.of( + wire.toBuilder().setRequestUuid(0, OTHER.toString()).build(), + wire.toBuilder() + .setExpectedCandidate(0, candidate.toBuilder().setAccountUuid(0, OTHER.toString())) + .build(), + wire.toBuilder() + .setExpectedCandidate(0, candidate.toBuilder().setTenantUuid(0, OTHER.toString())) + .setExpectedTarget( + 0, + withResealedHoldDigest( + target.toBuilder().setCanonicalTenantUuid(0, OTHER.toString()))) + .build(), + wire.toBuilder() + .setExpectedTarget( + 0, withResealedHoldDigest(target.toBuilder().setRealmUuid(0, OTHER.toString()))) + .build(), + wire.toBuilder() + .setExpectedTarget( + 0, withResealedHoldDigest(target.toBuilder().setWorldSlug(0, "another-world"))) + .build(), + wire.toBuilder() + .setExpectedTarget(0, target.toBuilder().setRealmSlug(0, "another-realm")) + .build(), + wire.toBuilder() + .setExpectedCandidate( + 0, candidate.toBuilder().setPlayableStateNamespaceUuid(0, OTHER.toString())) + .setExpectedTarget( + 0, + withResealedHoldDigest( + target.toBuilder().setPlayableStateNamespaceUuid(0, OTHER.toString()))) + .build(), + wire.toBuilder() + .setExpectedCandidate( + 0, candidate.toBuilder().setGameInstanceUuid(0, OTHER.toString())) + .setExpectedTarget( + 0, + withResealedHoldDigest( + target.toBuilder().setCanonicalGameInstanceUuid(0, OTHER.toString()))) + .build(), + wire.toBuilder() + .setExpectedCandidate( + 0, candidate.toBuilder().setCharacterUuid(0, OTHER.toString())) + .build(), + wire.toBuilder() + .setExpectedCandidate(0, candidate.toBuilder().setSessionUuid(0, OTHER.toString())) + .build(), + wire.toBuilder().setBindingGeneration(0, next).build(), + wire.toBuilder() + .setExpectedTarget( + 0, withResealedHoldDigest(target.toBuilder().setCatalogRevision(0, next))) + .build(), + wire.toBuilder() + .setExpectedTarget(0, target.toBuilder().setPointerVersion(0, next)) + .build(), + wire.toBuilder() + .setExpectedCandidate(0, candidate.toBuilder().setRegionUuid(0, OTHER.toString())) + .build(), + wire.toBuilder() + .setExpectedCandidate(0, candidate.toBuilder().setRegionEpoch(0, next)) + .build(), + wire.toBuilder() + .setExpectedCandidate(0, candidate.toBuilder().setIssuerAuthGeneration(0, next)) + .build()); + + for (AcquireGameplayAdmissionLeaseRequest mismatch : mismatches) { + var parsedMismatch = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(mismatch); + assertThat(parsedMismatch).isNotNull(); + assertRejected(parsedMismatch, response); + } + + // The existing World request only accepts SHARED, so vary the valid lease-side scope here. + var validRequest = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(wire); + var isolatedLeaseCarrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + mutableObject(isolatedLeaseCarrier, "bindingScope").put("playableStateScope", "ISOLATED"); + mutableObject(isolatedLeaseCarrier, "tokenIdentityEvidence").put("tokenSHA256", jwtSha256(JWT)); + var isolatedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(isolatedLeaseCarrier); + assertRejected(validRequest, pendingResponse(isolatedLease)); + } + + @Test + void refusesLegacyUuidIssuerEvenWhenIssuerGenerationMatches() { + var lease = lease(); + var wire = wireRequest(lease, candidate(lease), target(lease)); + var canonicalCandidate = wire.getExpectedCandidate(0); + var legacyIssuerCandidate = + canonicalCandidate.toBuilder() + .setIssuerId(0, "77777777-7777-4777-8777-777777777777") + .build(); + assertThat(legacyIssuerCandidate.getIssuerAuthGeneration(0)) + .isEqualTo(canonicalCandidate.getIssuerAuthGeneration(0)); + + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wire.toBuilder().setExpectedCandidate(0, legacyIssuerCandidate).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported issuer identity") + .hasMessageContaining("legacy UUID issuer identities require explicit recovery"); + } + + @Test + void rejectsAcquireResponseWhenTokenDigestDiffersFromPresentedCredential() { + var lease = lease(); + var request = request(lease, candidate(lease), target(lease)); + var changedCarrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + mutableObject(changedCarrier, "tokenIdentityEvidence").put("tokenSHA256", "f".repeat(64)); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + + assertRejected(request, pendingResponse(changedLease)); + } + + @Test + void rejectsMissingDuplicateAndUnknownAcquireAndResponseFields() { + var lease = lease(); + var wireRequest = wireRequest(lease, candidate(lease), target(lease)); + var response = pendingResponse(lease); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder().clearExpectedCandidate().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder().addSchemaVersion(1).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder() + .setExpectedCandidate( + 0, + wireRequest.getExpectedCandidate(0).toBuilder() + .addAccountUuid(OTHER.toString())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder() + .setExpectedTarget( + 0, + wireRequest.getExpectedTarget(0).toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + REQUEST_ID, + JWT, + withGameInstance(candidate(lease), OTHER), + target(lease), + new BigInteger(HIGH))) + .isInstanceOf(IllegalArgumentException.class); + + var parsedRequest = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(wireRequest); + assertRejected(parsedRequest, response.toBuilder().clearOriginalLeaseEvidenceUtf8().build()); + assertRejected( + parsedRequest, + response.toBuilder() + .addState( + AccountGameplayAdmissionLeaseState.ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_PENDING) + .build()); + assertRejected(parsedRequest, response.toBuilder().setUnknownFields(unknown).build()); + assertRejected( + parsedRequest, + response.toBuilder() + .addOriginalLeaseEvidenceUtf8( + ByteString.copyFrom(lease.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .build()); + } + + @Test + void rejectsCommittedWithoutCompleteAckAndKeepsAbortDecisionUnknownExplicit() { + var lease = lease(); + var acquireRequest = request(lease, candidate(lease), target(lease)); + var committedWithoutAck = + pendingResponse(lease).toBuilder() + .setState( + 0, + AccountGameplayAdmissionLeaseState.ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_COMMITTED) + .addBindingDecisionUuid(DECISION_ID.toString()) + .build(); + assertRejected(acquireRequest, committedWithoutAck); + + byte[] originalBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + AbortGameplayAdmissionLeaseRequest abortWire = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortRequest(JWT, originalBytes, null); + var abortRequest = AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(abortWire); + assertThat(abortRequest.bindingDecisionId()).isNull(); + + var aborted = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortResponse( + abortRequest, lease, State.ABORTED, null, CLEANUP_ID, null); + var decodedAbort = + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortResponse(abortRequest, aborted); + assertThat(decodedAbort.state()).isEqualTo(State.ABORTED); + assertThat(decodedAbort.bindingDecisionId()).isNull(); + assertThat(decodedAbort.orphanCleanupId()).isEqualTo(CLEANUP_ID); + assertThat(decodedAbort.originalAckReceipt()).isNull(); + assertThat(aborted.getBindingDecisionUuidCount()).isZero(); + assertThat(aborted.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest( + abortWire.toBuilder() + .addBindingDecisionUuid(DECISION_ID.toString()) + .addBindingDecisionUuid(OTHER.toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void preservesOriginalBytesAcrossFinalizeAndReadAndRejectsChangedReadback() { + var lease = lease(); + byte[] originalBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + + var finalizeRequest = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest( + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest( + JWT, originalBytes, DECISION_ID)); + var finalizeResponse = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeResponse( + finalizeRequest, lease, State.PENDING, null, null, null); + assertThat(finalizeResponse.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes); + assertThat( + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( + finalizeRequest, finalizeResponse) + .originalLeaseEvidence()) + .isEqualTo(lease); + + var readRequest = + AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest( + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(JWT, originalBytes)); + var readResponse = + AccountGameplayAdmissionLeaseGrpcCodec.toReadResponse( + readRequest, lease, State.PENDING, null, null, null); + assertThat(readResponse.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes); + assertThat( + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse(readRequest, readResponse) + .originalLeaseEvidence()) + .isEqualTo(lease); + + var changedCarrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + changedCarrier.put("evaluatedAt", "1000001"); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); + var changedReadback = + readResponse.toBuilder() + .setOriginalLeaseEvidenceUtf8( + 0, + ByteString.copyFrom(changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .build(); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( + readRequest, changedReadback)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void validatesCompleteAckFenceAndUnsigned64TransactionIds() { + var lease = lease(); + var request = request(lease, candidate(lease), target(lease)); + String uint64Max = "18446744073709551615"; + String uint64MaxMinusOne = "18446744073709551614"; + String uint64MaxPlusOne = "18446744073709551616"; + var leaseId = UUID.fromString((String) lease.carrier().get("leaseId")); + var receipt = + OriginalAckReceiptEvidence.fromFields( + 1, + REQUEST_ID, + ACCOUNT_ID, + leaseId, + lease.leaseFence().longValueExact(), + lease.sha256(), + DECISION_ID, + 1_015_000L, + uint64MaxMinusOne, + 1_014_999L, + uint64Max); + + var response = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireResponse( + request, lease, State.COMMITTED, DECISION_ID, null, receipt); + var parsed = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse(request, response); + assertThat(parsed.originalAckReceipt().leaseFence()) + .isEqualTo(lease.leaseFence().longValueExact()); + assertThat(parsed.originalAckReceipt().finalizationXid()).isEqualTo(uint64MaxMinusOne); + assertThat(parsed.originalAckReceipt().receiptXid()).isEqualTo(uint64Max); + + assertThatThrownBy( + () -> + OriginalAckReceiptEvidence.fromFields( + 1, + REQUEST_ID, + ACCOUNT_ID, + leaseId, + lease.leaseFence().longValueExact(), + lease.sha256(), + DECISION_ID, + 1_015_000L, + uint64MaxPlusOne, + 1_014_999L, + uint64Max)) + .isInstanceOf(IllegalArgumentException.class); + + var wrongFence = + OriginalAckReceiptEvidence.fromFields( + 1, + REQUEST_ID, + ACCOUNT_ID, + leaseId, + lease.leaseFence().longValueExact() + 1, + lease.sha256(), + DECISION_ID, + 1_015_000L, + "101", + 1_014_999L, + "102"); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireResponse( + request, lease, State.COMMITTED, DECISION_ID, null, wrongFence)) + .isInstanceOf(IllegalArgumentException.class); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var wireReceipt = response.getOriginalAckReceipt(0); + assertRejected( + request, + response.toBuilder() + .setOriginalAckReceipt(0, wireReceipt.toBuilder().clearReceiptXid()) + .build()); + assertRejected( + request, + response.toBuilder() + .setOriginalAckReceipt( + 0, + wireReceipt.toBuilder() + .addLeaseFence(Long.toString(lease.leaseFence().longValueExact()))) + .build()); + assertRejected( + request, + response.toBuilder() + .setOriginalAckReceipt(0, wireReceipt.toBuilder().setUnknownFields(unknown)) + .build()); + } + + @Test + void rejectsResumeAndExpectedOldGenerationLeaseForms() { + var resumeCarrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + resumeCarrier.put("leaseKind", "RESUME"); + resumeCarrier.put("resumeEpisodeId", OTHER.toString()); + resumeCarrier.put("expectedOldBindingGeneration", "7"); + var resume = AccountGameplayAdmissionLeaseEvidence.fromCarrier(resumeCarrier); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest( + JWT, resume.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + + var oldGenerationCarrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + oldGenerationCarrier.put("expectedOldBindingGeneration", "7"); + var oldGeneration = AccountGameplayAdmissionLeaseEvidence.fromCarrier(oldGenerationCarrier); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest( + JWT, oldGeneration.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void enforcesAcquireOriginalLeaseRequestAndResponseWireBounds() { + var lease = lease(); + var candidate = candidate(lease); + var target = target(lease); + var acquire = wireRequest(lease, candidate, target); + UnknownFieldSet oversizedAcquireField = + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom( + new byte + [AccountGameplayAdmissionLeaseGrpcCodec + .MAX_ACQUIRE_REQUEST_WIRE_BYTES])) + .build()) + .build(); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + acquire.toBuilder().setUnknownFields(oversizedAcquireField).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + + byte[] originalLease = lease.canonicalJson().getBytes(StandardCharsets.UTF_8); + var finalizeRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest(JWT, originalLease, DECISION_ID); + var readRequest = AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(JWT, originalLease); + var abortRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortRequest(JWT, originalLease, null); + UnknownFieldSet oversizedOriginalLeaseField = + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom( + new byte + [AccountGameplayAdmissionLeaseGrpcCodec + .MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES])) + .build()) + .build(); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest( + finalizeRequest.toBuilder() + .setUnknownFields(oversizedOriginalLeaseField) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest( + readRequest.toBuilder().setUnknownFields(oversizedOriginalLeaseField).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest( + abortRequest.toBuilder().setUnknownFields(oversizedOriginalLeaseField).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + + var parsedAcquire = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(acquire); + var parsedFinalize = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(finalizeRequest); + var parsedRead = AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(readRequest); + var parsedAbort = AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(abortRequest); + var oversizedResponse = + pendingResponse(lease).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom( + new byte + [AccountGameplayAdmissionLeaseGrpcCodec + .MAX_RESPONSE_WIRE_BYTES])) + .build()) + .build()) + .build(); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + parsedAcquire, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( + parsedFinalize, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( + parsedRead, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + assertThatThrownBy( + () -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortResponse( + parsedAbort, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + } + + private static void assertRejected( + AcquireRequest request, AccountGameplayAdmissionLeaseResponse response) { + assertThatThrownBy( + () -> AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AcquireRequest request( + AccountGameplayAdmissionLeaseEvidence lease, Candidate candidate, Target target) { + return AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest(lease, candidate, target)); + } + + private static AcquireGameplayAdmissionLeaseRequest wireRequest( + AccountGameplayAdmissionLeaseEvidence lease, Candidate candidate, Target target) { + return AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + UUID.fromString((String) lease.carrier().get("requestId")), + JWT, + candidate, + target, + new BigInteger(HIGH)); + } + + private static AccountGameplayAdmissionLeaseResponse pendingResponse( + AccountGameplayAdmissionLeaseEvidence lease) { + return AccountGameplayAdmissionLeaseResponse.newBuilder() + .addSchemaVersion(1) + .addOriginalLeaseEvidenceUtf8( + ByteString.copyFrom(lease.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .addState(AccountGameplayAdmissionLeaseState.ACCOUNT_GAMEPLAY_ADMISSION_LEASE_STATE_PENDING) + .build(); + } + + private static AccountGameplayAdmissionLeaseEvidence lease() { + Map carrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + mutableObject(carrier, "tokenIdentityEvidence").put("tokenSHA256", jwtSha256(JWT)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static Candidate candidate(AccountGameplayAdmissionLeaseEvidence lease) { + Map scope = object(lease.carrier(), "bindingScope"); + Map authority = object(lease.carrier(), "authorityTuple"); + return new Candidate( + uuid(scope, "accountId"), + uuid(scope, "tenantId"), + uuid(scope, "playableStateNamespaceId"), + uuid(scope, "characterId"), + (String) scope.get("playableStateScope"), + uuid(scope, "gameInstanceId"), + 71, + uuid(scope, "sessionId"), + uuid(scope, "regionId"), + new BigInteger((String) scope.get("regionEpoch")), + GameSessionAccountDelegationProfile.ISSUER, + new BigInteger((String) authority.get("issuerAuthGeneration")), + new BigInteger(HIGH), + new BigInteger(HIGH), + new BigInteger(HIGH)); + } + + private static Candidate withGameInstance(Candidate c, UUID gameInstanceId) { + return new Candidate( + c.accountId(), + c.tenantId(), + c.playableStateNamespaceId(), + c.characterId(), + c.playableStateScope(), + gameInstanceId, + c.runtimeGameInstanceId(), + c.sessionId(), + c.regionId(), + c.regionEpoch(), + c.issuerId(), + c.issuerAuthGeneration(), + c.issuerIndexLayoutVersion(), + c.issuerIndexPartitionCount(), + c.issuerIndexPartitionCapacity()); + } + + private static Target target(AccountGameplayAdmissionLeaseEvidence lease) { + Map carrier = lease.carrier(); + Map scope = object(carrier, "bindingScope"); + UUID tenantId = uuid(scope, "tenantId"); + UUID realmId = uuid(scope, "realmId"); + UUID namespaceId = uuid(scope, "playableStateNamespaceId"); + UUID gameInstanceId = uuid(scope, "gameInstanceId"); + long catalogRevision = Long.parseLong((String) scope.get("catalogRevision")); + long pointerVersion = Long.parseLong((String) scope.get("pointerVersion")); + long activeWorldEpoch = Long.parseLong(HIGH); + String requestId = (String) carrier.get("requestId"); + String requestDigest = "c".repeat(64); + WorldCanonicalInitialAdmissionHold.Request ownerRequest = + new WorldCanonicalInitialAdmissionHold.Request( + (String) carrier.get("targetNamespace"), + tenantId, + (String) scope.get("worldSlug"), + realmId, + namespaceId, + (String) scope.get("playableStateScope"), + gameInstanceId, + VERSION_ID, + activeWorldEpoch, + requestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + catalogRevision, + null); + return new Target( + (String) carrier.get("targetNamespace"), + "tenant", + tenantId, + (String) scope.get("worldSlug"), + "World", + realmId, + (String) scope.get("realmSlug"), + "Realm", + 11, + 71, + namespaceId, + (String) scope.get("playableStateScope"), + gameInstanceId, + VERSION_ID, + 99, + catalogRevision, + pointerVersion, + "d".repeat(64), + activeWorldEpoch, + requestId, + requestDigest, + OriginKind.NO_PRIOR_POINTER, + null, + HOLD_ID, + HOLD_FENCE, + new WorldCanonicalInitialAdmissionHold.HoldIdentity(ownerRequest, HOLD_ID, HOLD_FENCE) + .holdBindingDigest(), + 101, + "sha256:" + "a".repeat(64), + OwnerProofOutcome.COMMITTED, + false, + Instant.parse("2026-10-25T00:00:00Z"), + "PRESEEDED_ONLY"); + } + + private static CanonicalPlayableTargetEvidence withResealedHoldDigest( + CanonicalPlayableTargetEvidence.Builder builder) { + CanonicalPlayableTargetEvidence target = builder.build(); + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin origin = + switch (target.getInitialAdmissionOriginKind(0)) { + case CANONICAL_GAMEPLAY_ADMISSION_ORIGIN_KIND_NO_PRIOR_POINTER -> + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER; + case CANONICAL_GAMEPLAY_ADMISSION_ORIGIN_KIND_EXPECT_CLOSED -> + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED; + default -> throw new IllegalArgumentException("Unsupported initial admission origin"); + }; + Long expectedPriorPointerVersion = + target.getExpectedPriorPointerVersionCount() == 0 + ? null + : Long.parseLong(target.getExpectedPriorPointerVersion(0)); + var request = + new WorldCanonicalInitialAdmissionHold.Request( + target.getTargetNamespace(0), + UUID.fromString(target.getCanonicalTenantUuid(0)), + target.getWorldSlug(0), + UUID.fromString(target.getRealmUuid(0)), + UUID.fromString(target.getPlayableStateNamespaceUuid(0)), + target.getPlayableStateScope(0), + UUID.fromString(target.getCanonicalGameInstanceUuid(0)), + UUID.fromString(target.getCanonicalVersionUuid(0)), + Long.parseLong(target.getActiveWorldEpoch(0)), + target.getInitialAdmissionRequestId(0), + target.getInitialAdmissionRequestDigest(0), + origin, + Long.parseLong(target.getCatalogRevision(0)), + expectedPriorPointerVersion); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, + UUID.fromString(target.getHoldUuid(0)), + UUID.fromString(target.getHoldFenceUuid(0))); + return target.toBuilder().setHoldBindingDigest(0, hold.holdBindingDigest()).build(); + } + + private static String jwtSha256(String jwt) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(jwt.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static Map object(Map carrier, String field) { + return (Map) carrier.get(field); + } + + @SuppressWarnings("unchecked") + private static Map mutableObject(Map carrier, String field) { + return (Map) carrier.get(field); + } + + private static UUID uuid(Map source, String field) { + return UUID.fromString((String) source.get(field)); + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java new file mode 100644 index 0000000000..3ef303e6ca --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java @@ -0,0 +1,894 @@ +package net.firedevops.firemud.common.account.admission; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayAdmissionCandidate; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayAdmissionDecisionResponse; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +/** Shape and tuple codec proof only; this fixture grants no admission or Account authority. */ +class CanonicalGameplayAdmissionDecisionReadGrpcCodecTest { + private static final String HIGH = "9007199254740993"; + private static final UUID DECISION_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final UUID OTHER = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID VERSION_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID HOLD_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID REALM = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID PLAYABLE_NAMESPACE = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID INSTANCE = UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); + + @Test + void roundTripsCompleteProvisionalReadAndPreservesOriginalLeaseBytes() { + var lease = lease(); + var request = request(lease); + var response = response(request, lease, target(lease, "PRESEEDED_ONLY")); + + var evidence = CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromResponse(request, response); + + assertThat(response.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(request.expectedLeaseEvidenceUtf8()); + assertThat(evidence.originalLeaseEvidenceJson()).isEqualTo(lease.canonicalJson()); + assertThat(evidence.status()) + .isEqualTo(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Status.PROVISIONAL); + assertThat(evidence.bindingGeneration()).isEqualTo(new BigInteger(HIGH)); + assertThat(evidence.candidate().regionEpoch()).isEqualTo(new BigInteger(HIGH)); + assertThat(evidence.candidate().issuerIndexPartitionCount()).isEqualTo(new BigInteger(HIGH)); + assertThat(evidence.candidate().issuerIndexPartitionCapacity()).isEqualTo(new BigInteger(HIGH)); + assertThat(evidence.targetEvidence().catalogRevision()).isEqualTo(Long.parseLong(HIGH)); + assertThat(evidence.targetEvidence().pointerVersion()).isEqualTo(Long.parseLong(HIGH)); + assertThat(evidence.targetEvidence().activeWorldEpoch()).isEqualTo(Long.parseLong(HIGH)); + } + + @Test + void rejectsChangedDecisionLeaseCandidateAndOwnerProofTuple() { + var lease = lease(); + var request = request(lease); + var response = response(request, lease, target(lease, "PRESEEDED_ONLY")); + + assertRejected( + request, response.toBuilder().setBindingDecisionUuid(0, OTHER.toString()).build()); + + var changedLeaseCarrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); + mutableObject(changedLeaseCarrier, "bindingScope").put("pointerVersion", "9007199254740994"); + var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedLeaseCarrier); + assertRejected( + request, + response.toBuilder() + .setOriginalLeaseEvidenceUtf8( + 0, + ByteString.copyFrom(changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .build()); + + assertRejected( + request, + response.toBuilder() + .setCandidate( + 0, response.getCandidate(0).toBuilder().setAccountUuid(0, OTHER.toString())) + .build()); + + var legacyIssuerCandidate = + response.getCandidate(0).toBuilder().setIssuerId(0, "77777777-7777-4777-8777-777777777777"); + assertThat(legacyIssuerCandidate.getIssuerAuthGeneration(0)) + .isEqualTo(response.getCandidate(0).getIssuerAuthGeneration(0)); + assertRejected( + request, response.toBuilder().setCandidate(0, legacyIssuerCandidate.build()).build()); + + assertRejected( + request, + response.toBuilder() + .setTargetEvidence( + 0, + response.getTargetEvidence(0).toBuilder() + .setHoldBindingDigest(0, "sha256:" + "f".repeat(64)) + .build()) + .build()); + } + + @Test + void keepsIssuerIdAtStringTagElevenAndEmitsOnlyTheAccountIssuer() { + var wire = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toCandidate(candidate(lease())); + var issuerField = + CanonicalGameplayAdmissionCandidate.getDescriptor().findFieldByName("issuer_id"); + + assertThat(issuerField.getNumber()).isEqualTo(11); + assertThat(issuerField.getType()) + .isEqualTo(com.google.protobuf.Descriptors.FieldDescriptor.Type.STRING); + assertThat(wire.getIssuerIdList()).containsExactly(GameSessionAccountDelegationProfile.ISSUER); + } + + @Test + void rejectsMissingDuplicateAndUnknownWireFieldsAtEachClosedLevel() { + var lease = lease(); + var wireRequest = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toRequest(DECISION_ID, lease); + var request = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(wireRequest); + var response = response(request, lease, target(lease, "PRESEEDED_ONLY")); + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( + wireRequest.toBuilder().clearExpectedLeaseEvidenceUtf8().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( + wireRequest.toBuilder().addSchemaVersion(1).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + + assertRejected(request, response.toBuilder().clearBindingGeneration().build()); + assertRejected(request, response.toBuilder().addBindingGeneration(HIGH).build()); + assertRejected(request, response.toBuilder().setUnknownFields(unknown).build()); + assertRejected( + request, + response.toBuilder() + .setCandidate(0, response.getCandidate(0).toBuilder().clearAccountUuid().build()) + .build()); + assertRejected( + request, + response.toBuilder() + .setCandidate( + 0, response.getCandidate(0).toBuilder().addAccountUuid(OTHER.toString()).build()) + .build()); + assertRejected( + request, + response.toBuilder() + .setCandidate(0, response.getCandidate(0).toBuilder().setUnknownFields(unknown).build()) + .build()); + assertRejected( + request, + response.toBuilder() + .setTargetEvidence( + 0, response.getTargetEvidence(0).toBuilder().setUnknownFields(unknown).build()) + .build()); + assertRejected( + request, + response.toBuilder() + .setTargetEvidence( + 0, + response.getTargetEvidence(0).toBuilder() + .addExpectedPriorPointerVersion("1") + .addExpectedPriorPointerVersion("2") + .build()) + .build()); + } + + @Test + void enforcesFiniteRequestAndCompleteResponseBounds() { + var lease = lease(); + var wireRequest = CanonicalGameplayAdmissionDecisionReadGrpcCodec.toRequest(DECISION_ID, lease); + var oversizedRequest = + wireRequest.toBuilder() + .clearExpectedLeaseEvidenceUtf8() + .addExpectedLeaseEvidenceUtf8( + ByteString.copyFrom( + new byte + [CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_REQUEST_WIRE_BYTES])) + .build(); + assertThatThrownBy( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(oversizedRequest)) + .isInstanceOf(IllegalArgumentException.class); + + var request = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(wireRequest); + assertThatThrownBy(() -> response(request, lease, target(lease, "x".repeat(270_000)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + } + + @Test + void roundTripsClosedPublishedRealmSelectorAndCompleteCurrentTarget() throws Exception { + var source = publishedRealmEvidence(); + var selector = source.request(); + var wireRequest = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(selector); + var parsedRequest = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(wireRequest); + assertThat(parsedRequest.selector()).isEqualTo(selector); + + var target = publishedTarget(source); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + parsedRequest, source, target); + var evidence = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, response); + assertThat(evidence.selector()).isEqualTo(selector); + assertThat(evidence.sourceEvidence()).isEqualTo(source); + assertThat(evidence.currentTarget()).isEqualTo(target); + + UnknownFieldSet unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().addSchemaVersion(1).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder() + .setSelector( + 0, wireRequest.getSelector(0).toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().addSelector(wireRequest.getSelector(0)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder() + .setSelector(0, wireRequest.getSelector(0).toBuilder().clearWorldSlug()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().clearSelector().build())) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, response.toBuilder().addSchemaVersion(1).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setPublishedSource( + 0, response.getPublishedSource(0).toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, response.toBuilder().clearPublishedSource().build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setPublishedSource( + 0, response.getPublishedSource(0).toBuilder().clearRequest()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder().addCurrentTarget(response.getCurrentTarget(0)).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setCurrentTarget( + 0, response.getCurrentTarget(0).toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setCurrentTarget( + 0, response.getCurrentTarget(0).toBuilder().addPointerVersion("74")) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setPublishedSource( + 0, + response.getPublishedSource(0).toBuilder() + .setRequest( + response.getPublishedSource(0).getRequest().toBuilder() + .setCanonicalTenantUuid(OTHER.toString()))) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsPublishedTargetSourceAndSelectorSubstitutions() throws Exception { + var source = publishedRealmEvidence(); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + source.request())); + var target = publishedTarget(source); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + request, source, target); + var targetEvidence = response.getCurrentTarget(0); + for (var changed : + List.of( + targetEvidence.toBuilder().setCanonicalTenantUuid(0, OTHER.toString()).build(), + targetEvidence.toBuilder().setPointerVersion(0, "74").build(), + targetEvidence.toBuilder().setAdmissionPointerSnapshotDigest(0, "f".repeat(64)).build(), + targetEvidence.toBuilder().setOwnerProofDigest(0, "sha256:" + "f".repeat(64)).build(), + targetEvidence.toBuilder().setCharacterCreationPolicy(0, "PLAYER_CREATED").build())) { + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, response.toBuilder().setCurrentTarget(0, changed).build())) + .isInstanceOf(IllegalArgumentException.class); + } + + var changedSelector = + selectorWithExpectedPointer( + request.selector(), request.selector().expectedPointerVersion() + 1); + var changedRequest = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( + changedSelector)); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + changedRequest, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void enforcesPublishedRealmWireBoundsOnRequestAndResponse() throws Exception { + var source = publishedRealmEvidence(); + var request = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(source.request()); + var oversizedRequest = + request.toBuilder() + .setSelector(0, request.getSelector(0).toBuilder().setWorldSlug("x".repeat(3_000))) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + oversizedRequest)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + + var parsedRequest = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request); + var response = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + parsedRequest, source, publishedTarget(source)); + var oversizedResponse = + response.toBuilder() + .setPublishedSource( + 0, + response.getPublishedSource(0).toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFrom( + new byte + [CanonicalGameplayAdmissionDecisionReadGrpcCodec + .MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES]))) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire bound"); + } + + /** Controlled owner/policy fixture for codec shape proof; it simulates no owner execution. */ + private static CanonicalGameplayRosterOwnerReadEvidence publishedRealmEvidence() + throws Exception { + var operation = publishedOperation(5L); + var selected = operation.account().input().selection(); + var target = selected.target(); + var sourceBinding = selected.selectedCommit(); + var sourcePolicy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":1,\"worldSlug\":\"earth\",\"worldDisplayName\":\"Earth\"," + + "\"realmSlug\":\"main\",\"realmDisplayName\":\"Main\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PRESEEDED_ONLY\"}", + JSON); + UUID policyId = uuid("33333333-3333-4333-8333-333333333333"); + UUID policyCommitId = uuid("44444444-4444-4444-8444-444444444444"); + UUID policyRevisionId = uuid("55555555-5555-4555-8555-555555555555"); + var release = publishedRelease(operation, "generation-1"); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), Outcome.PUBLISHED, release, 6L); + var policyEvidence = + new PublishedRealmEntryPolicyEvidence( + policyId, + policyCommitId, + policyRevisionId, + "main-policy-v1", + sourcePolicy, + PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + target, + release.versionNumber(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + policyCommitId, + policyRevisionId, + "main-policy-v1", + sourcePolicy)); + List> policyRows = + List.of( + Map.of( + "commitId", policyCommitId.toString(), + "revisionId", policyRevisionId.toString(), + "logicalRevisionId", "main-policy-v1", + "policy", JSON.readTree(sourcePolicy.canonicalJson()))); + var snapshot = + Map.of( + "schema", + PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA, + "bindingJson", + sourceBinding.canonicalJson(), + "bindingDigest", + sourceBinding.digest(), + "sourceEpoch", + "43", + "policies", + policyRows); + byte[] snapshotBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + var capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + var policies = List.of(policyEvidence); + String policySetDigest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + release.versionNumber(), + sourceBinding.commitId(), + "43", + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + policies); + var policySet = + new PublishedRealmEntryPolicySetEvidence( + target, + release.versionNumber(), + sourceBinding.commitId(), + "43", + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + policies.size(), + policySetDigest, + policies); + + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + operation.world().request().targetNamespace(), + target.canonicalTenantId(), + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + target.canonicalVersionId(), + 82L, + "first-open-request-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + holdRequest, + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + uuid("ffffffff-ffff-4fff-8fff-ffffffffffff")); + var proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-08T03:04:05Z")); + var request = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + operation.world().request().targetNamespace(), + target.canonicalTenantId(), + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + target.canonicalVersionId(), + 71L, + 73L, + 82L); + return new CanonicalGameplayRosterOwnerReadEvidence(request, "1".repeat(64), proof, policySet); + } + + private static Target publishedTarget(CanonicalGameplayRosterOwnerReadEvidence evidence) { + var request = evidence.request(); + var proof = evidence.gameSessionOwnerProof(); + var hold = proof.holdIdentity(); + return new Target( + request.targetNamespace(), + "tenant", + request.canonicalTenantUuid(), + request.worldSlug(), + "Earth", + request.realmUuid(), + request.realmSlug(), + "Main", + 11L, + 71L, + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + 99L, + request.expectedCatalogRevision(), + request.expectedPointerVersion(), + evidence.admissionPointerSnapshotDigest(), + request.expectedActiveWorldEpoch(), + hold.request().initialAdmissionRequestId(), + hold.request().initialAdmissionRequestDigest(), + OriginKind.NO_PRIOR_POINTER, + null, + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + OwnerProofOutcome.COMMITTED, + false, + proof.terminalAt(), + "PRESEEDED_ONLY"); + } + + private static CanonicalGameplayRosterOwnerReadEvidence.Request selectorWithExpectedPointer( + CanonicalGameplayRosterOwnerReadEvidence.Request request, long expectedPointerVersion) { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + request.targetNamespace(), + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + expectedPointerVersion, + request.expectedActiveWorldEpoch()); + } + + private static GameDesignPublicationOperationBinding publishedOperation(long epoch) + throws Exception { + var seed = AuthoringFixtures.startLocationEvidence(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var target = draft.target(); + String requestId = "publication-request"; + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + requestId, + Long.toString(epoch), + "fixed-notes", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var request = seed.request(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + requestId, + selected.digest().substring(7), + epoch, + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + requestId) + .derivedWorkflowIdentity(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + return new GameDesignPublicationOperationBinding( + account, + world, + net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures.stipulated( + account, world)); + } + + private static ReleaseContent publishedRelease( + GameDesignPublicationOperationBinding operation, String generation) { + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + 12, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "asset-é", "FILE", "artifacts/sha256/" + "a".repeat(64), DIGEST, "text/plain", 1)), + List.of("asset-é"), + participants, + List.of("LOOK"), + generation, + operation.world()); + } + + private static void assertRejected( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence request, + GetCanonicalGameplayAdmissionDecisionResponse response) { + assertThatThrownBy( + () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static GetCanonicalGameplayAdmissionDecisionResponse response( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence request, + AccountGameplayAdmissionLeaseEvidence lease, + Target target) { + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + request, DECISION_ID, lease, new BigInteger(HIGH), null, null, candidate(lease), target); + } + + private static CanonicalGameplayAdmissionDecisionReadGrpcCodec.RequestEvidence request( + AccountGameplayAdmissionLeaseEvidence lease) { + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toRequest(DECISION_ID, lease)); + } + + private static AccountGameplayAdmissionLeaseEvidence lease() { + return AccountGameplayAdmissionLeaseEvidence.fromCarrier( + AccountGameplayAdmissionLeaseEvidenceTest.fixture()); + } + + private static Candidate candidate(AccountGameplayAdmissionLeaseEvidence lease) { + Map scope = object(lease.carrier(), "bindingScope"); + Map authority = object(lease.carrier(), "authorityTuple"); + return new Candidate( + uuid(scope, "accountId"), + uuid(scope, "tenantId"), + uuid(scope, "playableStateNamespaceId"), + uuid(scope, "characterId"), + (String) scope.get("playableStateScope"), + uuid(scope, "gameInstanceId"), + 71, + uuid(scope, "sessionId"), + uuid(scope, "regionId"), + new BigInteger((String) scope.get("regionEpoch")), + GameSessionAccountDelegationProfile.ISSUER, + new BigInteger((String) authority.get("issuerAuthGeneration")), + new BigInteger(HIGH), + new BigInteger(HIGH), + new BigInteger(HIGH)); + } + + private static Target target(AccountGameplayAdmissionLeaseEvidence lease, String policy) { + Map carrier = lease.carrier(); + Map scope = object(carrier, "bindingScope"); + UUID tenantId = uuid(scope, "tenantId"); + UUID realmId = uuid(scope, "realmId"); + UUID playableStateNamespaceId = uuid(scope, "playableStateNamespaceId"); + UUID gameInstanceId = uuid(scope, "gameInstanceId"); + long catalogRevision = Long.parseLong((String) scope.get("catalogRevision")); + long pointerVersion = Long.parseLong((String) scope.get("pointerVersion")); + long activeWorldEpoch = Long.parseLong(HIGH); + String requestId = (String) carrier.get("requestId"); + String requestDigest = "c".repeat(64); + WorldCanonicalInitialAdmissionHold.Request ownerRequest = + new WorldCanonicalInitialAdmissionHold.Request( + (String) carrier.get("targetNamespace"), + tenantId, + (String) scope.get("worldSlug"), + realmId, + playableStateNamespaceId, + (String) scope.get("playableStateScope"), + gameInstanceId, + VERSION_ID, + activeWorldEpoch, + requestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + catalogRevision, + null); + return new Target( + (String) carrier.get("targetNamespace"), + "tenant", + tenantId, + (String) scope.get("worldSlug"), + "World", + realmId, + (String) scope.get("realmSlug"), + "Realm", + 11, + 71, + playableStateNamespaceId, + (String) scope.get("playableStateScope"), + gameInstanceId, + VERSION_ID, + 99, + catalogRevision, + pointerVersion, + "d".repeat(64), + activeWorldEpoch, + requestId, + requestDigest, + OriginKind.NO_PRIOR_POINTER, + null, + HOLD_ID, + HOLD_FENCE, + new WorldCanonicalInitialAdmissionHold.HoldIdentity(ownerRequest, HOLD_ID, HOLD_FENCE) + .holdBindingDigest(), + 101, + "sha256:" + "a".repeat(64), + OwnerProofOutcome.COMMITTED, + false, + Instant.parse("2026-10-25T00:00:00Z"), + policy); + } + + private static Map object(Map source, String field) { + return (Map) source.get(field); + } + + @SuppressWarnings("unchecked") + private static Map mutableObject(Map source, String field) { + return (Map) source.get(field); + } + + private static UUID uuid(Map source, String field) { + return UUID.fromString((String) source.get(field)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberAcknowledgement.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberAcknowledgement.java new file mode 100644 index 0000000000..b7dc392875 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberAcknowledgement.java @@ -0,0 +1,126 @@ +package net.firedevops.firemud.gamesession.binding; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; + +/** Completed schema-v2 acknowledgement for one exact binding-local account-index member. */ +public record CanonicalGameplayAccountMemberAcknowledgement( + CanonicalGameplayAccountMemberRepairOperation operation, + BigInteger coverageGeneration, + String member) { + public CanonicalGameplayAccountMemberAcknowledgement { + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(coverageGeneration, "coverageGeneration"); + if (coverageGeneration.compareTo(operation.inventorySnapshotRevision()) <= 0) { + throw new IllegalArgumentException( + "coverageGeneration must be newer than the immutable inventory snapshot"); + } + Objects.requireNonNull(member, "member"); + if (!member.equals(operation.member())) { + throw new IllegalArgumentException("member differs from the exact owner operation"); + } + } + + public int schemaVersion() { + return 2; + } + + public AccountCoverageState accountCoverageState() { + return AccountCoverageState.NO_ACTIVE_ACCOUNT_WIDE_FLOW; + } + + public UUID operationId() { + return operation.operationId(); + } + + public NotApplicable accountCoverageOperationId() { + return NotApplicable.NOT_APPLICABLE; + } + + public NotApplicable accountCoverageLifecycle() { + return NotApplicable.NOT_APPLICABLE; + } + + public NotApplicable accountCoverageOperationFence() { + return NotApplicable.NOT_APPLICABLE; + } + + public NotApplicable accountAdmissionFence() { + return NotApplicable.NOT_APPLICABLE; + } + + public NotApplicable historicalAccountAdmissionFence() { + return NotApplicable.NOT_APPLICABLE; + } + + public NotApplicable resolvedScope() { + return NotApplicable.NOT_APPLICABLE; + } + + public UUID transitionId() { + return operation.transitionId(); + } + + public CanonicalGameplayBindingRef bindingRef() { + return operation.bindingRef(); + } + + public UUID accountId() { + return operation.accountId(); + } + + public UUID tenantId() { + return operation.tenantId(); + } + + public BigInteger bindingGeneration() { + return operation.bindingGeneration(); + } + + public UUID accountIndexFence() { + return operation.accountIndexFence(); + } + + public BigInteger operationFence() { + return operation.operationFence(); + } + + public UUID coverageFence() { + return operation.coverageFence(); + } + + public BigInteger inventorySnapshotRevision() { + return operation.inventorySnapshotRevision(); + } + + public CanonicalGameplayBindingAccountIndexObligation.Action action() { + return CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN; + } + + public Readback readback() { + return new Readback(ReadbackState.PRESENT, member); + } + + public enum AccountCoverageState { + NO_ACTIVE_ACCOUNT_WIDE_FLOW + } + + public enum NotApplicable { + NOT_APPLICABLE + } + + public enum ReadbackState { + PRESENT + } + + public record Readback(ReadbackState state, String member) { + public Readback { + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(member, "member"); + if (state != ReadbackState.PRESENT) { + throw new IllegalArgumentException("binding-local ADD_OR_RETAIN requires PRESENT"); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperation.java new file mode 100644 index 0000000000..d64862fbce --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperation.java @@ -0,0 +1,98 @@ +package net.firedevops.firemud.gamesession.binding; + +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; + +/** Immutable owner-allocated tuple for one binding-local account-index member repair. */ +public record CanonicalGameplayAccountMemberRepairOperation( + UUID transitionId, + UUID operationId, + BigInteger operationFence, + UUID coverageFence, + BigInteger inventorySnapshotRevision, + CanonicalGameplayBindingRef bindingRef, + UUID accountId, + UUID tenantId, + BigInteger bindingGeneration, + UUID accountIndexFence, + CanonicalGameplayBindingAccountIndexObligation originalObligation, + String member, + BigInteger accountControlEpoch) { + public CanonicalGameplayAccountMemberRepairOperation { + requireNonNil(transitionId, "transitionId"); + requireNonNil(operationId, "operationId"); + if (operationId.equals(transitionId)) { + throw new IllegalArgumentException("operationId must be distinct from transitionId"); + } + requirePositive(operationFence, "operationFence"); + requireNonNil(coverageFence, "coverageFence"); + requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision"); + Objects.requireNonNull(bindingRef, "bindingRef"); + requireNonNil(accountId, "accountId"); + requireNonNil(tenantId, "tenantId"); + requirePositive(bindingGeneration, "bindingGeneration"); + requireNonNil(accountIndexFence, "accountIndexFence"); + Objects.requireNonNull(originalObligation, "originalObligation"); + Objects.requireNonNull(member, "member"); + Objects.requireNonNull(accountControlEpoch, "accountControlEpoch"); + if (accountControlEpoch.signum() < 0) { + throw new IllegalArgumentException("accountControlEpoch must not be negative"); + } + if (coverageFence.equals(accountIndexFence) + || coverageFence.equals(operationId) + || coverageFence.equals(transitionId)) { + throw new IllegalArgumentException( + "coverageFence must be distinct from operation identities"); + } + if (!bindingRef.tenantId().equals(tenantId.toString())) { + throw new IllegalArgumentException("bindingRef tenant segment differs from tenantId"); + } + if (!originalObligation.transitionId().equals(transitionId) + || originalObligation.ordinal() != 0 + || !originalObligation.bindingRef().equals(bindingRef) + || !originalObligation.accountId().equals(accountId) + || !originalObligation.tenantId().equals(tenantId) + || originalObligation.action() + != CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN + || originalObligation.expectedPriorGeneration() != null + || !originalObligation.bindingGeneration().equals(bindingGeneration) + || !originalObligation.accountIndexFence().equals(accountIndexFence) + || originalObligation.executionPhase() + != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS + || originalObligation.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + || (originalObligation.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED + && originalObligation.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE)) { + throw new IllegalArgumentException( + "originalObligation is not the exact outstanding NEW account-index obligation"); + } + if (originalObligation.inventoryRevision().compareTo(inventorySnapshotRevision) > 0) { + throw new IllegalArgumentException( + "original obligation is newer than the immutable inventory snapshot"); + } + String expectedMember = + new CanonicalGameplayAccountIndexMember(bindingRef, bindingGeneration, accountIndexFence) + .value(); + if (!expectedMember.equals(member)) { + throw new IllegalArgumentException("member differs from the exact 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"); + } + } +} 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 index 775a95ebe6..a6462ecf36 100644 --- 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 @@ -39,6 +39,15 @@ public record CanonicalGameplayBindingAccountIndexObligation( Objects.requireNonNull(status, "status"); requirePositive(inventoryRevision, "inventoryRevision"); Objects.requireNonNull(projectionState, "projectionState"); + if (status == Status.ACKNOWLEDGED + && (ordinal != 0 + || action != Action.ADD_OR_RETAIN + || expectedPriorGeneration != null + || executionPhase != ExecutionPhase.BEFORE_FINAL_CAS + || projectionState != ProjectionState.PRESENT_AWAITING_COVERAGE)) { + throw new IllegalArgumentException( + "ACKNOWLEDGED is reserved for a completed NEW ADD_OR_RETAIN member repair"); + } switch (projectionState) { case REQUIRED -> { if (projectedMember != null || projectionInventoryRevision != null) { @@ -88,7 +97,8 @@ public enum ExecutionPhase { } public enum Status { - REQUIRED + REQUIRED, + ACKNOWLEDGED } /** 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 index 6e2c8f09ca..273636577d 100644 --- 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 @@ -3,6 +3,7 @@ import java.math.BigInteger; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; /** Canonical binding identity and separately retained runtime/issuer routing evidence. */ public record CanonicalGameplayBindingIdentity( @@ -16,7 +17,7 @@ public record CanonicalGameplayBindingIdentity( String sessionId, UUID regionId, BigInteger regionEpoch, - UUID issuerId, + String issuerId, BigInteger issuerAuthGeneration, BigInteger issuerIndexLayoutVersion, BigInteger issuerIndexPartitionCount, @@ -45,7 +46,7 @@ public record CanonicalGameplayBindingIdentity( throw new IllegalArgumentException("runtimeGameInstanceId must be positive"); } requireNonNil(regionId, "regionId"); - requireNonNil(issuerId, "issuerId"); + requireAccountIssuer(issuerId); if (!playableStateScope.equals("SHARED") && !playableStateScope.equals("ISOLATED")) { throw new IllegalArgumentException("playableStateScope must be SHARED or ISOLATED"); } @@ -82,4 +83,13 @@ private static void requireNonNil(UUID value, String name) { throw new IllegalArgumentException(name + " must not be nil"); } } + + private static void requireAccountIssuer(String issuerId) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException( + "Unsupported issuer identity; expected exact Account issuer " + + GameSessionAccountDelegationProfile.ISSUER + + "; legacy UUID issuer identities require explicit recovery"); + } + } } 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 index fa7725cce3..dbb34ba9b0 100644 --- 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 @@ -38,9 +38,18 @@ public record CanonicalGameplayBindingProvisionalCasEvidence( transition.status() == CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED ? CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL; + boolean accountIndexStillNeedsRepair = + candidate.accountIndexState() + == CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED; + // A provisional NEW transition may have a completed binding-local account-member repair. + // The repository must still prove that durable acknowledgement before it returns this model. + boolean accountIndexRepairWasAcknowledged = + initialBinding + && transition.status() == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + && candidate.accountIndexState() + == CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED; if (candidate.lifecycle() != expectedCandidateLifecycle - || candidate.accountIndexState() - != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED + || (!accountIndexStillNeedsRepair && !accountIndexRepairWasAcknowledged) || candidate.issuerIndexState() != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { throw new IllegalArgumentException("candidate is not an exact non-admissible transition row"); 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 index bae5d79dcb..7834200c9f 100644 --- 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 @@ -65,6 +65,13 @@ public byte[] bytes() { return bytes.clone(); } + /** Returns the exact UTF-8 tenant identifier encoded as the first owner segment. */ + public String tenantId() { + Cursor cursor = new Cursor(bytes); + cursor.readSegment(); + return decodeIdentifierSegment(cursor.readSegment(), "tenantId"); + } + /** Applies the canonical unsigned-big-endian SHA-256 partition function. */ public int partitionId(int partitionCount) { if (partitionCount <= 0) { @@ -122,6 +129,10 @@ private static void appendSegment(ByteArrayOutputStream output, byte[] bytes) { } private static void validateIdentifierSegment(byte[] bytes, String name) { + decodeIdentifierSegment(bytes, name); + } + + private static String decodeIdentifierSegment(byte[] bytes, String name) { try { String value = StandardCharsets.UTF_8 @@ -133,6 +144,7 @@ private static void validateIdentifierSegment(byte[] bytes, String name) { if (!Arrays.equals(bytes, encodeCanonicalIdentifier(value, name))) { throw new IllegalArgumentException(name + " does not retain its exact UTF-8 bytes"); } + return value; } catch (CharacterCodingException malformed) { throw new IllegalArgumentException(name + " must be valid UTF-8", malformed); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java new file mode 100644 index 0000000000..a03f2a7bae --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClient.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.math.BigInteger; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OperationEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Manual Game Session to Account transport for the four exact NEW-binding lease operations. */ +public final class AccountGameplayAdmissionLeaseClient + extends AbstractReloadingBlockingGrpcClient< + AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + + public AccountGameplayAdmissionLeaseClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties, "Gameplay admission lease"), + channelFactory, + AccountGameplayAdmissionLeaseClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Fixed Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes this manually composed client outside SQL transactions and synchronizations. */ + public void init() throws SSLException, IOException { + requireNoAmbientSql("Gameplay admission lease client initialization requires no ambient SQL"); + initOnce("Gameplay admission lease client is closed", "Account lease service unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountGameplayAdmissionLeaseServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(AccountGameplayAdmissionLeaseGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } + + /** Acquires the exact Account-owned lease for the supplied NEW-binding comparison values. */ + public OperationEvidence acquire( + UUID requestId, + String presentedInitialGsACompactJwt, + Candidate expectedCandidate, + Target expectedTarget, + BigInteger bindingGeneration) { + requireNoAmbientSql("Gameplay admission lease acquisition requires no ambient SQL"); + var wireRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + requestId, + presentedInitialGsACompactJwt, + expectedCandidate, + expectedTarget, + bindingGeneration); + AcquireRequest expected = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(wireRequest); + try { + OperationEvidence response = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + expected, + requireInitializedStub("Account lease service is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .acquireGameplayAdmissionLease(wireRequest)); + requireLeaseCorrelation(response.originalLeaseEvidence()); + return response; + } catch (StatusRuntimeException failure) { + throw statusFailure("Account gameplay admission lease acquisition failed", failure); + } catch (IllegalArgumentException malformed) { + throw invalidEvidence( + "Account returned invalid gameplay admission lease evidence", malformed); + } + } + + /** Finalizes one unchanged original lease against its exact Game Session decision UUID. */ + public OperationEvidence finalizeLease( + String presentedInitialGsACompactJwt, + byte[] originalLeaseEvidenceUtf8, + UUID bindingDecisionId) { + requireNoAmbientSql("Gameplay admission lease finalization requires no ambient SQL"); + var wireRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest( + presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8, bindingDecisionId); + OriginalLeaseRequest expected = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(wireRequest); + requireLeaseCorrelation(expected.originalLeaseEvidence()); + try { + OperationEvidence response = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( + expected, + requireInitializedStub("Account lease service is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .finalizeGameplayAdmissionLease(wireRequest)); + requireLeaseCorrelation(response.originalLeaseEvidence()); + return response; + } catch (StatusRuntimeException failure) { + throw statusFailure("Account gameplay admission lease finalization failed", failure); + } catch (IllegalArgumentException malformed) { + throw invalidEvidence( + "Account returned invalid gameplay admission lease evidence", malformed); + } + } + + /** Reads exact-operation recovery state without renewing or recreating the original lease. */ + public OperationEvidence read( + String presentedInitialGsACompactJwt, byte[] originalLeaseEvidenceUtf8) { + requireNoAmbientSql("Gameplay admission lease read requires no ambient SQL"); + var wireRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest( + presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8); + OriginalLeaseRequest expected = + AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(wireRequest); + requireLeaseCorrelation(expected.originalLeaseEvidence()); + try { + OperationEvidence response = + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( + expected, + requireInitializedStub("Account lease service is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readGameplayAdmissionLease(wireRequest)); + requireLeaseCorrelation(response.originalLeaseEvidence()); + return response; + } catch (StatusRuntimeException failure) { + throw statusFailure("Account gameplay admission lease read failed", failure); + } catch (IllegalArgumentException malformed) { + throw invalidEvidence( + "Account returned invalid gameplay admission lease evidence", malformed); + } + } + + /** Aborts the exact lease; a null decision UUID retains the protocol's UNKNOWN meaning. */ + public OperationEvidence abort( + String presentedInitialGsACompactJwt, + byte[] originalLeaseEvidenceUtf8, + UUID bindingDecisionId) { + requireNoAmbientSql("Gameplay admission lease abort requires no ambient SQL"); + var wireRequest = + AccountGameplayAdmissionLeaseGrpcCodec.toAbortRequest( + presentedInitialGsACompactJwt, originalLeaseEvidenceUtf8, bindingDecisionId); + OriginalLeaseRequest expected = + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(wireRequest); + requireLeaseCorrelation(expected.originalLeaseEvidence()); + try { + OperationEvidence response = + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortResponse( + expected, + requireInitializedStub("Account lease service is not initialized") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .abortGameplayAdmissionLease(wireRequest)); + requireLeaseCorrelation(response.originalLeaseEvidence()); + return response; + } catch (StatusRuntimeException failure) { + throw statusFailure("Account gameplay admission lease abort failed", failure); + } catch (IllegalArgumentException malformed) { + throw invalidEvidence( + "Account returned invalid gameplay admission lease evidence", malformed); + } + } + + private void requireLeaseCorrelation(AccountGameplayAdmissionLeaseEvidence lease) { + Objects.requireNonNull(lease, "lease"); + Object targetNamespace = lease.carrier().get("targetNamespace"); + Object callerWorkload = lease.carrier().get("callerWorkload"); + String expectedCaller = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + if (!workloadNamespace.equals(targetNamespace) || !expectedCaller.equals(callerWorkload)) { + throw new IllegalArgumentException( + "Account lease scope does not correlate to this Game Session workload"); + } + } + + private static IllegalStateException statusFailure( + String message, StatusRuntimeException failure) { + StatusRuntimeException sanitizedStatus = + Status.fromCode(failure.getStatus().getCode()).asRuntimeException(); + return new IllegalStateException(message, sanitizedStatus); + } + + private static IllegalStateException invalidEvidence( + String message, IllegalArgumentException malformed) { + return new IllegalStateException(message, malformed); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java new file mode 100644 index 0000000000..805d6cf439 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java @@ -0,0 +1,1318 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +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 net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered Game Session SQL owner for durable account-barrier acquisition intent. + * + *

This owner closes canonical NEW preparation and freezes its SQL cohort. It does not install + * tenant-local barriers, publish an installed-fence receipt, mint an admission token, or release a + * fence. + */ +final class CanonicalGameplayAccountAdmissionBarrierRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CONTROL = "game_session_canonical_account_coverage_control"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + private static final String LEGACY_DISPOSITION = + "game_session_canonical_binding_legacy_disposition"; + private static final String INTENT = "game_session_canonical_account_admission_fence_intent"; + private static final String COHORT = + "game_session_canonical_account_admission_fence_intent_cohort_row"; + private static final String BARRIER_TARGET = + "game_session_canonical_account_admission_fence_intent_barrier_target"; + private static final String TENANT_TAG_MAPPING = "game_session_canonical_tenant_gameplay_tag"; + private static final String CLOSED_RECEIPT = + "game_session_canonical_account_closed_barrier_receipt"; + private static final String CLOSED_BARRIER_SCHEMA = "gs_account_admission_barrier/v1"; + private static final String CLOSED_BARRIER_STATE = "CLOSED"; + private static final Set CLOSED_BARRIER_FIELDS = + Set.of( + "schema", + "accountId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "ownerOperationId", + "ownerFenceEpoch", + "incarnationDigest", + "state"); + private static final JsonMapper CLOSED_BARRIER_JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final Clock clock; + + CanonicalGameplayAccountAdmissionBarrierRepository(DSLContext dsl) { + this(dsl, Clock.systemUTC()); + } + + CanonicalGameplayAccountAdmissionBarrierRepository(DSLContext dsl, Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Creates or returns the exact persisted acquisition intent for this account and request. + * Inventory revision is locked before account control, matching the canonical prepare owner. + */ + CanonicalGameplayAccountAdmissionFenceIntent beginFenceIntent(UUID accountId, UUID requestId) { + requireNonNil(accountId, "accountId"); + requireNonNil(requestId, "requestId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger inventoryRevision = lockInventoryRevision(transaction); + Record control = lockExistingControl(transaction, accountId); + String controlState = control.get("state", String.class); + + Record priorIntent = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE account_id = ? AND request_id = ? FOR UPDATE", + accountId, + requestId); + if ("ACQUISITION_INTENT".equals(controlState)) { + if (priorIntent == null) { + throw conflict("A different account-fence intent already owns this account"); + } + return loadAndRequireCurrent(transaction, control, priorIntent); + } + if (priorIntent != null) { + throw conflict("The requested account-fence intent is no longer the current owner"); + } + requireNoActiveControl(control, accountId); + CanonicalGameplayLegacyMigrationDisposition legacyDisposition = + readVerifiedLegacyDisposition(transaction, inventoryRevision, true); + requireNoFutureAccountRows(transaction, accountId, inventoryRevision); + + BigInteger previousFence = readBigInteger(control, "last_operation_fence"); + BigInteger operationFence = previousFence.add(BigInteger.ONE); + UUID operationId = randomNonNilUuid(); + while (operationId.equals(accountId) || operationId.equals(requestId)) { + operationId = randomNonNilUuid(); + } + UUID plannedAccountAdmissionFence = randomNonNilUuid(); + while (plannedAccountAdmissionFence.equals(operationId) + || plannedAccountAdmissionFence.equals(requestId) + || plannedAccountAdmissionFence.equals(accountId)) { + plannedAccountAdmissionFence = randomNonNilUuid(); + } + + List cohortRows = + captureCohortRows(transaction, accountId); + requireResolvableCohortScopes(cohortRows); + List barrierTargets = + captureBarrierTargets(transaction, accountId); + requireBarrierTargetsCoverCohort(cohortRows, barrierTargets); + String cohortDigest = digestCohortRows(cohortRows); + String barrierTargetDigest = digestBarrierTargets(barrierTargets); + insertIntent( + transaction, + operationId, + requestId, + accountId, + operationFence, + plannedAccountAdmissionFence, + inventoryRevision, + legacyDisposition, + cohortRows, + barrierTargets, + cohortDigest, + barrierTargetDigest); + closeNewPreparation( + transaction, + accountId, + previousFence, + operationFence, + operationId, + plannedAccountAdmissionFence, + inventoryRevision); + Record savedIntent = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId), + "persisted account-fence intent must exist"); + Record savedControl = lockExistingControl(transaction, accountId); + return loadAndRequireCurrent(transaction, savedControl, savedIntent); + }); + } + + /** Reads and verifies the immutable persisted tuple, cohort rows, and target rows. */ + CanonicalGameplayAccountAdmissionFenceIntent readFenceIntent(UUID accountId, UUID requestId) { + requireNonNil(accountId, "accountId"); + requireNonNil(requestId, "requestId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record control = readControl(transaction, accountId); + Record intent = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE account_id = ? AND request_id = ?", + accountId, + requestId); + if (control == null || intent == null) { + throw conflict("The exact account-fence intent or its positive control row is missing"); + } + return loadAndRequireCurrent(transaction, control, intent); + }); + } + + /** Reloads the current durable intent and account control using only the operation identity. */ + CanonicalGameplayAccountAdmissionFenceIntent readCurrentFenceIntent(UUID operationId) { + requireNonNil(operationId, "operationId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record intent = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId); + if (intent == null) { + throw conflict("The exact account-fence intent operation is missing"); + } + UUID accountId = + Objects.requireNonNull(intent.get("account_id", UUID.class), "intent account id"); + Record control = readControl(transaction, accountId); + if (control == null) { + throw conflict("The account-fence intent lost its positive account-control row"); + } + return loadAndRequireCurrent(transaction, control, intent); + }); + } + + /** + * Persists one as-of CLOSED physical readback. It never advances the account intent or turns a + * stored receipt into a current-incarnation capability. + */ + StoredClosedBarrierReceipt acceptClosedBarrierReadback( + UUID expectedOperationId, + long expectedTargetOrdinal, + CanonicalGameplayAccountClosedBarrierRedisOwner.Readback readback) { + requireNonNil(expectedOperationId, "expectedOperationId"); + Objects.requireNonNull(readback, "readback"); + requireNoAmbientTransaction(); + if (expectedTargetOrdinal < 0 + || !expectedOperationId.equals(readback.operationId()) + || readback.targetOrdinal() != expectedTargetOrdinal + || !expectedOperationId.equals(readback.intent().operationId())) { + throw conflict("CLOSED readback differs from the explicitly expected operation and target"); + } + + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + + // The prepare owner takes this same inventory-clock then account-control lock order. + // The operation lookup below is only a locator; current SQL ownership is reloaded. + lockInventoryRevision(transaction); + Record identity = + transaction.fetchOne( + "SELECT account_id FROM " + INTENT + " WHERE operation_id = ?", + expectedOperationId); + if (identity == null) { + throw conflict("The exact CLOSED receipt acquisition intent is missing"); + } + UUID accountId = + Objects.requireNonNull(identity.get("account_id", UUID.class), "intent account id"); + Record control = lockExistingControl(transaction, accountId); + Record intentRow = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE operation_id = ? FOR UPDATE", + expectedOperationId); + if (intentRow == null) { + throw conflict("The exact CLOSED receipt acquisition intent is missing"); + } + CanonicalGameplayAccountAdmissionFenceIntent currentIntent = + loadAndRequireCurrent(transaction, control, intentRow); + requireSameIntentSnapshot(readback.intent(), currentIntent); + if (!expectedOperationId.equals(currentIntent.operationId()) + || !accountId.equals(currentIntent.accountId()) + || !accountId.equals(readback.accountId())) { + throw conflict("CLOSED readback differs from the exact current intent owner"); + } + + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target = + requireUniqueBarrierTarget(currentIntent, expectedTargetOrdinal); + Record persistedTarget = + transaction.fetchOne( + "SELECT account_id, tenant_id, playable_state_namespace_id, target_state FROM " + + BARRIER_TARGET + + " WHERE operation_id = ? AND target_ordinal = ? FOR SHARE", + expectedOperationId, + expectedTargetOrdinal); + if (persistedTarget == null + || !"REQUIRED".equals(persistedTarget.get("target_state", String.class)) + || !accountId.equals(persistedTarget.get("account_id", UUID.class)) + || !target.tenantId().equals(persistedTarget.get("tenant_id", UUID.class)) + || !target + .playableStateNamespaceId() + .equals(persistedTarget.get("playable_state_namespace_id", UUID.class))) { + throw conflict("CLOSED receipt target is not the exact current REQUIRED SQL target"); + } + + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + readback.assignment(); + requireReadbackAssignment( + assignment, currentIntent, target, expectedOperationId, expectedTargetOrdinal); + Record persistedTag = + transaction.fetchOne( + "SELECT tenant_id, allocation_version, tenant_gameplay_tag FROM " + + TENANT_TAG_MAPPING + + " WHERE tenant_id = ? FOR SHARE", + target.tenantId()); + if (persistedTag == null + || !target.tenantId().equals(persistedTag.get("tenant_id", UUID.class)) + || !Integer.valueOf(assignment.allocationVersion()) + .equals(persistedTag.get("allocation_version", Integer.class)) + || !assignment + .tenantGameplayTag() + .equals(persistedTag.get("tenant_gameplay_tag", String.class))) { + throw conflict("Persisted tenant mapping differs from the CLOSED readback assignment"); + } + + String redisKey = CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); + if (!redisKey.equals(readback.key())) { + throw conflict("Canonical CLOSED barrier key differs from the physical readback"); + } + + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + readback.beforeIncarnation(); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = + readback.afterIncarnation(); + requireVerifiedIncarnation(before, currentIntent, target, assignment); + requireVerifiedIncarnation(after, currentIntent, target, assignment); + if (!before.incarnationDigest().equals(after.incarnationDigest()) + || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) + || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() + || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { + throw conflict("Protected observations changed incarnation or regressed"); + } + + Map expectedFields = + expectedClosedBarrierFields( + currentIntent, target, assignment, after.incarnationDigest()); + if (!CLOSED_BARRIER_FIELDS.equals(readback.barrierFields().keySet()) + || !expectedFields.equals(readback.barrierFields()) + || !CLOSED_BARRIER_SCHEMA.equals(readback.barrierFields().get("schema")) + || !CLOSED_BARRIER_STATE.equals(readback.barrierFields().get("state"))) { + throw conflict("Physical CLOSED barrier fields differ from the current owner tuple"); + } + requireSuccessfulClosedMutation(readback.mutationOutcome()); + String fieldsDigest = digestClosedBarrierFields(expectedFields); + + // Clock is trusted owner configuration and is sampled only after all SQL guards. + long now = clock.millis(); + if (now <= 0) { + throw conflict("Trusted CLOSED receipt acceptance time must be positive"); + } + requireCurrentObservationWindow(before, now); + requireCurrentObservationWindow(after, now); + + Record existing = + transaction.fetchOne( + "SELECT * FROM " + + CLOSED_RECEIPT + + " WHERE operation_id = ? AND target_ordinal = ? FOR UPDATE", + expectedOperationId, + expectedTargetOrdinal); + if (existing != null) { + StoredClosedBarrierReceipt original = toStoredClosedBarrierReceipt(existing); + requireSameStoredBarrierIdentity( + original, + currentIntent, + target, + assignment, + redisKey, + fieldsDigest, + before.acceptedAttestationDigest(), + before.incarnationDigest()); + // A fresh protected observation has new source bytes/times. Exact retry returns the + // original immutable SQL row, including its original creation time and source digests. + return original; + } + + transaction.execute( + "INSERT INTO " + + CLOSED_RECEIPT + + " (operation_id, request_id, account_id, operation_fence," + + " planned_account_admission_fence, inventory_snapshot_revision, cohort_digest," + + " barrier_target_digest, target_ordinal, tenant_id," + + " playable_state_namespace_id, tenant_gameplay_tag, workload_namespace," + + " allocation_version, barrier_key, barrier_schema, incarnation_digest," + + " barrier_state, accepted_attestation_digest, barrier_fields_digest," + + " before_source_payload_digest, before_observation_issued_at_epoch_millis," + + " before_observation_observed_at_epoch_millis," + + " before_observation_expires_at_epoch_millis, after_source_payload_digest," + + " after_observation_issued_at_epoch_millis," + + " after_observation_observed_at_epoch_millis," + + " after_observation_expires_at_epoch_millis)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " ?, ?, ?, ?, ?, ?)", + currentIntent.operationId(), + currentIntent.requestId(), + currentIntent.accountId(), + decimal(currentIntent.operationFence()), + currentIntent.plannedAccountAdmissionFence(), + decimal(currentIntent.inventorySnapshotRevision()), + currentIntent.cohortDigest(), + currentIntent.barrierTargetDigest(), + target.ordinal(), + target.tenantId(), + target.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + assignment.workloadNamespace(), + assignment.allocationVersion(), + redisKey, + CLOSED_BARRIER_SCHEMA, + after.incarnationDigest(), + CLOSED_BARRIER_STATE, + before.acceptedAttestationDigest(), + fieldsDigest, + before.payloadDigest(), + before.issuedAtEpochMillis(), + before.observedAtEpochMillis(), + before.expiresAtEpochMillis(), + after.payloadDigest(), + after.issuedAtEpochMillis(), + after.observedAtEpochMillis(), + after.expiresAtEpochMillis()); + + Record saved = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT * FROM " + + CLOSED_RECEIPT + + " WHERE operation_id = ? AND target_ordinal = ? FOR UPDATE", + expectedOperationId, + expectedTargetOrdinal), + "inserted CLOSED receipt must exist"); + return toStoredClosedBarrierReceipt(saved); + }); + } + + private static void insertIntent( + DSLContext transaction, + UUID operationId, + UUID requestId, + UUID accountId, + BigInteger operationFence, + UUID plannedAccountAdmissionFence, + BigInteger inventoryRevision, + CanonicalGameplayLegacyMigrationDisposition legacy, + List cohortRows, + List barrierTargets, + String cohortDigest, + String barrierTargetDigest) { + transaction.execute( + "INSERT INTO " + + INTENT + + " (operation_id, request_id, account_id, operation_fence," + + " planned_account_admission_fence, inventory_snapshot_revision," + + " legacy_cohort_id, legacy_owner_operation_id, legacy_writer_fence," + + " legacy_source_snapshot_revision, legacy_canonical_inventory_revision," + + " legacy_namespace_index_readback_revision, legacy_evidence_digest, intent_state," + + " cohort_row_count, cohort_digest, barrier_target_count, barrier_target_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACQUISITION_INTENT', ?, ?, ?, ?)", + operationId, + requestId, + accountId, + decimal(operationFence), + plannedAccountAdmissionFence, + decimal(inventoryRevision), + legacy.cohortId(), + legacy.ownerOperationId(), + legacy.legacyWriterFence(), + decimal(legacy.sourceSnapshotRevision()), + decimal(legacy.canonicalInventoryRevision()), + decimal(legacy.namespaceIndexReadbackRevision()), + legacy.evidenceDigest(), + cohortRows.size(), + cohortDigest, + barrierTargets.size(), + barrierTargetDigest); + + for (var target : barrierTargets) { + transaction.execute( + "INSERT INTO " + + BARRIER_TARGET + + " (operation_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state)" + + " VALUES (?, ?, ?, ?, ?, 'REQUIRED')", + operationId, + accountId, + target.ordinal(), + target.tenantId(), + target.playableStateNamespaceId()); + } + for (var row : cohortRows) { + transaction.execute( + "INSERT INTO " + + COHORT + + " (operation_id, account_id, row_ordinal, source_kind, source_key, tenant_id," + + " playable_state_namespace_id, source_row)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + operationId, + accountId, + row.ordinal(), + row.kind().name(), + row.sourceKey(), + row.tenantId(), + row.playableStateNamespaceId(), + row.sourceRecordJson()); + } + } + + private static void closeNewPreparation( + DSLContext transaction, + UUID accountId, + BigInteger previousFence, + BigInteger operationFence, + UUID operationId, + UUID plannedAccountAdmissionFence, + BigInteger inventoryRevision) { + int updated = + transaction.execute( + "UPDATE " + + CONTROL + + " SET state = 'ACQUISITION_INTENT', last_operation_fence = ? ," + + " current_operation_id = NULL, current_fence_intent_id = ?," + + " current_operation_fence = ?, account_admission_fence = ?," + + " historical_account_admission_fence = NULL, coverage_fence = NULL," + + " inventory_snapshot_revision = ?, coverage_generation = NULL," + + " updated_at = CURRENT_TIMESTAMP" + + " WHERE account_id = ? AND state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'" + + " AND last_operation_fence = ? AND current_fence_intent_id IS NULL", + decimal(operationFence), + operationId, + decimal(operationFence), + plannedAccountAdmissionFence, + decimal(inventoryRevision), + accountId, + decimal(previousFence)); + requireOne( + updated, "Account control changed before acquisition intent could close NEW preparation"); + } + + private static List captureCohortRows( + DSLContext transaction, UUID accountId) { + var rows = new ArrayList(); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.BINDING, + "SELECT encode(i.binding_ref, 'hex') AS source_key, i.tenant_id," + + " i.playable_state_namespace_id, to_jsonb(i)::text AS source_record_json" + + " FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.account_id = ? ORDER BY encode(i.binding_ref, 'hex')", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.TRANSITION, + "SELECT t.transition_id::text AS source_key," + + " CASE WHEN t.tenant_id = i.tenant_id" + + " AND t.playable_state_namespace_id = i.playable_state_namespace_id" + + " THEN t.tenant_id ELSE NULL::uuid END AS tenant_id," + + " CASE WHEN t.tenant_id = i.tenant_id" + + " AND t.playable_state_namespace_id = i.playable_state_namespace_id" + + " THEN t.playable_state_namespace_id ELSE NULL::uuid END" + + " AS playable_state_namespace_id," + + " to_jsonb(t)::text AS source_record_json" + + " FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE i.account_id = ? ORDER BY t.transition_id", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.RESERVATION, + "SELECT r.reservation_id::text AS source_key, r.tenant_id," + + " r.playable_state_namespace_id, to_jsonb(r)::text AS source_record_json" + + " FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.account_id = ? ORDER BY r.reservation_id", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.ACCOUNT_OBLIGATION, + "SELECT o.transition_id::text || ':' || o.obligation_ordinal::text AS source_key," + + " o.tenant_id, CASE WHEN i.account_id = o.account_id AND i.tenant_id = o.tenant_id" + + " THEN i.playable_state_namespace_id ELSE NULL::uuid END" + + " AS playable_state_namespace_id, to_jsonb(o)::text AS source_record_json" + + " FROM game_session_canonical_binding_account_index_obligation o" + + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = o.binding_ref" + + " WHERE o.account_id = ? ORDER BY o.transition_id, o.obligation_ordinal", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.ISSUER_OBLIGATION, + "SELECT o.transition_id::text || ':' || encode(o.binding_ref, 'hex') AS source_key," + + " CASE WHEN o.binding_ref = t.candidate_binding_ref" + + " THEN i.tenant_id ELSE NULL::uuid END AS tenant_id," + + " CASE WHEN o.binding_ref = t.candidate_binding_ref" + + " THEN i.playable_state_namespace_id ELSE NULL::uuid END" + + " AS playable_state_namespace_id, to_jsonb(o)::text AS source_record_json" + + " FROM game_session_canonical_binding_issuer_index_obligation o" + + " JOIN game_session_canonical_binding_transition t" + + " ON t.transition_id = o.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE i.account_id = ? ORDER BY o.transition_id, encode(o.binding_ref, 'hex')", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.REGION_OBLIGATION, + "SELECT o.transition_id::text AS source_key, o.tenant_id," + + " CASE WHEN i.account_id = o.account_id AND i.tenant_id = o.tenant_id" + + " THEN i.playable_state_namespace_id ELSE NULL::uuid END" + + " AS playable_state_namespace_id, to_jsonb(o)::text AS source_record_json" + + " FROM game_session_canonical_binding_region_bridge_obligation o" + + " LEFT JOIN game_session_canonical_binding_transition t" + + " ON t.transition_id = o.transition_id" + + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE o.account_id = ? ORDER BY o.transition_id", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.MEMBER_REPAIR_CONTROL, + "SELECT c.account_id::text AS source_key, NULL::uuid AS tenant_id," + + " NULL::uuid AS playable_state_namespace_id, to_jsonb(c)::text AS source_record_json" + + " FROM game_session_canonical_account_member_repair_control c" + + " WHERE c.account_id = ?", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.MEMBER_REPAIR_OPERATION, + "SELECT o.operation_id::text AS source_key, o.tenant_id," + + " CASE WHEN i.account_id = o.account_id AND i.tenant_id = o.tenant_id" + + " THEN i.playable_state_namespace_id ELSE NULL::uuid END" + + " AS playable_state_namespace_id," + + " to_jsonb(o)::text AS source_record_json" + + " FROM game_session_canonical_account_member_repair_operation o" + + " LEFT JOIN game_session_canonical_binding_transition t" + + " ON t.transition_id = o.transition_id" + + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE o.account_id = ? ORDER BY o.operation_id", + accountId); + return List.copyOf(rows); + } + + private static void appendRows( + List rows, + DSLContext transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind kind, + String query, + UUID accountId) { + for (Record row : transaction.fetch(query, accountId)) { + rows.add( + CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( + rows.size(), + kind, + Objects.requireNonNull(row.get("source_key", String.class), "source key"), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + Objects.requireNonNull( + row.get("source_record_json", String.class), "source row JSON"))); + } + } + + private static List + captureBarrierTargets(DSLContext transaction, UUID accountId) { + List rows = + transaction.fetch( + "SELECT DISTINCT tenant_id, playable_state_namespace_id FROM (" + + " SELECT i.tenant_id, i.playable_state_namespace_id" + + " FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.account_id = ?" + + " UNION ALL SELECT r.tenant_id, r.playable_state_namespace_id" + + " FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.account_id = ?" + + " UNION ALL SELECT t.tenant_id, t.playable_state_namespace_id" + + " FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE i.account_id = ?" + + " UNION ALL SELECT o.tenant_id, CASE WHEN i.account_id = o.account_id" + + " AND i.tenant_id = o.tenant_id THEN i.playable_state_namespace_id" + + " ELSE NULL::uuid END" + + " FROM game_session_canonical_binding_account_index_obligation o" + + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = o.binding_ref" + + " WHERE o.account_id = ?" + + " UNION ALL SELECT i.tenant_id, i.playable_state_namespace_id" + + " FROM game_session_canonical_binding_issuer_index_obligation o" + + " JOIN game_session_canonical_binding_transition t" + + " ON t.transition_id = o.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE i.account_id = ?" + + " UNION ALL SELECT o.tenant_id, i.playable_state_namespace_id" + + " FROM game_session_canonical_binding_region_bridge_obligation o" + + " LEFT JOIN game_session_canonical_binding_transition t" + + " ON t.transition_id = o.transition_id" + + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE o.account_id = ?" + + " UNION ALL SELECT o.tenant_id, i.playable_state_namespace_id" + + " FROM game_session_canonical_account_member_repair_operation o" + + " LEFT JOIN game_session_canonical_binding_transition t" + + " ON t.transition_id = o.transition_id" + + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE o.account_id = ?" + + ") account_scopes" + + " ORDER BY tenant_id, playable_state_namespace_id", + accountId, + accountId, + accountId, + accountId, + accountId, + accountId, + accountId); + var targets = new ArrayList(); + for (Record row : rows) { + targets.add( + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + targets.size(), + Objects.requireNonNull(row.get("tenant_id", UUID.class), "barrier target tenant"), + Objects.requireNonNull( + row.get("playable_state_namespace_id", UUID.class), "barrier target namespace"))); + } + return List.copyOf(targets); + } + + private static void requireResolvableCohortScopes( + List cohortRows) { + for (var row : cohortRows) { + if ((row.tenantId() == null) != (row.playableStateNamespaceId() == null) + || (row.tenantId() == null + && row.kind() + != CanonicalGameplayAccountAdmissionFenceIntent.CohortKind + .MEMBER_REPAIR_CONTROL)) { + throw conflict( + "An account cohort source lacks an exact tenant/namespace barrier scope; retain the" + + " source and leave the account unfenced"); + } + } + } + + private static void requireBarrierTargetsCoverCohort( + List cohortRows, + List barrierTargets) { + Set scopes = new HashSet<>(); + for (var target : barrierTargets) { + scopes.add(target.tenantId() + "/" + target.playableStateNamespaceId()); + } + for (var row : cohortRows) { + if (row.tenantId() != null + && !scopes.contains(row.tenantId() + "/" + row.playableStateNamespaceId())) { + throw conflict( + "A frozen account source has no matching SQL-derived barrier target; retain the" + + " source and leave the account unfenced"); + } + } + } + + private static CanonicalGameplayAccountAdmissionFenceIntent loadAndRequireCurrent( + DSLContext transaction, Record control, Record intent) { + UUID operationId = + Objects.requireNonNull(intent.get("operation_id", UUID.class), "operation id"); + UUID accountId = Objects.requireNonNull(intent.get("account_id", UUID.class), "account id"); + if (!"ACQUISITION_INTENT".equals(intent.get("intent_state", String.class)) + || !"ACQUISITION_INTENT".equals(control.get("state", String.class)) + || !accountId.equals(control.get("account_id", UUID.class)) + || !operationId.equals(control.get("current_fence_intent_id", UUID.class)) + || control.get("current_operation_id", UUID.class) != null + || !readBigInteger(control, "current_operation_fence") + .equals(readBigInteger(intent, "operation_fence")) + || !readBigInteger(control, "last_operation_fence") + .equals(readBigInteger(intent, "operation_fence")) + || !Objects.equals( + control.get("account_admission_fence", UUID.class), + intent.get("planned_account_admission_fence", UUID.class)) + || control.get("historical_account_admission_fence", UUID.class) != null + || control.get("coverage_fence", UUID.class) != null + || control.get("coverage_generation") != null + || !readBigInteger(control, "inventory_snapshot_revision") + .equals(readBigInteger(intent, "inventory_snapshot_revision"))) { + throw conflict("Persisted acquisition intent is not the exact current account-control owner"); + } + CanonicalGameplayLegacyMigrationDisposition legacy = readPersistedLegacyDisposition(intent); + CanonicalGameplayLegacyMigrationDisposition currentLegacy = + readVerifiedLegacyDisposition( + transaction, readBigInteger(intent, "inventory_snapshot_revision"), false); + if (!legacy.equals(currentLegacy)) { + throw conflict("The verified legacy migration disposition changed after intent capture"); + } + List cohortRows = + readCohortRows(transaction, operationId); + List barrierTargets = + readBarrierTargets(transaction, operationId); + String cohortDigest = digestCohortRows(cohortRows); + String targetDigest = digestBarrierTargets(barrierTargets); + if (cohortRows.size() != readLong(intent, "cohort_row_count") + || !cohortDigest.equals(intent.get("cohort_digest", String.class)) + || barrierTargets.size() != readLong(intent, "barrier_target_count") + || !targetDigest.equals(intent.get("barrier_target_digest", String.class))) { + throw conflict("Immutable account-fence intent cohort or barrier target changed on readback"); + } + return new CanonicalGameplayAccountAdmissionFenceIntent( + operationId, + intent.get("request_id", UUID.class), + accountId, + readBigInteger(intent, "operation_fence"), + intent.get("planned_account_admission_fence", UUID.class), + readBigInteger(intent, "inventory_snapshot_revision"), + legacy, + CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT, + cohortRows, + barrierTargets, + cohortDigest, + targetDigest); + } + + private static List readCohortRows( + DSLContext transaction, UUID operationId) { + return transaction + .fetch( + "SELECT row_ordinal, source_kind, source_key, tenant_id," + + " playable_state_namespace_id, source_row::text AS source_record_json FROM " + + COHORT + + " WHERE operation_id = ? ORDER BY row_ordinal", + operationId) + .map( + row -> { + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind kind; + try { + kind = + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.valueOf( + row.get("source_kind", String.class)); + } catch (RuntimeException malformed) { + throw conflict("Persisted account-fence cohort contains an unknown source kind"); + } + return CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( + readLong(row, "row_ordinal"), + kind, + row.get("source_key", String.class), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("source_record_json", String.class)); + }); + } + + private static List + readBarrierTargets(DSLContext transaction, UUID operationId) { + return transaction + .fetch( + "SELECT target_ordinal, tenant_id, playable_state_namespace_id FROM " + + BARRIER_TARGET + + " WHERE operation_id = ? ORDER BY target_ordinal", + operationId) + .map( + row -> + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + readLong(row, "target_ordinal"), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class))); + } + + private static CanonicalGameplayLegacyMigrationDisposition readVerifiedLegacyDisposition( + DSLContext transaction, BigInteger inventoryRevision, 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( + "Account-fence intent requires the exact VERIFIED legacy-index migration disposition"); + } + 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("Verified legacy migration disposition is incomplete or invalid"); + } + if (disposition.canonicalInventoryRevision().compareTo(inventoryRevision) > 0) { + throw conflict("Verified legacy disposition is newer than the account snapshot revision"); + } + return disposition; + } + + private static CanonicalGameplayLegacyMigrationDisposition readPersistedLegacyDisposition( + Record row) { + try { + return new CanonicalGameplayLegacyMigrationDisposition( + row.get("legacy_cohort_id", UUID.class), + row.get("legacy_owner_operation_id", UUID.class), + row.get("legacy_writer_fence", UUID.class), + readBigInteger(row, "legacy_source_snapshot_revision"), + readBigInteger(row, "legacy_canonical_inventory_revision"), + readBigInteger(row, "legacy_namespace_index_readback_revision"), + row.get("legacy_evidence_digest", String.class)); + } catch (RuntimeException malformed) { + throw conflict("Persisted account-fence intent has malformed legacy evidence"); + } + } + + private static void requireNoFutureAccountRows( + DSLContext transaction, UUID accountId, BigInteger revision) { + Record future = + transaction.fetchOne( + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE account_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE i.account_id = ? AND t.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" + + " WHERE account_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation" + + " WHERE account_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation o" + + " JOIN game_session_canonical_binding_transition t" + + " ON t.transition_id = o.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref" + + " WHERE i.account_id = ? AND o.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation" + + " WHERE account_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_account_member_repair_operation" + + " WHERE account_id = ? AND (original_inventory_revision > ?" + + " OR completed_inventory_revision > ?)) AS has_future_revision", + accountId, + decimal(revision), + accountId, + decimal(revision), + accountId, + decimal(revision), + accountId, + decimal(revision), + accountId, + decimal(revision), + accountId, + decimal(revision), + accountId, + decimal(revision), + decimal(revision)); + if (future == null || Boolean.TRUE.equals(future.get("has_future_revision", Boolean.class))) { + throw conflict( + "Account rows beyond the locked inventory clock cannot be omitted from intent"); + } + } + + private static Record lockExistingControl(DSLContext transaction, UUID accountId) { + Record control = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); + if (control == null) { + throw conflict("Positive account-control row is missing; absence cannot start fence intent"); + } + return control; + } + + private static Record readControl(DSLContext transaction, UUID accountId) { + return transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE account_id = ?", accountId); + } + + private static void requireNoActiveControl(Record control, UUID accountId) { + if (!"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(control.get("state", String.class)) + || !accountId.equals(control.get("account_id", UUID.class)) + || control.get("current_operation_id", UUID.class) != null + || control.get("current_fence_intent_id", UUID.class) != null + || control.get("current_operation_fence") != null + || control.get("account_admission_fence", UUID.class) != null + || control.get("historical_account_admission_fence", UUID.class) != null + || control.get("coverage_fence", UUID.class) != null + || control.get("inventory_snapshot_revision") != null + || control.get("coverage_generation") != null) { + throw conflict("Only positively read NO_ACTIVE account control may begin fence intent"); + } + } + + private static BigInteger lockInventoryRevision(DSLContext transaction) { + Record row = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"), + "inventory revision clock row must exist"); + BigInteger revision = readBigInteger(row, "inventory_revision"); + if (revision.signum() <= 0) { + throw conflict("Verified account intent requires a positive inventory snapshot revision"); + } + return revision; + } + + private static BigInteger readBigInteger(Record row, String name) { + BigDecimal value = row.get(name, BigDecimal.class); + if (value == null) { + throw conflict("Persisted account-fence intent field is missing: " + name); + } + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted account-fence intent field is not an integer: " + name); + } + } + + private static long readLong(Record row, String name) { + BigDecimal value = row.get(name, BigDecimal.class); + if (value != null) { + try { + return value.longValueExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted account-fence intent field is out of range: " + name); + } + } + Long longValue = row.get(name, Long.class); + if (longValue == null) { + throw conflict("Persisted account-fence intent field is missing: " + name); + } + return longValue; + } + + private static String digestCohortRows( + List rows) { + MessageDigest digest = sha256Digest(); + for (var row : rows) { + updateDigest(digest, Long.toString(row.ordinal())); + updateDigest(digest, row.kind().name()); + updateDigest(digest, row.sourceKey()); + updateDigest(digest, row.tenantId() == null ? null : row.tenantId().toString()); + updateDigest( + digest, + row.playableStateNamespaceId() == null + ? null + : row.playableStateNamespaceId().toString()); + updateDigest(digest, row.sourceRecordJson()); + } + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static String digestBarrierTargets( + List targets) { + MessageDigest digest = sha256Digest(); + for (var target : targets) { + updateDigest(digest, Long.toString(target.ordinal())); + updateDigest(digest, target.tenantId().toString()); + updateDigest(digest, target.playableStateNamespaceId().toString()); + } + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static void updateDigest(MessageDigest digest, String value) { + if (value == null) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(-1).array()); + return; + } + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + + private static MessageDigest sha256Digest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static BigDecimal decimal(BigInteger value) { + return new BigDecimal(value); + } + + private static UUID randomNonNilUuid() { + UUID value = UUID.randomUUID(); + if (NIL_UUID.equals(value)) { + throw new IllegalStateException("UUID generator returned nil account-fence identity"); + } + return value; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account-fence intent owner must not run inside an ambient transaction"); + } + } + + private static void requireOne(int updated, String message) { + if (updated != 1) { + throw conflict(message); + } + } + + private static CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget + requireUniqueBarrierTarget( + CanonicalGameplayAccountAdmissionFenceIntent intent, long ordinal) { + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget match = null; + for (var target : intent.barrierTargets()) { + if (target.ordinal() == ordinal) { + if (match != null) throw conflict("Intent target ordinal is duplicated"); + match = target; + } + } + if (match == null) throw conflict("Exact frozen CLOSED barrier target is missing"); + return match; + } + + private static void requireSameIntentSnapshot( + CanonicalGameplayAccountAdmissionFenceIntent expected, + CanonicalGameplayAccountAdmissionFenceIntent current) { + if (!expected.operationId().equals(current.operationId()) + || !expected.requestId().equals(current.requestId()) + || !expected.accountId().equals(current.accountId()) + || !expected.operationFence().equals(current.operationFence()) + || !expected.plannedAccountAdmissionFence().equals(current.plannedAccountAdmissionFence()) + || !expected.inventorySnapshotRevision().equals(current.inventorySnapshotRevision()) + || !expected.legacyMigrationDisposition().equals(current.legacyMigrationDisposition()) + || expected.state() != current.state() + || !expected.cohortDigest().equals(current.cohortDigest()) + || !expected.barrierTargetDigest().equals(current.barrierTargetDigest()) + || expected.cohortRows().size() != current.cohortRows().size() + || expected.barrierTargets().size() != current.barrierTargets().size()) { + throw conflict("Redis readback intent differs from the complete current SQL intent"); + } + for (int index = 0; index < expected.cohortRows().size(); index++) { + var left = expected.cohortRows().get(index); + var right = current.cohortRows().get(index); + if (left.ordinal() != right.ordinal() + || left.kind() != right.kind() + || !left.sourceKey().equals(right.sourceKey()) + || !Objects.equals(left.tenantId(), right.tenantId()) + || !Objects.equals(left.playableStateNamespaceId(), right.playableStateNamespaceId()) + || !left.sourceRecordJson().equals(right.sourceRecordJson())) { + throw conflict("Redis readback intent differs from the immutable SQL cohort"); + } + } + for (int index = 0; index < expected.barrierTargets().size(); index++) { + var left = expected.barrierTargets().get(index); + var right = current.barrierTargets().get(index); + if (left.ordinal() != right.ordinal() + || !left.tenantId().equals(right.tenantId()) + || !left.playableStateNamespaceId().equals(right.playableStateNamespaceId())) { + throw conflict("Redis readback intent differs from the immutable SQL target set"); + } + } + } + + private static void requireReadbackAssignment( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayAccountAdmissionFenceIntent intent, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target, + UUID operationId, + long ordinal) { + if (assignment.isBindingTransition() + || !operationId.equals(assignment.admissionFenceIntentOperationId()) + || !Long.valueOf(ordinal).equals(assignment.barrierTargetOrdinal()) + || !intent.accountId().equals(assignment.accountId()) + || !target.tenantId().equals(assignment.tenantId()) + || !target.playableStateNamespaceId().equals(assignment.playableStateNamespaceId()) + || assignment.allocationVersion() <= 0 + || assignment.workloadNamespace().isBlank()) { + throw conflict("Redis assignment differs from the exact frozen SQL target"); + } + } + + private static void requireVerifiedIncarnation( + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation value, + CanonicalGameplayAccountAdmissionFenceIntent intent, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { + if (!intent.operationId().equals(value.operationId()) + || value.targetOrdinal() != target.ordinal() + || !intent.accountId().equals(value.accountId()) + || !target.tenantId().equals(value.tenantId()) + || !target.playableStateNamespaceId().equals(value.playableStateNamespaceId()) + || !intent.plannedAccountAdmissionFence().equals(value.plannedAccountAdmissionFence()) + || !intent.operationFence().toString().equals(value.operationFence()) + || !intent.cohortDigest().equals(value.cohortDigest()) + || !intent.barrierTargetDigest().equals(value.barrierTargetDigest()) + || !assignment.tenantGameplayTag().equals(value.tenantGameplayTag()) + || !canonicalSha256(value.acceptedAttestationDigest()) + || !canonicalSha256(value.payloadDigest()) + || !canonicalSha256(value.incarnationDigest()) + || value.issuedAtEpochMillis() <= 0 + || value.observedAtEpochMillis() < value.issuedAtEpochMillis() + || value.expiresAtEpochMillis() <= value.observedAtEpochMillis()) { + throw conflict("Protected incarnation proof differs from the complete current target tuple"); + } + } + + private static void requireCurrentObservationWindow( + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation value, long now) { + if (now < value.issuedAtEpochMillis() || now < value.observedAtEpochMillis()) { + throw conflict("Trusted acceptance clock precedes the protected observation"); + } + if (now >= value.expiresAtEpochMillis()) { + throw conflict("Protected incarnation observation is expired"); + } + } + + private static Map expectedClosedBarrierFields( + CanonicalGameplayAccountAdmissionFenceIntent intent, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + String incarnationDigest) { + return Map.of( + "schema", CLOSED_BARRIER_SCHEMA, + "accountId", intent.accountId().toString(), + "tenantId", target.tenantId().toString(), + "playableStateNamespaceId", target.playableStateNamespaceId().toString(), + "tenantGameplayTag", assignment.tenantGameplayTag(), + "ownerOperationId", intent.operationId().toString(), + "ownerFenceEpoch", intent.operationFence().toString(), + "incarnationDigest", incarnationDigest, + "state", CLOSED_BARRIER_STATE); + } + + private static void requireSuccessfulClosedMutation( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome outcome) { + if (outcome != CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.CREATED_CLOSED + && outcome + != CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.EXACT_CLOSED_REPLAY + && outcome + != CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.ADVANCED_TO_CLOSED) { + throw conflict("Redis owner did not report a successful CLOSED write and readback"); + } + } + + private static String digestClosedBarrierFields(Map fields) { + try { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(CLOSED_BARRIER_JSON.writeValueAsString(fields)); + return "sha256:" + HexFormat.of().formatHex(sha256Digest().digest(canonical)); + } catch (IOException invalid) { + throw new IllegalStateException("Could not canonicalize CLOSED barrier fields", invalid); + } + } + + private static boolean canonicalSha256(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static StoredClosedBarrierReceipt toStoredClosedBarrierReceipt(Record row) { + return new StoredClosedBarrierReceipt( + row.get("operation_id", UUID.class), + row.get("request_id", UUID.class), + row.get("account_id", UUID.class), + readBigInteger(row, "operation_fence"), + row.get("planned_account_admission_fence", UUID.class), + readBigInteger(row, "inventory_snapshot_revision"), + row.get("cohort_digest", String.class), + row.get("barrier_target_digest", String.class), + readLong(row, "target_ordinal"), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("tenant_gameplay_tag", String.class), + row.get("workload_namespace", String.class), + Objects.requireNonNull( + row.get("allocation_version", Integer.class), "persisted allocation version"), + row.get("barrier_key", String.class), + row.get("barrier_schema", String.class), + row.get("incarnation_digest", String.class), + row.get("barrier_state", String.class), + row.get("accepted_attestation_digest", String.class), + row.get("barrier_fields_digest", String.class), + row.get("before_source_payload_digest", String.class), + readLong(row, "before_observation_issued_at_epoch_millis"), + readLong(row, "before_observation_observed_at_epoch_millis"), + readLong(row, "before_observation_expires_at_epoch_millis"), + row.get("after_source_payload_digest", String.class), + readLong(row, "after_observation_issued_at_epoch_millis"), + readLong(row, "after_observation_observed_at_epoch_millis"), + readLong(row, "after_observation_expires_at_epoch_millis"), + row.get("created_at", OffsetDateTime.class)); + } + + private static void requireSameStoredBarrierIdentity( + StoredClosedBarrierReceipt stored, + CanonicalGameplayAccountAdmissionFenceIntent intent, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + String barrierKey, + String fieldsDigest, + String acceptedAttestationDigest, + String incarnationDigest) { + if (!stored.operationId().equals(intent.operationId()) + || !stored.requestId().equals(intent.requestId()) + || !stored.accountId().equals(intent.accountId()) + || !stored.operationFence().equals(intent.operationFence()) + || !stored.plannedAccountAdmissionFence().equals(intent.plannedAccountAdmissionFence()) + || !stored.inventorySnapshotRevision().equals(intent.inventorySnapshotRevision()) + || !stored.cohortDigest().equals(intent.cohortDigest()) + || !stored.barrierTargetDigest().equals(intent.barrierTargetDigest()) + || stored.targetOrdinal() != target.ordinal() + || !stored.tenantId().equals(target.tenantId()) + || !stored.playableStateNamespaceId().equals(target.playableStateNamespaceId()) + || !stored.tenantGameplayTag().equals(assignment.tenantGameplayTag()) + || !stored.workloadNamespace().equals(assignment.workloadNamespace()) + || stored.allocationVersion() != assignment.allocationVersion() + || !stored.barrierKey().equals(barrierKey) + || !stored.barrierSchema().equals(CLOSED_BARRIER_SCHEMA) + || !stored.incarnationDigest().equals(incarnationDigest) + || !stored.barrierState().equals(CLOSED_BARRIER_STATE) + || !stored.acceptedAttestationDigest().equals(acceptedAttestationDigest) + || !stored.barrierFieldsDigest().equals(fieldsDigest)) { + throw conflict( + "Existing CLOSED receipt belongs to a different immutable owner or incarnation"); + } + } + + 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/CanonicalGameplayAccountAdmissionFenceIntent.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java new file mode 100644 index 0000000000..8d805921c8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java @@ -0,0 +1,222 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; + +/** + * Immutable Game Session SQL read model for an uninstalled account-wide fence acquisition intent. + */ +public final class CanonicalGameplayAccountAdmissionFenceIntent { + public enum State { + ACQUISITION_INTENT + } + + public enum CohortKind { + BINDING, + TRANSITION, + RESERVATION, + ACCOUNT_OBLIGATION, + ISSUER_OBLIGATION, + REGION_OBLIGATION, + MEMBER_REPAIR_CONTROL, + MEMBER_REPAIR_OPERATION + } + + private final UUID operationId; + private final UUID requestId; + private final UUID accountId; + private final BigInteger operationFence; + private final UUID plannedAccountAdmissionFence; + private final BigInteger inventorySnapshotRevision; + private final CanonicalGameplayLegacyMigrationDisposition legacyMigrationDisposition; + private final State state; + private final List cohortRows; + private final List barrierTargets; + private final String cohortDigest; + private final String barrierTargetDigest; + + CanonicalGameplayAccountAdmissionFenceIntent( + UUID operationId, + UUID requestId, + UUID accountId, + BigInteger operationFence, + UUID plannedAccountAdmissionFence, + BigInteger inventorySnapshotRevision, + CanonicalGameplayLegacyMigrationDisposition legacyMigrationDisposition, + State state, + List cohortRows, + List barrierTargets, + String cohortDigest, + String barrierTargetDigest) { + this.operationId = Objects.requireNonNull(operationId, "operationId"); + this.requestId = Objects.requireNonNull(requestId, "requestId"); + this.accountId = Objects.requireNonNull(accountId, "accountId"); + this.operationFence = Objects.requireNonNull(operationFence, "operationFence"); + this.plannedAccountAdmissionFence = + Objects.requireNonNull(plannedAccountAdmissionFence, "plannedAccountAdmissionFence"); + this.inventorySnapshotRevision = + Objects.requireNonNull(inventorySnapshotRevision, "inventorySnapshotRevision"); + this.legacyMigrationDisposition = + Objects.requireNonNull(legacyMigrationDisposition, "legacyMigrationDisposition"); + this.state = Objects.requireNonNull(state, "state"); + this.cohortRows = List.copyOf(Objects.requireNonNull(cohortRows, "cohortRows")); + this.barrierTargets = List.copyOf(Objects.requireNonNull(barrierTargets, "barrierTargets")); + this.cohortDigest = requireDigest(cohortDigest, "cohortDigest"); + this.barrierTargetDigest = requireDigest(barrierTargetDigest, "barrierTargetDigest"); + if (this.cohortRows.stream().anyMatch(Objects::isNull) + || this.barrierTargets.stream().anyMatch(Objects::isNull)) { + throw new IllegalArgumentException("Persisted intent snapshots must not contain null rows"); + } + if (operationFence.signum() <= 0 || inventorySnapshotRevision.signum() <= 0) { + throw new IllegalArgumentException("Intent fence and snapshot revision must be positive"); + } + } + + public UUID operationId() { + return operationId; + } + + public UUID requestId() { + return requestId; + } + + public UUID accountId() { + return accountId; + } + + public BigInteger operationFence() { + return operationFence; + } + + /** Identity reserved for the future CLOSED barrier; this does not prove that it is installed. */ + public UUID plannedAccountAdmissionFence() { + return plannedAccountAdmissionFence; + } + + public BigInteger inventorySnapshotRevision() { + return inventorySnapshotRevision; + } + + public CanonicalGameplayLegacyMigrationDisposition legacyMigrationDisposition() { + return legacyMigrationDisposition; + } + + public State state() { + return state; + } + + public List cohortRows() { + return cohortRows; + } + + public List barrierTargets() { + return barrierTargets; + } + + public String cohortDigest() { + return cohortDigest; + } + + public String barrierTargetDigest() { + return barrierTargetDigest; + } + + public static final class CohortRow { + private final long ordinal; + private final CohortKind kind; + private final String sourceKey; + private final UUID tenantId; + private final UUID playableStateNamespaceId; + private final String sourceRecordJson; + + private CohortRow( + long ordinal, + CohortKind kind, + String sourceKey, + UUID tenantId, + UUID playableStateNamespaceId, + String sourceRecordJson) { + this.ordinal = ordinal; + this.kind = Objects.requireNonNull(kind, "kind"); + this.sourceKey = Objects.requireNonNull(sourceKey, "sourceKey"); + this.tenantId = tenantId; + this.playableStateNamespaceId = playableStateNamespaceId; + this.sourceRecordJson = Objects.requireNonNull(sourceRecordJson, "sourceRecordJson"); + } + + public long ordinal() { + return ordinal; + } + + public CohortKind kind() { + return kind; + } + + public String sourceKey() { + return sourceKey; + } + + public UUID tenantId() { + return tenantId; + } + + public UUID playableStateNamespaceId() { + return playableStateNamespaceId; + } + + /** Exact owner-captured source row serialization, retained for bounded later reconciliation. */ + public String sourceRecordJson() { + return sourceRecordJson; + } + } + + public static final class BarrierTarget { + private final long ordinal; + private final UUID tenantId; + private final UUID playableStateNamespaceId; + + private BarrierTarget(long ordinal, UUID tenantId, UUID playableStateNamespaceId) { + this.ordinal = ordinal; + this.tenantId = Objects.requireNonNull(tenantId, "tenantId"); + this.playableStateNamespaceId = + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + } + + public long ordinal() { + return ordinal; + } + + public UUID tenantId() { + return tenantId; + } + + public UUID playableStateNamespaceId() { + return playableStateNamespaceId; + } + } + + static CohortRow cohortRow( + long ordinal, + CohortKind kind, + String sourceKey, + UUID tenantId, + UUID playableStateNamespaceId, + String sourceRecordJson) { + return new CohortRow( + ordinal, kind, sourceKey, tenantId, playableStateNamespaceId, sourceRecordJson); + } + + static BarrierTarget barrierTarget(long ordinal, UUID tenantId, UUID playableStateNamespaceId) { + return new BarrierTarget(ordinal, tenantId, playableStateNamespaceId); + } + + private static String 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"); + } + return value; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwner.java new file mode 100644 index 0000000000..fbc6afd741 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwner.java @@ -0,0 +1,568 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.util.Arrays; +import java.util.HexFormat; +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 java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountClosedBarrierRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Game Session owner for one tenant-local CLOSED account-admission barrier. + * + *

This owner performs only a guarded one-key CLOSED write and physical readback. It does not + * publish an SQL installation receipt, open admission, perform final binding CAS, or establish + * account-wide coverage. Every Redis phase is outside SQL transactions. + */ +final class CanonicalGameplayAccountClosedBarrierRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:account-admission:"; + private static final String SCHEMA = "gs_account_admission_barrier/v1"; + private static final String CLOSED = "CLOSED"; + private static final int MAX_SCRIPT_BYTES = 32 * 1024; + private static final int MAX_DECIMAL_BYTES = 256; + private static final long REDIS_COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List FIELDS = + List.of( + "schema", + "accountId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "ownerOperationId", + "ownerFenceEpoch", + "incarnationDigest", + "state"); + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "accountAdmissionBarrier", + KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("schema"), + new RedisScriptDescriptor.ArgumentSpec("accountId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("ownerOperationId"), + new RedisScriptDescriptor.ArgumentSpec("ownerFenceEpoch"), + new RedisScriptDescriptor.ArgumentSpec("incarnationDigest"), + new RedisScriptDescriptor.ArgumentSpec("state")); + private static final List EXPECTED_OUTCOMES = + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "CLOSED_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "CLOSED_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "CLOSED_ADVANCED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "TYPE_TTL_OR_FIELDS_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGUMENTS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "STALE_OR_CONFLICTING_OWNER", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + private static final Set EXPECTED_FIELD_SET = Set.copyOf(FIELDS); + + enum MutationOutcome { + CREATED_CLOSED, + EXACT_CLOSED_REPLAY, + ADVANCED_TO_CLOSED + } + + private final CanonicalGameplayAccountAdmissionBarrierRepository intentRepository; + private final CanonicalGameplayTenantGameplayTagRepository tenantTagRepository; + private final CanonicalGameplayProtectedIncarnationReceiver incarnationReceiver; + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final Clock clock; + + CanonicalGameplayAccountClosedBarrierRedisOwner( + CanonicalGameplayAccountAdmissionBarrierRepository intentRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, + CanonicalGameplayProtectedIncarnationReceiver incarnationReceiver, + RedisClient redisClient, + RedisScriptCatalog catalog, + Clock clock) { + this.intentRepository = Objects.requireNonNull(intentRepository, "intentRepository"); + this.tenantTagRepository = Objects.requireNonNull(tenantTagRepository, "tenantTagRepository"); + this.incarnationReceiver = Objects.requireNonNull(incarnationReceiver, "incarnationReceiver"); + this.redisClient = Objects.requireNonNull(redisClient, "configured Redis client"); + this.catalog = Objects.requireNonNull(catalog, "installed Redis script catalog"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Installs or exactly retries one CLOSED barrier, then reads it back from a distinct Redis + * connection and obtains fresh protected current-incarnation evidence. The result is only local + * physical evidence; a SQL owner must separately accept a guarded per-target receipt. + */ + Readback installAndRead(UUID operationId, long targetOrdinal) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + if (targetOrdinal < 0) throw unavailable(); + + try { + BarrierContext before = loadCurrentContext(operationId, targetOrdinal); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation = + incarnationReceiver.observeForFenceTarget(operationId, targetOrdinal); + requireIncarnationMatches(before, beforeIncarnation); + requireUnexpired(beforeIncarnation); + + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] source = source(descriptor); + byte[] key = ascii(before.key()); + Map expectedFields = + expectedFields(before, beforeIncarnation.incarnationDigest()); + byte[][] arguments = arguments(before, beforeIncarnation.incarnationDigest()); + long mutationReply = executeMutation(source, key, arguments); + MutationOutcome outcome = mutationOutcome(mutationReply); + + Map actualFields = readPhysicalBarrier(key, expectedFields); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation afterIncarnation = + incarnationReceiver.observeForFenceTarget(operationId, targetOrdinal); + requireIncarnationMatches(before, afterIncarnation); + if (!beforeIncarnation.incarnationDigest().equals(afterIncarnation.incarnationDigest())) { + throw unavailable(); + } + requireUnexpired(beforeIncarnation); + requireUnexpired(afterIncarnation); + + BarrierContext after = loadCurrentContext(operationId, targetOrdinal); + if (!before.sameOwnerContext(after)) throw unavailable(); + if (!actualFields.equals(expectedFields)) throw unavailable(); + requireNoAmbientTransaction(); + return new Readback(before, actualFields, outcome, beforeIncarnation, afterIncarnation); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("CLOSED account barrier is unavailable")) { + throw state; + } + throw unavailable(failure); + } + } + + private BarrierContext loadCurrentContext(UUID operationId, long targetOrdinal) { + requireNoAmbientTransaction(); + CanonicalGameplayAccountAdmissionFenceIntent intent = + intentRepository.readCurrentFenceIntent(operationId); + if (!operationId.equals(intent.operationId()) + || intent.state() + != CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT) { + throw unavailable(); + } + List targets = + intent.barrierTargets().stream() + .filter(target -> target.ordinal() == targetOrdinal) + .toList(); + if (targets.size() != 1) throw unavailable(); + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target = targets.get(0); + + requireNoAmbientTransaction(); + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + tenantTagRepository.assignmentForBarrierTarget(operationId, targetOrdinal); + if (assignment.isBindingTransition() + || !operationId.equals(assignment.admissionFenceIntentOperationId()) + || !Long.valueOf(targetOrdinal).equals(assignment.barrierTargetOrdinal()) + || !intent.accountId().equals(assignment.accountId()) + || !target.tenantId().equals(assignment.tenantId()) + || !target.playableStateNamespaceId().equals(assignment.playableStateNamespaceId())) { + throw unavailable(); + } + String key = CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); + if (!key.startsWith(KEY_PREFIX)) throw unavailable(); + if (!canonicalPositiveDecimal(intent.operationFence().toString()) + || !canonicalPositiveDecimal(intent.inventorySnapshotRevision().toString())) { + throw unavailable(); + } + return new BarrierContext(intent, targetOrdinal, assignment, key); + } + + private static Map expectedFields( + BarrierContext context, String incarnationDigest) { + if (!canonicalDigest(incarnationDigest)) throw unavailable(); + CanonicalGameplayAccountAdmissionFenceIntent intent = context.intent(); + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = context.assignment(); + Map fields = new LinkedHashMap<>(); + fields.put("schema", SCHEMA); + fields.put("accountId", intent.accountId().toString()); + fields.put("tenantId", assignment.tenantId().toString()); + fields.put("playableStateNamespaceId", assignment.playableStateNamespaceId().toString()); + fields.put("tenantGameplayTag", assignment.tenantGameplayTag()); + fields.put("ownerOperationId", intent.operationId().toString()); + fields.put("ownerFenceEpoch", intent.operationFence().toString()); + fields.put("incarnationDigest", incarnationDigest); + fields.put("state", CLOSED); + return Map.copyOf(fields); + } + + private static void requireIncarnationMatches( + BarrierContext context, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation incarnation) { + Objects.requireNonNull(incarnation, "verified current-incarnation evidence"); + CanonicalGameplayAccountAdmissionFenceIntent intent = context.intent(); + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = context.assignment(); + if (!intent.operationId().equals(incarnation.operationId()) + || incarnation.targetOrdinal() != context.targetOrdinal() + || !intent.accountId().equals(incarnation.accountId()) + || !assignment.tenantId().equals(incarnation.tenantId()) + || !assignment.playableStateNamespaceId().equals(incarnation.playableStateNamespaceId()) + || !intent.plannedAccountAdmissionFence().equals(incarnation.plannedAccountAdmissionFence()) + || !intent.operationFence().toString().equals(incarnation.operationFence()) + || !intent.cohortDigest().equals(incarnation.cohortDigest()) + || !intent.barrierTargetDigest().equals(incarnation.barrierTargetDigest()) + || !assignment.tenantGameplayTag().equals(incarnation.tenantGameplayTag()) + || !canonicalDigest(incarnation.incarnationDigest())) { + throw unavailable(); + } + } + + private long executeMutation(byte[] source, byte[] key, byte[][] arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String loadedSha = await(commands.scriptLoad(source)); + if (!digest("SHA-1", source).equals(loadedSha)) throw unavailable(); + RedisFuture mutation = + commands.evalsha(loadedSha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments); + Long reply = await(mutation); + if (reply == null || reply < 0L) throw unavailable(); + return reply; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private Map readPhysicalBarrier(byte[] key, Map expected) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key))) + || !Long.valueOf(FIELDS.size()).equals(await(commands.hlen(key)))) { + throw unavailable(); + } + Map physical = await(commands.hgetall(key)); + if (physical == null || physical.size() != FIELDS.size()) throw unavailable(); + Map actual = new LinkedHashMap<>(); + for (Map.Entry entry : physical.entrySet()) { + String field = strictAscii(entry.getKey()); + String value = strictAscii(entry.getValue()); + if (!EXPECTED_FIELD_SET.contains(field) || actual.putIfAbsent(field, value) != null) { + throw unavailable(); + } + } + if (!EXPECTED_FIELD_SET.equals(actual.keySet()) || !expected.equals(actual)) { + throw unavailable(); + } + return Map.copyOf(actual); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[][] arguments(BarrierContext context, String incarnationDigest) { + Map fields = expectedFields(context, incarnationDigest); + return new byte[][] { + ascii(fields.get("schema")), + ascii(fields.get("accountId")), + ascii(fields.get("tenantId")), + ascii(fields.get("playableStateNamespaceId")), + ascii(fields.get("tenantGameplayTag")), + ascii(fields.get("ownerOperationId")), + ascii(fields.get("ownerFenceEpoch")), + ascii(fields.get("incarnationDigest")), + ascii(fields.get("state")) + }; + } + + private static MutationOutcome mutationOutcome(long reply) { + if (reply == 1L) return MutationOutcome.CREATED_CLOSED; + if (reply == 2L) return MutationOutcome.EXACT_CLOSED_REPLAY; + if (reply == 3L) return MutationOutcome.ADVANCED_TO_CLOSED; + throw unavailable(); + } + + private void requireUnexpired( + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation incarnation) { + long now = clock.millis(); + if (now < incarnation.issuedAtEpochMillis() || now >= incarnation.expiresAtEpochMillis()) { + throw unavailable(); + } + } + + private RedisScriptDescriptor requireDescriptor() { + try { + RedisScriptDescriptor descriptor = + catalog.require(CanonicalGameplayAccountClosedBarrierRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayAccountClosedBarrierRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayAccountClosedBarrierRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none"))) + || descriptor.legacyPayloadShape() != null) { + throw unavailable(); + } + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] source(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayAccountClosedBarrierRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) { + throw unavailable(); + } + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + return connection.async(); + } + + private static T await(RedisFuture future) { + try { + return future.get(REDIS_COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable(failure); + } + } + + private static void requirePrincipal(String actual) { + if (!PRINCIPAL.equals(actual)) throw unavailable(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable(); + } + } + + private static String strictAscii(byte[] value) { + if (value == null) throw unavailable(); + String decoded = new String(value, StandardCharsets.US_ASCII); + if (!Arrays.equals(value, ascii(decoded))) throw unavailable(); + return decoded; + } + + private static boolean canonicalPositiveDecimal(String value) { + if (value == null || value.isEmpty() || value.length() > MAX_DECIMAL_BYTES) return false; + if (value.charAt(0) < '1' || value.charAt(0) > '9') return false; + for (int index = 1; index < value.length(); index++) { + if (value.charAt(index) < '0' || value.charAt(index) > '9') return false; + } + return true; + } + + private static boolean canonicalDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw unavailable(); + } + + private static byte[] ascii(String value) { + if (value == null) throw unavailable(); + byte[] bytes = value.getBytes(StandardCharsets.US_ASCII); + if (!value.equals(new String(bytes, StandardCharsets.US_ASCII))) throw unavailable(); + return bytes; + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (java.security.NoSuchAlgorithmException failure) { + throw unavailable(failure); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("CLOSED account barrier is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("CLOSED account barrier is unavailable", cause); + } + + private record BarrierContext( + CanonicalGameplayAccountAdmissionFenceIntent intent, + long targetOrdinal, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + String key) { + + private boolean sameOwnerContext(BarrierContext other) { + return other != null + && intent.operationId().equals(other.intent.operationId()) + && intent.requestId().equals(other.intent.requestId()) + && intent.accountId().equals(other.intent.accountId()) + && intent.operationFence().equals(other.intent.operationFence()) + && intent + .plannedAccountAdmissionFence() + .equals(other.intent.plannedAccountAdmissionFence()) + && intent.inventorySnapshotRevision().equals(other.intent.inventorySnapshotRevision()) + && intent.cohortDigest().equals(other.intent.cohortDigest()) + && intent.barrierTargetDigest().equals(other.intent.barrierTargetDigest()) + && targetOrdinal == other.targetOrdinal + && assignment.accountId().equals(other.assignment.accountId()) + && assignment.tenantId().equals(other.assignment.tenantId()) + && assignment + .playableStateNamespaceId() + .equals(other.assignment.playableStateNamespaceId()) + && assignment.tenantGameplayTag().equals(other.assignment.tenantGameplayTag()) + && assignment.workloadNamespace().equals(other.assignment.workloadNamespace()) + && assignment.allocationVersion() == other.assignment.allocationVersion() + && key.equals(other.key); + } + } + + /** Opaque physical CLOSED readback; construction is private to this Redis owner. */ + static final class Readback { + private final CanonicalGameplayAccountAdmissionFenceIntent intent; + private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; + private final UUID operationId; + private final UUID accountId; + private final long targetOrdinal; + private final String key; + private final Map barrierFields; + private final MutationOutcome mutationOutcome; + private final CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before; + private final CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after; + + private Readback( + BarrierContext context, + Map barrierFields, + MutationOutcome mutationOutcome, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after) { + this.intent = context.intent(); + this.assignment = context.assignment(); + this.operationId = context.intent().operationId(); + this.accountId = context.intent().accountId(); + this.targetOrdinal = context.targetOrdinal(); + this.key = context.key(); + this.barrierFields = Map.copyOf(barrierFields); + this.mutationOutcome = Objects.requireNonNull(mutationOutcome, "mutationOutcome"); + this.before = Objects.requireNonNull(before, "before verified incarnation"); + this.after = Objects.requireNonNull(after, "after verified incarnation"); + if (!this.barrierFields.equals(expectedFields(context, before.incarnationDigest())) + || !CLOSED.equals(this.barrierFields.get("state")) + || !this.before.incarnationDigest().equals(this.after.incarnationDigest())) { + throw unavailable(); + } + } + + UUID operationId() { + return operationId; + } + + CanonicalGameplayAccountAdmissionFenceIntent intent() { + return intent; + } + + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment() { + return assignment; + } + + UUID accountId() { + return accountId; + } + + long targetOrdinal() { + return targetOrdinal; + } + + String key() { + return key; + } + + MutationOutcome mutationOutcome() { + return mutationOutcome; + } + + Map barrierFields() { + return barrierFields; + } + + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation() { + return before; + } + + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation afterIncarnation() { + return after; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairOwner.java new file mode 100644 index 0000000000..36c064fed5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairOwner.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Explicit, unregistered composition of the binding-local SQL and Redis repair phases. It returns + * only the SQL owner's stored acknowledgement and does not perform or imply final admission. + */ +public final class CanonicalGameplayAccountMemberRepairOwner { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final CanonicalGameplayBindingInventoryRepository inventory; + private final CanonicalGameplayAccountMemberRepairRedisOwner redis; + + /** Builds concrete owners from the configured Game Session database and Redis clients. */ + public CanonicalGameplayAccountMemberRepairOwner( + DSLContext dsl, RedisClient redisClient, RedisScriptCatalog catalog) { + this.inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + this.redis = new CanonicalGameplayAccountMemberRepairRedisOwner(redisClient, catalog); + } + + /** + * Reuses the original SQL-allocated tuple on every retry: begin in SQL, project/read in Redis, + * then let SQL independently reload and accept that actual readback. + */ + public CanonicalGameplayAccountMemberAcknowledgement repair(UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId required"); + if (transitionId.equals(NIL_UUID)) { + throw new IllegalArgumentException("transitionId must not be nil"); + } + + requireNoAmbientTransaction(); + CanonicalGameplayAccountMemberRepairOperation original = + inventory.beginAccountMemberRepair(transitionId); + requireNoAmbientTransaction(); + + CanonicalGameplayAccountMemberRepairRedisOwner.Readback actual = redis.projectAndRead(original); + requireNoAmbientTransaction(); + if (!original.equals(actual.operation()) || !original.member().equals(actual.member())) { + throw new IllegalStateException( + "Redis readback does not match the original repair operation"); + } + + // The repository performs its own transaction and validates the complete stored tuple, + // current obligation, account-control epoch, and exact actual readback before accepting. + return inventory.acknowledgeAccountMemberRepair(original, actual); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Binding-local account member repair phases cannot share an ambient transaction"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwner.java new file mode 100644 index 0000000000..7d71783e69 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwner.java @@ -0,0 +1,360 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Projects one frozen binding-local ADD_OR_RETAIN obligation to the untagged global account set. + * This owner emits only physical Redis evidence; SQL independently accepts the original tuple. + */ +public final class CanonicalGameplayAccountMemberRepairRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String ACCOUNT_KEY_PREFIX = "session:game:index:account:"; + private static final int MAX_SCRIPT_BYTES = 32 * 1024; + private static final int MAX_BINDING_REF_BYTES = 6_144; + private static final int MAX_MEMBER_BYTES = 8_192; + private static final int MAX_DECIMAL_BYTES = 256; + private static final long REDIS_COMMAND_TIMEOUT_MILLIS = 5_000; + + private static final List EXPECTED_KEYS = + List.of( + new RedisScriptDescriptor.KeySpec( + "accountIndex", + ACCOUNT_KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)); + private static final List EXPECTED_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("accountId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("canonicalBindingRefBytes"), + new RedisScriptDescriptor.ArgumentSpec("bindingGeneration"), + new RedisScriptDescriptor.ArgumentSpec("accountIndexFence"), + new RedisScriptDescriptor.ArgumentSpec("exactAccountIndexMember"), + new RedisScriptDescriptor.ArgumentSpec("transitionId"), + new RedisScriptDescriptor.ArgumentSpec("operationId"), + new RedisScriptDescriptor.ArgumentSpec("operationFence"), + new RedisScriptDescriptor.ArgumentSpec("coverageFence"), + new RedisScriptDescriptor.ArgumentSpec("inventorySnapshotRevision"), + new RedisScriptDescriptor.ArgumentSpec("accountControlEpoch")); + private static final List EXPECTED_OUTCOMES = + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "MEMBER_ADDED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "MEMBER_ALREADY_PRESENT", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "WRONG_KEY_TYPE_OR_EXPIRY", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "INVALID_ARGUMENTS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final RedisClient redisClient; + private final RedisScriptCatalog catalog; + + /** Uses the caller's configured Redis client and installed owner contribution catalog. */ + public CanonicalGameplayAccountMemberRepairRedisOwner( + RedisClient redisClient, RedisScriptCatalog catalog) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client required"); + this.catalog = Objects.requireNonNull(catalog, "Installed Redis script catalog required"); + } + + /** + * Adds or retains exactly the frozen generation-qualified member and reads that member back on a + * separate connection from the same configured Redis client. No SQL call or admission decision + * occurs in this phase. + */ + public Readback projectAndRead(CanonicalGameplayAccountMemberRepairOperation operation) { + validateOperation(operation); + requireNoAmbientTransaction(); + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] source = source(descriptor); + byte[] key = accountKey(operation.accountId()); + byte[] member = operation.member().getBytes(StandardCharsets.US_ASCII); + + try (StatefulRedisConnection writeConnection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(writeConnection); + requirePrincipal(await(commands.aclWhoami())); + String loadedSha = await(commands.scriptLoad(source)); + if (!digest("SHA-1", source).equals(loadedSha)) throw unavailable(); + RedisFuture mutation = + commands.evalsha( + loadedSha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + operation.accountId().toString().getBytes(StandardCharsets.US_ASCII), + operation.tenantId().toString().getBytes(StandardCharsets.US_ASCII), + operation.bindingRef().bytes(), + operation.bindingGeneration().toString().getBytes(StandardCharsets.US_ASCII), + operation.accountIndexFence().toString().getBytes(StandardCharsets.US_ASCII), + member, + operation.transitionId().toString().getBytes(StandardCharsets.US_ASCII), + operation.operationId().toString().getBytes(StandardCharsets.US_ASCII), + operation.operationFence().toString().getBytes(StandardCharsets.US_ASCII), + operation.coverageFence().toString().getBytes(StandardCharsets.US_ASCII), + operation.inventorySnapshotRevision().toString().getBytes(StandardCharsets.US_ASCII), + operation.accountControlEpoch().toString().getBytes(StandardCharsets.US_ASCII)); + Long reply = await(mutation); + if (reply == null || (reply != 1L && reply != 2L)) throw unavailable(); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + + requireNoAmbientTransaction(); + try (StatefulRedisConnection readConnection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(readConnection); + requirePrincipal(await(commands.aclWhoami())); + if (!"set".equals(await(commands.type(key))) + || !Long.valueOf(-1L).equals(await(commands.pttl(key))) + || !Boolean.TRUE.equals(await(commands.sismember(key, member)))) throw unavailable(); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + // Both a new SADD (1) and an exact idempotent SADD replay (2) require the physical read above. + return new Readback(operation, operation.member()); + } + + private static void validateOperation(CanonicalGameplayAccountMemberRepairOperation operation) { + Objects.requireNonNull(operation, "Binding-local repair operation required"); + requireNonNil(operation.transitionId(), "transitionId"); + requireNonNil(operation.operationId(), "operationId"); + requirePositive(operation.operationFence(), "operationFence"); + requireNonNil(operation.coverageFence(), "coverageFence"); + requirePositive(operation.inventorySnapshotRevision(), "inventorySnapshotRevision"); + requireNonNil(operation.accountId(), "accountId"); + requireNonNil(operation.tenantId(), "tenantId"); + requirePositive(operation.bindingGeneration(), "bindingGeneration"); + requireNonNil(operation.accountIndexFence(), "accountIndexFence"); + Objects.requireNonNull(operation.accountControlEpoch(), "accountControlEpoch"); + if (operation.accountControlEpoch().signum() < 0 + || operation.operationId().equals(operation.transitionId()) + || operation.coverageFence().equals(operation.transitionId()) + || operation.coverageFence().equals(operation.operationId()) + || operation.coverageFence().equals(operation.accountIndexFence())) { + throw unavailable(); + } + + CanonicalGameplayBindingRef bindingRef; + try { + bindingRef = CanonicalGameplayBindingRef.fromExactBytes(operation.bindingRef().bytes()); + } catch (RuntimeException malformed) { + throw unavailable(malformed); + } + if (!bindingRef.equals(operation.bindingRef()) + || !operation.tenantId().toString().equals(bindingRef.tenantId())) throw unavailable(); + + var expectedMember = + new CanonicalGameplayAccountIndexMember( + bindingRef, operation.bindingGeneration(), operation.accountIndexFence()) + .value(); + if (expectedMember.length() > MAX_MEMBER_BYTES + || !expectedMember.equals(operation.member()) + || bindingRef.bytes().length > MAX_BINDING_REF_BYTES) throw unavailable(); + + CanonicalGameplayBindingAccountIndexObligation obligation = operation.originalObligation(); + if (!operation.transitionId().equals(obligation.transitionId()) + || obligation.ordinal() != 0 + || !bindingRef.equals(obligation.bindingRef()) + || !operation.accountId().equals(obligation.accountId()) + || !operation.tenantId().equals(obligation.tenantId()) + || obligation.action() + != CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN + || !operation.bindingGeneration().equals(obligation.bindingGeneration()) + || !operation.accountIndexFence().equals(obligation.accountIndexFence()) + || obligation.executionPhase() + != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS + || obligation.status() != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + || obligation.expectedPriorGeneration() != null + || obligation.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .ABSENT_AWAITING_COVERAGE + || obligation.inventoryRevision().compareTo(operation.inventorySnapshotRevision()) > 0) { + throw unavailable(); + } + if (obligation.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED) { + if (obligation.projectedMember() != null || obligation.projectionInventoryRevision() != null) + throw unavailable(); + } else if (!operation.member().equals(obligation.projectedMember()) + || obligation.projectionInventoryRevision() == null + || obligation.projectionInventoryRevision().signum() <= 0) { + throw unavailable(); + } + + if (!canonicalDecimal(operation.bindingGeneration().toString(), false) + || !canonicalDecimal(operation.operationFence().toString(), false) + || !canonicalDecimal(operation.inventorySnapshotRevision().toString(), false) + || !canonicalDecimal(operation.accountControlEpoch().toString(), true)) throw unavailable(); + } + + private RedisScriptDescriptor requireDescriptor() { + try { + var descriptor = + catalog.require(CanonicalGameplayAccountMemberRepairRedisScriptContribution.SCRIPT_ID); + if (!CanonicalGameplayAccountMemberRepairRedisScriptContribution.SCRIPT_ID.equals( + descriptor.scriptId()) + || !CanonicalGameplayAccountMemberRepairRedisScriptContribution.RESOURCE_PATH.equals( + descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !EXPECTED_KEYS.equals(descriptor.keys()) + || !EXPECTED_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_ACCOUNT_INDEX + || !EXPECTED_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none"))) + || descriptor.legacyPayloadShape() != null) throw unavailable(); + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] source(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayAccountMemberRepairRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) throw unavailable(); + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] accountKey(UUID accountId) { + return (ACCOUNT_KEY_PREFIX + accountId).getBytes(StandardCharsets.US_ASCII); + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + return connection.async(); + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static T await(RedisFuture future) { + try { + return future.get(REDIS_COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + future.cancel(true); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException | RuntimeException failure) { + future.cancel(true); + throw unavailable(failure); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); + } + + private static boolean canonicalDecimal(String value, boolean allowZero) { + if (value == null || value.isEmpty() || value.length() > MAX_DECIMAL_BYTES) return false; + if (allowZero && value.equals("0")) return true; + if (value.charAt(0) < '1' || value.charAt(0) > '9') return false; + for (int index = 1; index < value.length(); index++) { + if (value.charAt(index) < '0' || value.charAt(index) > '9') return false; + } + return true; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) throw unavailable(); + } + + private static void requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw unavailable(); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Binding-local account member Redis projection is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException( + "Binding-local account member Redis projection is unavailable", cause); + } + + /** + * Capability created only after script execution and separate physical SET membership readback. A + * caller cannot manufacture one from a PRESENT claim or a Redis script echo. + */ + public static final class Readback { + private final CanonicalGameplayAccountMemberRepairOperation operation; + private final String member; + + private Readback(CanonicalGameplayAccountMemberRepairOperation operation, String member) { + this.operation = Objects.requireNonNull(operation, "operation"); + this.member = Objects.requireNonNull(member, "member"); + if (!member.equals(operation.member())) throw unavailable(); + } + + public CanonicalGameplayAccountMemberRepairOperation operation() { + return operation; + } + + public String member() { + return member; + } + } +} 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 index cdcc43539d..8a0dc97ea6 100644 --- 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 @@ -12,6 +12,8 @@ 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.CanonicalGameplayAccountMemberAcknowledgement; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexProjectionReceipt; @@ -36,9 +38,9 @@ /** * 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. + *

This class deliberately has no Spring stereotype and a package-private API. It owns the + * binding-local account-member acknowledgement, but it is not a Redis or controller-CAS surface. A + * completed member acknowledgement leaves the candidate provisional and non-admitting. */ public final class CanonicalGameplayBindingInventoryRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -277,10 +279,23 @@ CanonicalGameplayBindingAccountIndexProjectionReceipt markCandidateAccountIndexP || !candidateObligation .accountIndexFence() .equals(current.candidate().accountIndexFence()) - || candidateObligation.status() - != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED) { + || (candidateObligation.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + && candidateObligation.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED)) { throw conflict("The account-index candidate obligation differs from durable ownership"); } + if (candidateObligation.status() + == CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED) { + if (candidateObligation.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE + || !member.equals(candidateObligation.projectedMember())) { + throw conflict( + "Completed account-index acknowledgement differs from the exact member"); + } + return projectionReceipt(candidateObligation); + } if (candidateObligation.projectionState() == CanonicalGameplayBindingAccountIndexObligation.ProjectionState .PRESENT_AWAITING_COVERAGE) { @@ -406,6 +421,156 @@ CanonicalGameplayBindingAccountIndexProjectionReceipt markCandidateAccountIndexP }); } + /** + * Allocates or returns the immutable binding-local account-member repair operation for one + * ordinary NEW transition. The account-wide control is positively read and pinned by its epoch; + * this method never creates or releases an account-wide admission fence. + */ + CanonicalGameplayAccountMemberRepairOperation beginAccountMemberRepair(UUID transitionId) { + Objects.requireNonNull(transitionId, "transitionId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger inventoryRevision = lockInventoryRevision(transaction); + CanonicalGameplayBindingProvisionalCasEvidence evidence = + loadProvisionalCasEvidence(transaction, transitionId, true); + UUID accountId = evidence.candidate().identity().accountId(); + AccountCoverageControl control = + lockExistingAccountCoverageControl(transaction, accountId); + requireNoActiveAccountControl(control); + if (!control.evidence().equals(evidence.transition().accountCoverageEvidence())) { + throw conflict( + "Binding transition did not retain the current positively read account-control state"); + } + readVerifiedLegacyDisposition(transaction, inventoryRevision, true); + requireOrdinaryNewMemberRepairTransition(evidence); + + Record existing = findMemberRepairOperation(transaction, transitionId, true); + if (existing != null) { + CanonicalGameplayAccountMemberRepairOperation operation = + toMemberRepairOperation(existing); + if (!operation.accountControlEpoch().equals(control.epoch())) { + throw conflict("The account-wide control fence advanced after member repair began"); + } + CanonicalGameplayBindingAccountIndexObligation currentObligation = + loadAccountIndexObligations(transaction, transitionId, true).getFirst(); + boolean completed = "ACKNOWLEDGED".equals(existing.get("status", String.class)); + requireMemberRepairObligationCurrent( + operation, evidence.candidate(), currentObligation, completed); + if (completed) { + toMemberAcknowledgement(existing); + } + return operation; + } + + CanonicalGameplayBindingAccountIndexObligation originalObligation = + loadAccountIndexObligations(transaction, transitionId, true).getFirst(); + if (originalObligation.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + || evidence.candidate().accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { + throw conflict( + "A new member repair requires the original unresolved account obligation"); + } + + UUID operationId = freshOperationId(transitionId); + UUID coverageFence = + freshDistinctCoverageFence( + operationId, transitionId, evidence.candidate().accountIndexFence()); + BigInteger operationFence = allocateMemberRepairFence(transaction, accountId); + String member = CanonicalGameplayAccountIndexMember.of(evidence.candidate()).value(); + CanonicalGameplayAccountMemberRepairOperation operation = + new CanonicalGameplayAccountMemberRepairOperation( + transitionId, + operationId, + operationFence, + coverageFence, + inventoryRevision, + evidence.candidate().bindingRef(), + accountId, + evidence.candidate().identity().tenantId(), + evidence.candidate().bindingGeneration(), + evidence.candidate().accountIndexFence(), + originalObligation, + member, + control.epoch()); + insertMemberRepairOperation(transaction, operation); + return operation; + }); + } + + /** + * Commits only an actual Redis write/read result bound to the stored original operation. The + * durable operation, current obligation, account-control epoch, readback, and later evidence + * generation are compared or written in one PostgreSQL transaction. + */ + CanonicalGameplayAccountMemberAcknowledgement acknowledgeAccountMemberRepair( + CanonicalGameplayAccountMemberRepairOperation expected, + CanonicalGameplayAccountMemberRepairRedisOwner.Readback actual) { + Objects.requireNonNull(expected, "expected"); + Objects.requireNonNull(actual, "actual"); + if (!expected.equals(actual.operation()) || !expected.member().equals(actual.member())) { + throw conflict("Redis readback is not bound to the exact expected member repair operation"); + } + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + lockLeaseBoundRuntimeBeforeTransition( + transaction, expected.transitionId(), expected.bindingRef().bytes(), null); + AccountCoverageControl control = + lockExistingAccountCoverageControl(transaction, expected.accountId()); + requireNoActiveAccountControl(control); + if (!control.epoch().equals(expected.accountControlEpoch())) { + throw conflict("The account-wide control fence changed during member repair"); + } + readVerifiedLegacyDisposition(transaction, currentRevision, true); + Record operationRow = + findMemberRepairOperation(transaction, expected.transitionId(), true); + if (operationRow == null) { + throw conflict("The exact durable account-member repair operation is missing"); + } + CanonicalGameplayAccountMemberRepairOperation stored = + toMemberRepairOperation(operationRow); + if (!stored.equals(expected) + || !stored.equals(actual.operation()) + || !stored.member().equals(actual.member())) { + throw conflict("Expected and actual member repair differ from the durable owner tuple"); + } + CanonicalGameplayBindingProvisionalCasEvidence current = + loadProvisionalCasEvidence(transaction, expected.transitionId(), true); + requireOrdinaryNewMemberRepairTransition(current); + CanonicalGameplayBindingAccountIndexObligation currentObligation = + loadAccountIndexObligations(transaction, expected.transitionId(), true).getFirst(); + boolean completed = "ACKNOWLEDGED".equals(operationRow.get("status", String.class)); + requireMemberRepairObligationCurrent( + stored, current.candidate(), currentObligation, completed); + if (!current.transition().accountCoverageEvidence().equals(control.evidence())) { + throw conflict( + "Transition account-wide state no longer matches the pinned control row"); + } + String exactMember = CanonicalGameplayAccountIndexMember.of(current.candidate()).value(); + if (!exactMember.equals(actual.member())) { + throw conflict("Redis readback member differs from the exact durable candidate tuple"); + } + if (completed) { + return toMemberAcknowledgement(operationRow); + } + + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + BigInteger coverageGeneration = + allocateMemberRepairCoverageGeneration( + transaction, stored.accountId(), stored.inventorySnapshotRevision()); + if (coverageGeneration.compareTo(stored.inventorySnapshotRevision()) <= 0) { + throw conflict("Binding-local evidence generation must advance beyond its snapshot"); + } + persistMemberRepairAcknowledgement( + transaction, stored, current, nextRevision, coverageGeneration, actual.member()); + return new CanonicalGameplayAccountMemberAcknowledgement( + stored, coverageGeneration, actual.member()); + }); + } + /** * 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 @@ -1093,9 +1258,49 @@ private static CanonicalGameplayBindingProvisionalCasEvidence loadProvisionalCas CanonicalGameplayBindingRegionBridgeObligation regionObligation = regionObligationRow == null ? null : toRegionObligation(regionObligationRow); requireExactProvisionalRows(evidence, accountObligations, issuerObligation, regionObligation); + if (!accountObligations.isEmpty() + && accountObligations.getFirst().status() + == CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED) { + requireCompletedMemberRepairAcknowledgement( + transaction, evidence, accountObligations.getFirst()); + } return evidence; } + private static void requireCompletedMemberRepairAcknowledgement( + DSLContext transaction, + CanonicalGameplayBindingProvisionalCasEvidence evidence, + CanonicalGameplayBindingAccountIndexObligation obligation) { + requireOrdinaryNewMemberRepairTransition(evidence); + Record operationRow = + findMemberRepairOperation(transaction, evidence.transition().transitionId(), false); + if (operationRow == null) { + throw conflict( + "Acknowledged account-index obligation has no durable member-repair operation"); + } + CanonicalGameplayAccountMemberRepairOperation operation = toMemberRepairOperation(operationRow); + if (!"ACKNOWLEDGED".equals(operationRow.get("status", String.class))) { + throw conflict("Account-index obligation was acknowledged before its operation completed"); + } + requireMemberRepairObligationCurrent(operation, evidence.candidate(), obligation, true); + toMemberAcknowledgement(operationRow); + Record control = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control WHERE account_id = ?", + operation.accountId()); + if (control == null) { + throw conflict("Acknowledged member repair lost its positive account-control row"); + } + CanonicalGameplayAccountCoverageEvidence currentControl = + accountCoverageEvidenceFromControl(control, operation.accountId()); + if (!(currentControl instanceof CanonicalGameplayAccountCoverageEvidence.NoActiveFlow) + || !evidence.transition().accountCoverageEvidence().equals(currentControl) + || !readBigInteger(control, "last_operation_fence") + .equals(operation.accountControlEpoch())) { + throw conflict("Acknowledged member repair has stale account-control state or fence epoch"); + } + } + private static void requireExactProvisionalRows( CanonicalGameplayBindingProvisionalCasEvidence evidence, List accountObligations, @@ -1134,8 +1339,17 @@ private static void requireExactProvisionalRows( || !candidateAccount.accountIndexFence().equals(candidate.accountIndexFence()) || candidateAccount.executionPhase() != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS - || candidateAccount.status() - != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + || (candidateAccount.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + && candidateAccount.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED) + || (candidateAccount.status() + == CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED + && (candidateAccount.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE + || candidate.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED)) || !candidateAccount.inventoryRevision().equals(transition.inventoryRevision())) { throw conflict("Durable account-index repair obligations differ from this exact transition"); } @@ -1466,6 +1680,11 @@ private static CanonicalGameplayLegacyMigrationDisposition readVerifiedLegacyDis private static CanonicalGameplayAccountCoverageEvidence lockAccountCoverageEvidence( DSLContext transaction, UUID accountId) { + return lockAccountCoverageControl(transaction, accountId).evidence(); + } + + private static AccountCoverageControl lockAccountCoverageControl( + DSLContext transaction, UUID accountId) { transaction.execute( "INSERT INTO game_session_canonical_account_coverage_control " + "(account_id, state, last_operation_fence) " @@ -1478,7 +1697,35 @@ private static CanonicalGameplayAccountCoverageEvidence lockAccountCoverageEvide + "WHERE account_id = ? FOR UPDATE", accountId), "account coverage control row must exist"); - return accountCoverageEvidenceFromControl(control, accountId); + return toAccountCoverageControl(control, accountId); + } + + private static AccountCoverageControl lockExistingAccountCoverageControl( + DSLContext transaction, UUID accountId) { + Record control = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control " + + "WHERE account_id = ? FOR UPDATE", + accountId); + if (control == null) { + throw conflict("Account coverage control row is missing; absence is not no-active proof"); + } + return toAccountCoverageControl(control, accountId); + } + + private static AccountCoverageControl toAccountCoverageControl(Record control, UUID accountId) { + return new AccountCoverageControl( + accountId, + control.get("state", String.class), + readBigInteger(control, "last_operation_fence"), + control.get("current_operation_id", UUID.class), + nullableBigInteger(control, "current_operation_fence"), + control.get("account_admission_fence", UUID.class), + control.get("historical_account_admission_fence", UUID.class), + control.get("coverage_fence", UUID.class), + nullableBigInteger(control, "inventory_snapshot_revision"), + nullableBigInteger(control, "coverage_generation"), + accountCoverageEvidenceFromControl(control, accountId)); } private static void requireReadAccountCoverageEvidenceCurrent( @@ -1499,6 +1746,9 @@ private static CanonicalGameplayAccountCoverageEvidence accountCoverageEvidenceF if ("ACTIVE".equals(state)) { throw conflict("Account-wide admission fence blocks a new binding transition"); } + if ("ACQUISITION_INTENT".equals(state)) { + throw conflict("Account-fence acquisition intent blocks a new binding transition"); + } if ("NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(state)) { return CanonicalGameplayAccountCoverageEvidence.noActiveFlow(); } @@ -1515,6 +1765,486 @@ private static CanonicalGameplayAccountCoverageEvidence accountCoverageEvidenceF throw conflict("Account coverage control state is unknown and cannot authorize a transition"); } + private static void requireNoActiveAccountControl(AccountCoverageControl control) { + if (!"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(control.state()) + || control.currentOperationId() != null + || control.currentOperationFence() != null + || control.accountAdmissionFence() != null + || control.historicalAccountAdmissionFence() != null + || control.coverageFence() != null + || control.inventorySnapshotRevision() != null + || control.coverageGeneration() != null + || !(control.evidence() instanceof CanonicalGameplayAccountCoverageEvidence.NoActiveFlow)) { + throw conflict("Account-wide control is not the positively read no-active state"); + } + if (control.epoch().signum() < 0) { + throw conflict("Account-wide control has an invalid fence epoch"); + } + } + + private static void requireOrdinaryNewMemberRepairTransition( + CanonicalGameplayBindingProvisionalCasEvidence evidence) { + if (evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || evidence.candidate().lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL + || evidence.expectedPrior() != null + || evidence.expectedPriorReservation() != null + || evidence.transition().expectedPriorBindingRef() != null + || evidence.transition().expectedPriorBindingGeneration() != null + || !(evidence.transition().accountCoverageEvidence() + instanceof CanonicalGameplayAccountCoverageEvidence.NoActiveFlow)) { + throw conflict( + "Binding-local member repair requires an ordinary NEW provisional transition in the no-active arm"); + } + } + + private static void requireMemberRepairObligationCurrent( + CanonicalGameplayAccountMemberRepairOperation operation, + CanonicalGameplayBindingInventoryEntry candidate, + CanonicalGameplayBindingAccountIndexObligation current, + boolean completed) { + CanonicalGameplayBindingAccountIndexObligation original = operation.originalObligation(); + if (!current.transitionId().equals(operation.transitionId()) + || current.ordinal() != original.ordinal() + || !current.bindingRef().equals(operation.bindingRef()) + || !current.accountId().equals(operation.accountId()) + || !current.tenantId().equals(operation.tenantId()) + || current.action() != original.action() + || !current.bindingGeneration().equals(operation.bindingGeneration()) + || !Objects.equals(current.expectedPriorGeneration(), original.expectedPriorGeneration()) + || !current.accountIndexFence().equals(operation.accountIndexFence()) + || current.executionPhase() != original.executionPhase() + || !current.inventoryRevision().equals(candidate.inventoryRevision())) { + throw conflict("Current account-index obligation differs from its immutable original tuple"); + } + if (completed) { + if (current.status() != CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED + || current.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE + || !operation.member().equals(current.projectedMember()) + || (original.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE + && !Objects.equals( + original.projectionInventoryRevision(), current.projectionInventoryRevision())) + || candidate.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED) { + throw conflict("Completed member repair lost its exact durable acknowledgement state"); + } + } else { + if (current.status() != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + || candidate.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { + throw conflict("Pending member repair no longer owns its unresolved candidate obligation"); + } + if (current.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED) { + if (original.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED + || current.projectedMember() != null + || current.projectionInventoryRevision() != null) { + throw conflict("Current account-index projection differs from its frozen original state"); + } + } else if (current.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE) { + if (!operation.member().equals(current.projectedMember())) { + throw conflict("Retained PRESENT observation differs from the exact repair member"); + } + if (original.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE + && (!Objects.equals(original.projectedMember(), current.projectedMember()) + || !Objects.equals( + original.projectionInventoryRevision(), + current.projectionInventoryRevision()))) { + throw conflict("Original PRESENT observation changed after the repair was frozen"); + } + } else { + throw conflict("Pending ADD_OR_RETAIN has an unsupported account-index projection state"); + } + } + } + + private static Record findMemberRepairOperation( + DSLContext transaction, UUID transitionId, boolean forUpdate) { + return transaction.fetchOne( + "SELECT * FROM game_session_canonical_account_member_repair_operation" + + " WHERE transition_id = ? AND obligation_ordinal = 0" + + (forUpdate ? " FOR UPDATE" : ""), + transitionId); + } + + private static BigInteger allocateMemberRepairFence(DSLContext transaction, UUID accountId) { + transaction.execute( + "INSERT INTO game_session_canonical_account_member_repair_control " + + "(account_id, last_operation_fence) VALUES (?, 0) ON CONFLICT (account_id) DO NOTHING", + accountId); + Record fenceRow = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT last_operation_fence FROM " + + "game_session_canonical_account_member_repair_control " + + "WHERE account_id = ? FOR UPDATE", + accountId), + "account member-repair fence row must exist"); + BigInteger previous = readBigInteger(fenceRow, "last_operation_fence"); + BigInteger next = previous.add(BigInteger.ONE); + requireOne( + transaction.execute( + "UPDATE game_session_canonical_account_member_repair_control " + + "SET last_operation_fence = ? WHERE account_id = ? AND last_operation_fence = ?", + decimal(next), + accountId, + decimal(previous)), + "Account member-repair operation fence compare-and-set lost its locked row"); + return next; + } + + private static BigInteger allocateMemberRepairCoverageGeneration( + DSLContext transaction, UUID accountId, BigInteger inventorySnapshotRevision) { + Record generationRow = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT last_coverage_generation FROM " + + "game_session_canonical_account_member_repair_control " + + "WHERE account_id = ? FOR UPDATE", + accountId), + "account member-repair generation row must exist"); + BigInteger previous = readBigInteger(generationRow, "last_coverage_generation"); + BigInteger next = previous.add(BigInteger.ONE); + if (next.compareTo(inventorySnapshotRevision) <= 0) { + next = inventorySnapshotRevision.add(BigInteger.ONE); + } + requireOne( + transaction.execute( + "UPDATE game_session_canonical_account_member_repair_control " + + "SET last_coverage_generation = ? WHERE account_id = ?" + + " AND last_coverage_generation = ?", + decimal(next), + accountId, + decimal(previous)), + "Account member-repair coverage generation compare-and-set lost its locked row"); + return next; + } + + private static UUID freshNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (value.equals(NIL_UUID)); + return value; + } + + private static UUID freshOperationId(UUID transitionId) { + UUID value; + do { + value = freshNonNilUuid(); + } while (value.equals(transitionId)); + return value; + } + + private static UUID freshDistinctCoverageFence( + UUID operationId, UUID transitionId, UUID accountIndexFence) { + UUID coverageFence; + do { + coverageFence = freshNonNilUuid(); + } while (coverageFence.equals(operationId) + || coverageFence.equals(transitionId) + || coverageFence.equals(accountIndexFence)); + return coverageFence; + } + + private static void insertMemberRepairOperation( + DSLContext transaction, CanonicalGameplayAccountMemberRepairOperation operation) { + CanonicalGameplayBindingAccountIndexObligation original = operation.originalObligation(); + requireOne( + transaction.execute( + "INSERT INTO game_session_canonical_account_member_repair_operation " + + "(operation_id, transition_id, obligation_ordinal, operation_fence, coverage_fence," + + " inventory_snapshot_revision, binding_ref, account_id, tenant_id, binding_generation," + + " account_index_fence, original_action, original_expected_prior_generation," + + " original_execution_phase, original_status, original_inventory_revision," + + " original_projection_state, original_projection_member," + + " original_projection_inventory_revision, desired_action, member," + + " account_control_state, account_control_epoch, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', ?, 'PENDING')", + operation.operationId(), + operation.transitionId(), + original.ordinal(), + decimal(operation.operationFence()), + operation.coverageFence(), + decimal(operation.inventorySnapshotRevision()), + operation.bindingRef().bytes(), + operation.accountId(), + operation.tenantId(), + decimal(operation.bindingGeneration()), + operation.accountIndexFence(), + original.action().name(), + decimalNullable(original.expectedPriorGeneration()), + original.executionPhase().name(), + original.status().name(), + decimal(original.inventoryRevision()), + original.projectionState().name(), + original.projectedMember(), + decimalNullable(original.projectionInventoryRevision()), + original.action().name(), + operation.member(), + decimal(operation.accountControlEpoch())), + "Account member-repair operation insert conflicted with an existing obligation"); + } + + private static CanonicalGameplayAccountMemberRepairOperation toMemberRepairOperation(Record row) { + try { + if (!"ADD_OR_RETAIN".equals(row.get("desired_action", String.class)) + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW" + .equals(row.get("account_control_state", String.class))) { + throw conflict("Durable member-repair operation carries an unsupported action or scope"); + } + CanonicalGameplayBindingRef bindingRef = + CanonicalGameplayBindingRef.fromExactBytes(row.get("binding_ref", byte[].class)); + UUID accountId = row.get("account_id", UUID.class); + UUID tenantId = row.get("tenant_id", UUID.class); + if (!bindingRef.tenantId().equals(tenantId.toString())) { + throw conflict("Durable member-repair bindingRef belongs to a different tenant"); + } + CanonicalGameplayBindingAccountIndexObligation original = + new CanonicalGameplayBindingAccountIndexObligation( + row.get("transition_id", UUID.class), + row.get("obligation_ordinal", Integer.class), + bindingRef, + accountId, + tenantId, + CanonicalGameplayBindingAccountIndexObligation.Action.valueOf( + row.get("original_action", String.class)), + readBigInteger(row, "binding_generation"), + nullableBigInteger(row, "original_expected_prior_generation"), + row.get("account_index_fence", UUID.class), + CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.valueOf( + row.get("original_execution_phase", String.class)), + CanonicalGameplayBindingAccountIndexObligation.Status.valueOf( + row.get("original_status", String.class)), + readBigInteger(row, "original_inventory_revision"), + CanonicalGameplayBindingAccountIndexObligation.ProjectionState.valueOf( + row.get("original_projection_state", String.class)), + row.get("original_projection_member", String.class), + nullableBigInteger(row, "original_projection_inventory_revision")); + return new CanonicalGameplayAccountMemberRepairOperation( + row.get("transition_id", UUID.class), + row.get("operation_id", UUID.class), + readBigInteger(row, "operation_fence"), + row.get("coverage_fence", UUID.class), + readBigInteger(row, "inventory_snapshot_revision"), + bindingRef, + accountId, + tenantId, + readBigInteger(row, "binding_generation"), + row.get("account_index_fence", UUID.class), + original, + row.get("member", String.class), + readBigInteger(row, "account_control_epoch")); + } catch (CanonicalGameplayBindingInventoryConflictException classified) { + throw classified; + } catch (RuntimeException malformed) { + throw conflict("Durable account-member repair operation is incomplete or invalid"); + } + } + + private static CanonicalGameplayAccountMemberAcknowledgement toMemberAcknowledgement( + Record operationRow) { + if (!"ACKNOWLEDGED".equals(operationRow.get("status", String.class)) + || !"PRESENT".equals(operationRow.get("readback_state", String.class))) { + throw conflict( + "Durable account-member repair has no complete exact readback acknowledgement"); + } + try { + return new CanonicalGameplayAccountMemberAcknowledgement( + toMemberRepairOperation(operationRow), + readBigInteger(operationRow, "coverage_generation"), + operationRow.get("readback_member", String.class)); + } catch (RuntimeException malformed) { + throw conflict("Durable binding-local account-index acknowledgement is invalid"); + } + } + + private static void persistMemberRepairAcknowledgement( + DSLContext transaction, + CanonicalGameplayAccountMemberRepairOperation operation, + CanonicalGameplayBindingProvisionalCasEvidence current, + BigInteger nextRevision, + BigInteger coverageGeneration, + String member) { + BigInteger transitionRevision = current.transition().inventoryRevision(); + 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 = ?" + + " AND account_coverage_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'" + + " AND account_coverage_operation_id IS NULL" + + " AND account_coverage_operation_fence IS NULL" + + " AND account_coverage_lifecycle IS NULL" + + " AND account_admission_fence_kind = 'NOT_APPLICABLE'" + + " AND account_admission_fence IS NULL AND historical_account_admission_fence IS NULL" + + " AND historical_account_admission_fence_kind = 'NOT_APPLICABLE'" + + " 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", + decimal(nextRevision), + operation.transitionId(), + decimal(transitionRevision), + operation.bindingRef().bytes(), + decimal(operation.bindingGeneration()), + operation.accountIndexFence()), + "Durable NEW transition changed before member acknowledgement"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET account_index_state = 'ACKNOWLEDGED', inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'PROVISIONAL'" + + " AND binding_generation = ? AND account_index_fence = ?" + + " AND account_id = ? AND tenant_id = ?" + + " AND account_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), + operation.bindingRef().bytes(), + operation.transitionId(), + decimal(operation.bindingGeneration()), + operation.accountIndexFence(), + operation.accountId(), + operation.tenantId(), + decimal(transitionRevision)), + "Durable NEW candidate changed before member acknowledgement"); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET status = 'ACKNOWLEDGED', projection_state = 'PRESENT_AWAITING_COVERAGE'," + + " projection_member = ?, projection_inventory_revision = COALESCE(" + + " projection_inventory_revision, ?), inventory_revision = ?" + + " WHERE transition_id = ? AND obligation_ordinal = 0" + + " AND binding_ref = ? AND account_id = ? AND tenant_id = ?" + + " AND action = 'ADD_OR_RETAIN' AND binding_generation = ?" + + " AND expected_prior_generation IS NULL AND account_index_fence = ?" + + " AND execution_phase = 'BEFORE_FINAL_CAS' AND status = 'REQUIRED'" + + " AND inventory_revision = ?" + + " AND ((projection_state = 'REQUIRED' AND projection_member IS NULL" + + " AND projection_inventory_revision IS NULL)" + + " OR (projection_state = 'PRESENT_AWAITING_COVERAGE' AND projection_member = ?))", + member, + decimal(nextRevision), + decimal(nextRevision), + operation.transitionId(), + operation.bindingRef().bytes(), + operation.accountId(), + operation.tenantId(), + decimal(operation.bindingGeneration()), + operation.accountIndexFence(), + decimal(transitionRevision), + member), + "Original account-index obligation changed before complete v2 acknowledgement"); + requireCount( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND obligation_ordinal = 1" + + " AND inventory_revision = ?", + decimal(nextRevision), + operation.transitionId(), + decimal(transitionRevision)), + 0, + "Ordinary NEW unexpectedly owns a prior account-index obligation"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND binding_ref = ?" + + " AND status = 'REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), + operation.transitionId(), + operation.bindingRef().bytes(), + decimal(transitionRevision)), + "Issuer obligation changed before member acknowledgement"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND binding_ref = ?" + + " AND status = 'REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), + operation.transitionId(), + operation.bindingRef().bytes(), + decimal(transitionRevision)), + "Region obligation changed before member acknowledgement"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET inventory_revision = ? WHERE reservation_id = ? AND transition_id = ?" + + " AND binding_ref = ? AND lifecycle = 'RESERVED' AND inventory_revision = ?", + decimal(nextRevision), + current.transition().issuerReservationId(), + operation.transitionId(), + operation.bindingRef().bytes(), + decimal(transitionRevision)), + "Issuer reservation changed before member acknowledgement"); + requireOne( + transaction.execute( + "UPDATE " + + "game_session_canonical_account_member_repair_operation" + + " SET status = 'ACKNOWLEDGED', coverage_generation = ?, readback_state = 'PRESENT'," + + " readback_member = ?, completed_inventory_revision = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND transition_id = ? AND obligation_ordinal = 0" + + " AND operation_fence = ? AND coverage_fence = ?" + + " AND inventory_snapshot_revision = ? AND binding_ref = ?" + + " AND account_id = ? AND tenant_id = ? AND binding_generation = ?" + + " AND account_index_fence = ? AND member = ? AND account_control_epoch = ?" + + " AND original_action = 'ADD_OR_RETAIN'" + + " AND original_expected_prior_generation IS NULL" + + " AND original_execution_phase = 'BEFORE_FINAL_CAS'" + + " AND original_status = 'REQUIRED' AND original_inventory_revision = ?" + + " AND original_projection_state = ?" + + " AND original_projection_member IS NOT DISTINCT FROM ?" + + " AND original_projection_inventory_revision IS NOT DISTINCT FROM ?" + + " AND desired_action = 'ADD_OR_RETAIN'" + + " AND account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'" + + " AND status = 'PENDING' AND coverage_generation IS NULL" + + " AND readback_state IS NULL AND readback_member IS NULL", + decimal(coverageGeneration), + member, + decimal(nextRevision), + operation.operationId(), + operation.transitionId(), + decimal(operation.operationFence()), + operation.coverageFence(), + decimal(operation.inventorySnapshotRevision()), + operation.bindingRef().bytes(), + operation.accountId(), + operation.tenantId(), + decimal(operation.bindingGeneration()), + operation.accountIndexFence(), + member, + decimal(operation.accountControlEpoch()), + decimal(operation.originalObligation().inventoryRevision()), + operation.originalObligation().projectionState().name(), + operation.originalObligation().projectedMember(), + decimalNullable(operation.originalObligation().projectionInventoryRevision())), + "Durable member-repair operation changed before acknowledgement persistence"); + requireOne( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = ?", + decimal(nextRevision), + decimal(nextRevision.subtract(BigInteger.ONE))), + "Inventory revision compare-and-set lost during member acknowledgement"); + } + private static void requireAccountCoverageEvidenceCurrent( DSLContext transaction, UUID accountId, CanonicalGameplayAccountCoverageEvidence expected) { CanonicalGameplayAccountCoverageEvidence current = @@ -1604,6 +2334,11 @@ private static CanonicalGameplayBindingTransitionSnapshot requireExactRetry( request.issuerReservation().reservationId())) { throw conflict("The same transition identity was retried with a different exact request"); } + if ("PROVISIONAL".equals(storedStatus) && expectedRef == null) { + // Keep the transition-first row-lock order and verify any completed member ACK from its + // durable operation before this exact NEW retry accepts the acknowledged candidate state. + loadProvisionalCasEvidence(transaction, request.transitionId(), true); + } if (expectedRef == null && findActiveController(transaction, candidate) != null) { throw conflict("A first-binding retry cannot proceed while an active controller exists"); } @@ -1611,10 +2346,16 @@ private static CanonicalGameplayBindingTransitionSnapshot requireExactRetry( transaction.fetchOne( "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE", candidate.bindingRef().bytes()); + boolean acknowledgedOrdinaryNewRetry = + "PROVISIONAL".equals(storedStatus) + && expectedRef == null + && binding != null + && "ACKNOWLEDGED".equals(binding.get("account_index_state", String.class)); 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("account_index_state", String.class)) + && !acknowledgedOrdinaryNewRetry) || !"REPAIR_REQUIRED".equals(binding.get("issuer_index_state", String.class)) || !readBigInteger(binding, "binding_generation") .equals(readBigInteger(transition, "candidate_binding_generation")) @@ -1655,7 +2396,7 @@ private static CanonicalGameplayBindingTransitionSnapshot requireExactRetry( 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()) + || !Objects.equals(reservation.get("issuer_id", String.class), candidate.issuerId()) || !readBigInteger(reservation, "issuer_auth_generation") .equals(candidate.issuerAuthGeneration()) || !readBigInteger(reservation, "issuer_index_layout_version") @@ -1709,13 +2450,20 @@ private static void requireExactStoredObligations( throw conflict("Stored transition does not retain every required account-index obligation"); } Record add = obligations.get(0); + boolean completedOrdinaryNewMemberRepair = + "PROVISIONAL".equals(transition.get("status", String.class)) + && expectedPriorBindingRef == null + && "ACKNOWLEDGED".equals(add.get("status", String.class)) + && "PRESENT_AWAITING_COVERAGE".equals(add.get("projection_state", String.class)) + && "ACKNOWLEDGED".equals(candidate.get("account_index_state", String.class)); 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)) + || (!"REQUIRED".equals(add.get("status", String.class)) + && !completedOrdinaryNewMemberRepair) || !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()) @@ -1810,7 +2558,8 @@ private static void requireExactStoredObligations( 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()) + || !Objects.equals( + reservation.get("issuer_id", String.class), request.candidate().issuerId()) || !readBigInteger(reservation, "issuer_auth_generation") .equals(request.candidate().issuerAuthGeneration()) || !readBigInteger(reservation, "issuer_index_layout_version") @@ -2281,7 +3030,7 @@ private static CanonicalGameplayBindingIdentity toIdentity(Record row) { row.get("session_id", String.class), row.get("region_id", UUID.class), readBigInteger(row, "region_epoch"), - row.get("issuer_id", UUID.class), + row.get("issuer_id", String.class), readBigInteger(row, "issuer_auth_generation"), readBigInteger(row, "issuer_index_layout_version"), readBigInteger(row, "issuer_index_partition_count"), @@ -2309,6 +3058,23 @@ private static BigDecimal decimal(BigInteger value) { return new BigDecimal(value); } + private static BigDecimal decimalNullable(BigInteger value) { + return value == null ? null : decimal(value); + } + + private record AccountCoverageControl( + UUID accountId, + String state, + BigInteger epoch, + UUID currentOperationId, + BigInteger currentOperationFence, + UUID accountAdmissionFence, + UUID historicalAccountAdmissionFence, + UUID coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger coverageGeneration, + CanonicalGameplayAccountCoverageEvidence evidence) {} + private static void requireOne(int changed, String message) { if (changed != 1) { throw conflict(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 index eb363cd188..66618574f1 100644 --- 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 @@ -10,7 +10,7 @@ import java.util.Set; import java.util.TreeSet; import java.util.UUID; -import java.util.regex.Pattern; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventorySnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationReadback; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; @@ -25,16 +25,14 @@ /** * 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. + * not contain an active-session serializer or delete path. Only the exact canonical Account issuer + * generation projection key 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)); @@ -178,7 +176,8 @@ private Set scanConnection( 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"); + throw conflict( + "Target Redis inventory contains an unsupported issuer identity key; preserve legacy UUID issuer keys for explicit recovery"); } visited++; if (visited > limits.maxVisitedKeys()) { @@ -305,19 +304,7 @@ private String decodeKey(byte[] serializedKey) { } 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; - } + return (ISSUER_GENERATION_PREFIX + GameSessionAccountDelegationProfile.ISSUER).equals(key); } private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java new file mode 100644 index 0000000000..7f7b2c1d95 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -0,0 +1,941 @@ +package net.firedevops.firemud.gamesession.repository; + +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.security.MessageDigest; +import java.security.SecureRandom; +import java.security.Signature; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashSet; +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 java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered Game Session adapter that verifies a protected current-incarnation observation. + * + *

This is a LOCAL current-read proof only. It does not implement the Redis reset challenge, + * accepted post-reset attestation lifecycle, barrier installation, OPEN authorization, or + * admission. Production source, custody, and key provisioning are intentionally absent. + */ +final class CanonicalGameplayProtectedIncarnationReceiver { + private static final String OBSERVATION_SCHEMA = "firemud.gs.protected-incarnation-read/v1"; + private static final String INCARNATION_BINDING_SCHEMA = + "firemud.gs.protected-incarnation-binding/v1"; + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "attestorBinding", + "attestorKeyId", + "acceptedAttestationDigest", + "observationNonce", + "observationIssuedAtEpochMillis", + "observationObservedAtEpochMillis", + "observationExpiresAtEpochMillis", + "owner", + "target", + "targetDeploymentEvidence", + "coordOpsRoAclDigest", + "coordRedisConfigObservedDigest"); + private static final Set OWNER_FIELDS = + Set.of( + "operationId", + "requestId", + "accountId", + "operationFence", + "plannedAccountAdmissionFence", + "inventorySnapshotRevision", + "cohortDigest", + "barrierTargetDigest"); + private static final Set TARGET_FIELDS = + Set.of( + "targetOrdinal", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "workloadNamespace", + "allocationVersion"); + private static final Set EVIDENCE_FIELDS = + Set.of( + "deploymentIdentity", + "deploymentGeneration", + "canonicalNodeSet", + "redisBuildIdentity", + "luaScriptRegistryVersion", + "luaScriptRegistryDigest", + "startupState", + "bootGeneration", + "startupGeneration", + "storageGeneration", + "aofGeneration"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final CanonicalGameplayAccountAdmissionBarrierRepository intentRepository; + private final CanonicalGameplayTenantGameplayTagRepository tenantTagRepository; + private final ProtectedObservationChannel observationChannel; + private final TrustedConfiguration trustedConfiguration; + private final Clock clock; + private final SecureRandom secureRandom; + + CanonicalGameplayProtectedIncarnationReceiver( + CanonicalGameplayAccountAdmissionBarrierRepository intentRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, + ProtectedObservationChannel observationChannel, + TrustedConfiguration trustedConfiguration, + Clock clock) { + this( + intentRepository, + tenantTagRepository, + observationChannel, + trustedConfiguration, + clock, + new SecureRandom()); + } + + CanonicalGameplayProtectedIncarnationReceiver( + CanonicalGameplayAccountAdmissionBarrierRepository intentRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, + ProtectedObservationChannel observationChannel, + TrustedConfiguration trustedConfiguration, + Clock clock, + SecureRandom secureRandom) { + this.intentRepository = intentRepository; + this.tenantTagRepository = tenantTagRepository; + this.observationChannel = observationChannel; + this.trustedConfiguration = trustedConfiguration; + this.clock = clock; + this.secureRandom = secureRandom; + } + + /** + * Reads current evidence for one REQUIRED frozen fence target. + * + *

The correlation nonce below is local to this bounded current observation. It is not the + * replacementVerificationChallenge nonce and never renews, consumes, or replaces that challenge. + */ + VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) { + requireNoAmbientTransaction(); + requireNonNil(operationId, "operationId"); + if (targetOrdinal < 0) { + throw new IllegalArgumentException("targetOrdinal must not be negative"); + } + requireAvailable(); + + CurrentContext before = loadCurrentContext(operationId, targetOrdinal); + long issuedAt = clock.millis(); + if (issuedAt <= 0L) { + throw new ObservationUnavailableException("Protected observation clock is unavailable"); + } + long expiresAt; + try { + expiresAt = Math.addExact(issuedAt, trustedConfiguration.observationTtlMillis()); + } catch (ArithmeticException overflow) { + throw new ObservationUnavailableException("Protected observation time window is invalid"); + } + byte[] nonceBytes = new byte[32]; + secureRandom.nextBytes(nonceBytes); + String nonce = Base64.getUrlEncoder().withoutPadding().encodeToString(nonceBytes); + ObservationRequest request = + new ObservationRequest( + nonce, + issuedAt, + expiresAt, + trustedConfiguration.attestorBinding(), + trustedConfiguration.acceptedAttestationDigest(), + before, + trustedConfiguration.expectedEvidence(), + trustedConfiguration.coordOpsRoAclDigest(), + trustedConfiguration.coordRedisConfigObservedDigest()); + + requireNoAmbientTransaction(); + SignedObservation signed; + try { + signed = observationChannel.observe(request); + } catch (ObservationUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException unavailable) { + throw new ObservationUnavailableException("Protected observation source is unavailable"); + } + requireNoAmbientTransaction(); + if (signed == null) { + throw new ObservationUnavailableException("Protected observation source returned no bytes"); + } + + VerifiedPayload payload = verifyObservation(signed, request, before); + CurrentContext after = loadCurrentContext(operationId, targetOrdinal); + if (!before.equals(after)) { + throw new ObservationRejectedException("Protected observation owner context changed"); + } + long now = clock.millis(); + if (now < issuedAt + || now >= expiresAt + || payload.observedAtEpochMillis() < issuedAt + || payload.observedAtEpochMillis() > now + || payload.expiresAtEpochMillis() != expiresAt) { + throw new ObservationRejectedException("Protected observation is expired or out of window"); + } + String incarnationDigest = incarnationDigest(trustedConfiguration); + return new VerifiedIncarnation( + before, + trustedConfiguration.acceptedAttestationDigest(), + trustedConfiguration.expectedEvidence(), + payload.observationNonce(), + issuedAt, + payload.observedAtEpochMillis(), + expiresAt, + payload.payloadDigest(), + incarnationDigest); + } + + private void requireAvailable() { + if (intentRepository == null + || tenantTagRepository == null + || observationChannel == null + || trustedConfiguration == null + || clock == null + || secureRandom == null + || trustedConfiguration.attestorBinding() == null + || trustedConfiguration.attestorBinding().isBlank() + || trustedConfiguration.trustedAttestorKeys().isEmpty() + || trustedConfiguration.expectedEvidence() == null + || trustedConfiguration.acceptedAttestationDigest() == null + || trustedConfiguration.coordOpsRoAclDigest() == null + || trustedConfiguration.coordRedisConfigObservedDigest() == null) { + throw new ObservationUnavailableException( + "Protected current-incarnation source or trust configuration is unavailable"); + } + } + + private CurrentContext loadCurrentContext(UUID operationId, long targetOrdinal) { + requireNoAmbientTransaction(); + CanonicalGameplayAccountAdmissionFenceIntent intent = + intentRepository.readCurrentFenceIntent(operationId); + if (!operationId.equals(intent.operationId()) + || intent.state() + != CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT) { + throw new ObservationRejectedException("Protected observation intent is not current"); + } + List matches = + intent.barrierTargets().stream() + .filter(target -> target.ordinal() == targetOrdinal) + .toList(); + if (matches.size() != 1) { + throw new ObservationRejectedException("Protected observation target is not unique"); + } + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target = matches.get(0); + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + tenantTagRepository.assignmentForBarrierTarget(operationId, targetOrdinal); + if (assignment.isBindingTransition() + || !operationId.equals(assignment.admissionFenceIntentOperationId()) + || !Long.valueOf(targetOrdinal).equals(assignment.barrierTargetOrdinal()) + || !intent.accountId().equals(assignment.accountId()) + || !target.tenantId().equals(assignment.tenantId()) + || !target.playableStateNamespaceId().equals(assignment.playableStateNamespaceId())) { + throw new ObservationRejectedException( + "Protected observation target differs from current SQL and tenant mapping"); + } + CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); + return new CurrentContext( + intent.operationId(), + intent.requestId(), + intent.accountId(), + intent.operationFence().toString(), + intent.plannedAccountAdmissionFence(), + intent.inventorySnapshotRevision().toString(), + intent.cohortDigest(), + intent.barrierTargetDigest(), + targetOrdinal, + target.tenantId(), + target.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + assignment.workloadNamespace(), + assignment.allocationVersion()); + } + + private VerifiedPayload verifyObservation( + SignedObservation signed, ObservationRequest request, CurrentContext expected) { + validateObservationBounds(signed); + byte[] payloadBytes = signed.payloadBytes(); + byte[] signatureBytes = signed.signatureBytes(); + String keyId = signed.keyId(); + if (keyId == null || !KEY_ID.matcher(keyId).matches()) { + throw new ObservationRejectedException("Protected observation key id is invalid"); + } + java.security.interfaces.RSAPublicKey publicKey = + trustedConfiguration.trustedAttestorKeys().get(keyId); + if (publicKey == null) { + throw new ObservationRejectedException("Protected observation key is not pinned"); + } + requireRsaKey(publicKey); + String payloadText = strictUtf8(payloadBytes); + JsonNode root; + byte[] canonical; + try { + root = JSON.readTree(payloadText); + canonical = Rfc8785CanonicalJson.canonicalizeUtf8(payloadText); + } catch (IOException | RuntimeException invalid) { + throw new ObservationRejectedException("Protected observation JSON is invalid"); + } + if (root == null || !root.isObject() || !Arrays.equals(payloadBytes, canonical)) { + throw new ObservationRejectedException("Protected observation JSON is not canonical"); + } + verifyDetachedSignature(publicKey, canonical, signatureBytes); + + requireExactFields(root, ROOT_FIELDS); + requireText(root, "schema", OBSERVATION_SCHEMA); + requireText(root, "attestorBinding", trustedConfiguration.attestorBinding()); + requireText(root, "attestorKeyId", keyId); + requireText(root, "acceptedAttestationDigest", request.acceptedAttestationDigest()); + requireText(root, "observationNonce", request.nonce()); + long issuedAt = requiredPositiveLong(root, "observationIssuedAtEpochMillis"); + long observedAt = requiredPositiveLong(root, "observationObservedAtEpochMillis"); + long expiresAt = requiredPositiveLong(root, "observationExpiresAtEpochMillis"); + if (issuedAt != request.issuedAtEpochMillis() + || expiresAt != request.expiresAtEpochMillis() + || observedAt < issuedAt + || observedAt > expiresAt) { + throw new ObservationRejectedException("Protected observation timing differs from request"); + } + + JsonNode owner = requiredObject(root, "owner"); + requireExactFields(owner, OWNER_FIELDS); + requireText(owner, "operationId", expected.operationId().toString()); + requireText(owner, "requestId", expected.requestId().toString()); + requireText(owner, "accountId", expected.accountId().toString()); + requireText(owner, "operationFence", expected.operationFence()); + requireText( + owner, "plannedAccountAdmissionFence", expected.plannedAccountAdmissionFence().toString()); + requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); + requireText(owner, "cohortDigest", expected.cohortDigest()); + requireText(owner, "barrierTargetDigest", expected.barrierTargetDigest()); + + JsonNode target = requiredObject(root, "target"); + requireExactFields(target, TARGET_FIELDS); + if (requiredNonNegativeLong(target, "targetOrdinal") != expected.targetOrdinal() + || requiredPositiveLong(target, "allocationVersion") != expected.allocationVersion()) { + throw new ObservationRejectedException("Protected observation target ordinal differs"); + } + requireText(target, "tenantId", expected.tenantId().toString()); + requireText(target, "playableStateNamespaceId", expected.playableStateNamespaceId().toString()); + requireText(target, "tenantGameplayTag", expected.tenantGameplayTag()); + requireText(target, "workloadNamespace", expected.workloadNamespace()); + + requireEvidence(requiredObject(root, "targetDeploymentEvidence")); + requireText(root, "coordOpsRoAclDigest", trustedConfiguration.coordOpsRoAclDigest()); + requireText( + root, + "coordRedisConfigObservedDigest", + trustedConfiguration.coordRedisConfigObservedDigest()); + return new VerifiedPayload(request.nonce(), observedAt, expiresAt, digest(payloadBytes)); + } + + private void validateObservationBounds(SignedObservation signed) { + if (signed == null + || signed.payloadBytes == null + || signed.signatureBytes == null + || signed.payloadBytes.length == 0 + || signed.signatureBytes.length == 0 + || (long) signed.payloadBytes.length + signed.signatureBytes.length + > trustedConfiguration.maxSignedBytes()) { + throw new ObservationRejectedException("Protected observation exceeds configured bounds"); + } + } + + private void requireEvidence(JsonNode evidence) { + requireExactFields(evidence, EVIDENCE_FIELDS); + ExpectedTargetDeploymentEvidence expected = trustedConfiguration.expectedEvidence(); + requireText(evidence, "deploymentIdentity", expected.deploymentIdentity()); + requireText(evidence, "deploymentGeneration", expected.deploymentGeneration()); + requireText(evidence, "redisBuildIdentity", expected.redisBuildIdentity()); + requireText(evidence, "luaScriptRegistryVersion", expected.luaScriptRegistryVersion()); + requireText(evidence, "luaScriptRegistryDigest", expected.luaScriptRegistryDigest()); + requireText(evidence, "startupState", expected.startupState()); + requireText(evidence, "bootGeneration", expected.bootGeneration()); + requireText(evidence, "startupGeneration", expected.startupGeneration()); + requireText(evidence, "storageGeneration", expected.storageGeneration()); + requireText(evidence, "aofGeneration", expected.aofGeneration()); + JsonNode nodes = evidence.get("canonicalNodeSet"); + if (nodes == null || !nodes.isArray() || nodes.size() > trustedConfiguration.maxNodes()) { + throw new ObservationRejectedException("Protected observation node set exceeds bounds"); + } + List observedNodes = new ArrayList<>(); + for (JsonNode node : nodes) { + if (!node.isTextual() || node.textValue().isBlank()) { + throw new ObservationRejectedException("Protected observation node set is malformed"); + } + observedNodes.add(node.textValue()); + } + if (observedNodes.isEmpty() + || new HashSet<>(observedNodes).size() != observedNodes.size() + || !isCanonicalNodeOrder(observedNodes) + || !expected.canonicalNodeSet().equals(observedNodes)) { + throw new ObservationRejectedException("Protected observation node set differs"); + } + } + + private static boolean isCanonicalNodeOrder(List nodes) { + List sorted = new ArrayList<>(nodes); + Collections.sort(sorted); + return sorted.equals(nodes); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Protected observation requires bounded SQL and remote phases"); + } + } + + 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 requireRsaKey(java.security.interfaces.RSAPublicKey key) { + if (!"RSA".equalsIgnoreCase(key.getAlgorithm()) || key.getModulus().bitLength() < 2048) { + throw new ObservationRejectedException("Pinned attestor key is not RSA-2048 or stronger"); + } + } + + private static void verifyDetachedSignature( + java.security.interfaces.RSAPublicKey key, byte[] payload, byte[] signatureBytes) { + try { + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(key); + verifier.update(payload); + if (!verifier.verify(signatureBytes)) { + throw new ObservationRejectedException("Protected observation signature is invalid"); + } + } catch (ObservationRejectedException rejected) { + throw rejected; + } catch (Exception invalid) { + throw new ObservationRejectedException("Protected observation signature is invalid"); + } + } + + 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 invalid) { + throw new ObservationRejectedException("Protected observation is not valid UTF-8"); + } + } + + private static JsonNode requiredObject(JsonNode parent, String field) { + JsonNode value = parent.get(field); + if (value == null || !value.isObject()) { + throw new ObservationRejectedException("Protected observation object is missing"); + } + return value; + } + + private static void requireExactFields(JsonNode object, Set expected) { + Set actual = new HashSet<>(); + object.propertyNames().forEach(actual::add); + if (!actual.equals(expected)) { + throw new ObservationRejectedException("Protected observation fields are not exact"); + } + } + + private static void requireText(JsonNode object, String field, String expected) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || !expected.equals(value.textValue())) { + throw new ObservationRejectedException("Protected observation context differs"); + } + } + + private static long requiredPositiveLong(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToLong() + || value.longValue() <= 0L) { + throw new ObservationRejectedException("Protected observation integer is invalid"); + } + return value.longValue(); + } + + private static long requiredNonNegativeLong(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null + || !value.isIntegralNumber() + || !value.canConvertToLong() + || value.longValue() < 0L) { + throw new ObservationRejectedException("Protected observation integer is invalid"); + } + return value.longValue(); + } + + private static String digest(byte[] payload) { + try { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(payload)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String incarnationDigest(TrustedConfiguration configuration) { + ExpectedTargetDeploymentEvidence evidence = configuration.expectedEvidence(); + Map targetEvidence = new LinkedHashMap<>(); + targetEvidence.put("deploymentIdentity", evidence.deploymentIdentity()); + targetEvidence.put("deploymentGeneration", evidence.deploymentGeneration()); + targetEvidence.put("canonicalNodeSet", evidence.canonicalNodeSet()); + targetEvidence.put("redisBuildIdentity", evidence.redisBuildIdentity()); + targetEvidence.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + targetEvidence.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + targetEvidence.put("startupState", evidence.startupState()); + targetEvidence.put("bootGeneration", evidence.bootGeneration()); + targetEvidence.put("startupGeneration", evidence.startupGeneration()); + targetEvidence.put("storageGeneration", evidence.storageGeneration()); + targetEvidence.put("aofGeneration", evidence.aofGeneration()); + + Map binding = new LinkedHashMap<>(); + binding.put("schema", INCARNATION_BINDING_SCHEMA); + binding.put("attestorBinding", configuration.attestorBinding()); + binding.put("acceptedAttestationDigest", configuration.acceptedAttestationDigest()); + binding.put("targetDeploymentEvidence", targetEvidence); + binding.put("coordOpsRoAclDigest", configuration.coordOpsRoAclDigest()); + binding.put("coordRedisConfigObservedDigest", configuration.coordRedisConfigObservedDigest()); + try { + String json = JSON.writeValueAsString(binding); + return digest(Rfc8785CanonicalJson.canonicalizeUtf8(json)); + } catch (IOException invalid) { + throw new IllegalStateException( + "Could not canonicalize trusted incarnation binding", invalid); + } + } + + /** Raw source output only. Constructing this value does not assert signature validity. */ + static final class SignedObservation { + private final String keyId; + private final byte[] payloadBytes; + private final byte[] signatureBytes; + + SignedObservation(String keyId, byte[] payloadBytes, byte[] signatureBytes) { + this.keyId = keyId; + this.payloadBytes = payloadBytes; + this.signatureBytes = signatureBytes; + } + + String keyId() { + return keyId; + } + + byte[] payloadBytes() { + return payloadBytes == null ? new byte[0] : payloadBytes.clone(); + } + + byte[] signatureBytes() { + return signatureBytes == null ? new byte[0] : signatureBytes.clone(); + } + } + + /** Trusted protected source abstraction; implementations return only signed bytes and key id. */ + @FunctionalInterface + interface ProtectedObservationChannel { + SignedObservation observe(ObservationRequest request); + } + + /** Receiver-created request; its nonce and times belong only to this current read. */ + static final class ObservationRequest { + private final String nonce; + private final long issuedAtEpochMillis; + private final long expiresAtEpochMillis; + private final String attestorBinding; + private final String acceptedAttestationDigest; + private final CurrentContext context; + private final ExpectedTargetDeploymentEvidence expectedEvidence; + private final String coordOpsRoAclDigest; + private final String coordRedisConfigObservedDigest; + + private ObservationRequest( + String nonce, + long issuedAtEpochMillis, + long expiresAtEpochMillis, + String attestorBinding, + String acceptedAttestationDigest, + CurrentContext context, + ExpectedTargetDeploymentEvidence expectedEvidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest) { + this.nonce = nonce; + this.issuedAtEpochMillis = issuedAtEpochMillis; + this.expiresAtEpochMillis = expiresAtEpochMillis; + this.attestorBinding = attestorBinding; + this.acceptedAttestationDigest = acceptedAttestationDigest; + this.context = context; + this.expectedEvidence = expectedEvidence; + this.coordOpsRoAclDigest = coordOpsRoAclDigest; + this.coordRedisConfigObservedDigest = coordRedisConfigObservedDigest; + } + + String nonce() { + return nonce; + } + + long issuedAtEpochMillis() { + return issuedAtEpochMillis; + } + + long expiresAtEpochMillis() { + return expiresAtEpochMillis; + } + + String attestorBinding() { + return attestorBinding; + } + + String acceptedAttestationDigest() { + return acceptedAttestationDigest; + } + + CurrentContext context() { + return context; + } + + ExpectedTargetDeploymentEvidence expectedEvidence() { + return expectedEvidence; + } + + String coordOpsRoAclDigest() { + return coordOpsRoAclDigest; + } + + String coordRedisConfigObservedDigest() { + return coordRedisConfigObservedDigest; + } + } + + /** Local immutable, manually configured verifier trust. No production provisioner is provided. */ + static final class TrustedConfiguration { + private final String attestorBinding; + private final String acceptedAttestationDigest; + private final Map trustedAttestorKeys; + private final ExpectedTargetDeploymentEvidence expectedEvidence; + private final String coordOpsRoAclDigest; + private final String coordRedisConfigObservedDigest; + private final int maxSignedBytes; + private final int maxNodes; + private final long observationTtlMillis; + + TrustedConfiguration( + String attestorBinding, + String acceptedAttestationDigest, + Map trustedAttestorKeys, + ExpectedTargetDeploymentEvidence expectedEvidence, + String coordOpsRoAclDigest, + String coordRedisConfigObservedDigest, + int maxSignedBytes, + int maxNodes, + Duration observationTtl) { + this.attestorBinding = attestorBinding; + this.acceptedAttestationDigest = acceptedAttestationDigest; + this.trustedAttestorKeys = + trustedAttestorKeys == null + ? Map.of() + : Collections.unmodifiableMap(new LinkedHashMap<>(trustedAttestorKeys)); + this.expectedEvidence = expectedEvidence; + this.coordOpsRoAclDigest = coordOpsRoAclDigest; + this.coordRedisConfigObservedDigest = coordRedisConfigObservedDigest; + if (attestorBinding == null + || attestorBinding.isBlank() + || acceptedAttestationDigest == null + || expectedEvidence == null + || coordOpsRoAclDigest == null + || coordRedisConfigObservedDigest == null) { + throw new ObservationUnavailableException( + "Protected observation trust binding is unavailable"); + } + if (!DIGEST.matcher(acceptedAttestationDigest).matches() + || !DIGEST.matcher(coordOpsRoAclDigest).matches() + || !DIGEST.matcher(coordRedisConfigObservedDigest).matches() + || maxSignedBytes <= 0 + || maxNodes <= 0 + || observationTtl == null + || observationTtl.isNegative() + || observationTtl.isZero()) { + throw new IllegalArgumentException("Protected observation trust configuration is invalid"); + } + try { + this.observationTtlMillis = observationTtl.toMillis(); + } catch (ArithmeticException overflow) { + throw new IllegalArgumentException("Observation TTL is outside finite millisecond bounds"); + } + if (this.observationTtlMillis <= 0) { + throw new IllegalArgumentException("Observation TTL must be positive in milliseconds"); + } + for (Map.Entry entry : + this.trustedAttestorKeys.entrySet()) { + if (entry.getKey() == null || !KEY_ID.matcher(entry.getKey()).matches()) { + throw new IllegalArgumentException("Pinned attestor key id is invalid"); + } + if (entry.getValue() == null) { + throw new IllegalArgumentException("Pinned attestor public key is missing"); + } + requireRsaKey(entry.getValue()); + } + if (expectedEvidence.canonicalNodeSet().size() > maxNodes) { + throw new IllegalArgumentException("Expected node set exceeds configured local bound"); + } + this.maxSignedBytes = maxSignedBytes; + this.maxNodes = maxNodes; + } + + String attestorBinding() { + return attestorBinding; + } + + String acceptedAttestationDigest() { + return acceptedAttestationDigest; + } + + Map trustedAttestorKeys() { + return trustedAttestorKeys; + } + + ExpectedTargetDeploymentEvidence expectedEvidence() { + return expectedEvidence; + } + + String coordOpsRoAclDigest() { + return coordOpsRoAclDigest; + } + + String coordRedisConfigObservedDigest() { + return coordRedisConfigObservedDigest; + } + + int maxSignedBytes() { + return maxSignedBytes; + } + + int maxNodes() { + return maxNodes; + } + + long observationTtlMillis() { + return observationTtlMillis; + } + } + + /** Exact independently configured target binding; never learned from the response. */ + record ExpectedTargetDeploymentEvidence( + String deploymentIdentity, + String deploymentGeneration, + List canonicalNodeSet, + String redisBuildIdentity, + String luaScriptRegistryVersion, + String luaScriptRegistryDigest, + String startupState, + String bootGeneration, + String startupGeneration, + String storageGeneration, + String aofGeneration) { + ExpectedTargetDeploymentEvidence { + requireConfiguredText(deploymentIdentity, "deploymentIdentity"); + requireConfiguredText(deploymentGeneration, "deploymentGeneration"); + canonicalNodeSet = List.copyOf(Objects.requireNonNull(canonicalNodeSet, "canonicalNodeSet")); + requireConfiguredText(redisBuildIdentity, "redisBuildIdentity"); + requireConfiguredText(luaScriptRegistryVersion, "luaScriptRegistryVersion"); + requireDigestValue(luaScriptRegistryDigest, "luaScriptRegistryDigest"); + requireConfiguredText(startupState, "startupState"); + requireConfiguredText(bootGeneration, "bootGeneration"); + requireConfiguredText(startupGeneration, "startupGeneration"); + requireConfiguredText(storageGeneration, "storageGeneration"); + requireConfiguredText(aofGeneration, "aofGeneration"); + if (canonicalNodeSet.isEmpty() + || canonicalNodeSet.stream().anyMatch(node -> node == null || node.isBlank()) + || new HashSet<>(canonicalNodeSet).size() != canonicalNodeSet.size() + || !isCanonicalNodeOrder(canonicalNodeSet)) { + throw new IllegalArgumentException("Expected node set must be nonempty and canonical"); + } + } + } + + private static void requireConfiguredText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(field + " is required in trusted configuration"); + } + } + + private static void requireDigestValue(String value, String field) { + if (!DIGEST.matcher(value == null ? "" : value).matches()) { + throw new IllegalArgumentException(field + " must be canonical SHA-256"); + } + } + + /** Current owner and exact target tuple obtained from the actual SQL owners. */ + record CurrentContext( + UUID operationId, + UUID requestId, + UUID accountId, + String operationFence, + UUID plannedAccountAdmissionFence, + String inventorySnapshotRevision, + String cohortDigest, + String barrierTargetDigest, + long targetOrdinal, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + String workloadNamespace, + int allocationVersion) {} + + private record VerifiedPayload( + String observationNonce, + long observedAtEpochMillis, + long expiresAtEpochMillis, + String payloadDigest) {} + + /** Opaque exact-context evidence produced only after signature and two current-owner reads. */ + static final class VerifiedIncarnation { + private final CurrentContext context; + private final String acceptedAttestationDigest; + private final ExpectedTargetDeploymentEvidence evidence; + private final String observationNonce; + private final long issuedAtEpochMillis; + private final long observedAtEpochMillis; + private final long expiresAtEpochMillis; + private final String payloadDigest; + private final String incarnationDigest; + + private VerifiedIncarnation( + CurrentContext context, + String acceptedAttestationDigest, + ExpectedTargetDeploymentEvidence evidence, + String observationNonce, + long issuedAtEpochMillis, + long observedAtEpochMillis, + long expiresAtEpochMillis, + String payloadDigest, + String incarnationDigest) { + this.context = Objects.requireNonNull(context); + this.acceptedAttestationDigest = Objects.requireNonNull(acceptedAttestationDigest); + this.evidence = Objects.requireNonNull(evidence); + this.observationNonce = Objects.requireNonNull(observationNonce); + this.issuedAtEpochMillis = issuedAtEpochMillis; + this.observedAtEpochMillis = observedAtEpochMillis; + this.expiresAtEpochMillis = expiresAtEpochMillis; + this.payloadDigest = Objects.requireNonNull(payloadDigest); + this.incarnationDigest = Objects.requireNonNull(incarnationDigest); + } + + UUID operationId() { + return context.operationId(); + } + + long targetOrdinal() { + return context.targetOrdinal(); + } + + UUID accountId() { + return context.accountId(); + } + + UUID tenantId() { + return context.tenantId(); + } + + UUID playableStateNamespaceId() { + return context.playableStateNamespaceId(); + } + + UUID plannedAccountAdmissionFence() { + return context.plannedAccountAdmissionFence(); + } + + String cohortDigest() { + return context.cohortDigest(); + } + + String operationFence() { + return context.operationFence(); + } + + String barrierTargetDigest() { + return context.barrierTargetDigest(); + } + + String tenantGameplayTag() { + return context.tenantGameplayTag(); + } + + String acceptedAttestationDigest() { + return acceptedAttestationDigest; + } + + ExpectedTargetDeploymentEvidence evidence() { + return evidence; + } + + String observationNonce() { + return observationNonce; + } + + long issuedAtEpochMillis() { + return issuedAtEpochMillis; + } + + long observedAtEpochMillis() { + return observedAtEpochMillis; + } + + long expiresAtEpochMillis() { + return expiresAtEpochMillis; + } + + String payloadDigest() { + return payloadDigest; + } + + String incarnationDigest() { + return incarnationDigest; + } + } + + static final class ObservationUnavailableException extends RuntimeException { + ObservationUnavailableException(String message) { + super(message); + } + } + + static final class ObservationRejectedException extends RuntimeException { + ObservationRejectedException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java new file mode 100644 index 0000000000..bdcdeb62a1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; + +/** Canonical tenant-tagged gameplay key construction from a persisted repository assignment. */ +public final class CanonicalGameplaySessionRedisKeys { + private CanonicalGameplaySessionRedisKeys() {} + + public static String session( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayBindingRef expectedBindingRef) { + requireBinding(assignment, expectedBindingRef); + return "session:game:{" + + tag(assignment) + + "}:" + + assignment.gameInstanceId() + + ":" + + assignment.sessionId(); + } + + public static String characterIndex( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayBindingRef expectedBindingRef) { + requireBinding(assignment, expectedBindingRef); + return "session:game:index:character:{" + + tag(assignment) + + "}:" + + assignment.playableStateNamespaceId() + + ":" + + assignment.characterId(); + } + + public static String accountTenantIndex( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayBindingRef expectedBindingRef) { + requireBinding(assignment, expectedBindingRef); + return "session:game:index:account-tenant:{" + tag(assignment) + "}:" + assignment.accountId(); + } + + public static String tenantIndex( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayBindingRef expectedBindingRef) { + requireBinding(assignment, expectedBindingRef); + return "session:game:index:tenant:{" + tag(assignment) + "}"; + } + + /** Builds the future shard-local CLOSED barrier key for an exact frozen SQL target. */ + public static String accountAdmissionBarrier( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { + Objects.requireNonNull(assignment, "assignment"); + if (assignment.isBindingTransition() || assignment.admissionFenceIntentOperationId() == null) { + throw new IllegalArgumentException( + "Account admission barrier keys require a persisted acquisition-intent target"); + } + return "session:game:account-admission:{" + + tag(assignment) + + "}:" + + assignment.accountId() + + ":" + + assignment.playableStateNamespaceId(); + } + + private static void requireBinding( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayBindingRef expectedBindingRef) { + Objects.requireNonNull(assignment, "assignment"); + Objects.requireNonNull(expectedBindingRef, "expectedBindingRef"); + CanonicalGameplayBindingRef assigned = assignment.bindingRef(); + if (!assignment.isBindingTransition() + || assigned == null + || !assigned.equals(expectedBindingRef) + || !assignment.tenantId().toString().equals(expectedBindingRef.tenantId())) { + throw new IllegalArgumentException( + "Canonical gameplay key bindingRef differs from the persisted tenant assignment"); + } + } + + private static String tag(CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { + String tag = assignment.tenantGameplayTag(); + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag(tag); + return tag; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java new file mode 100644 index 0000000000..9a34cf46f7 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -0,0 +1,484 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; + +/** + * Persists the opaque tenant tag used to co-locate canonical gameplay keys. + * + *

The assignment is topology only. It does not establish current admission, install a barrier, + * or grant permission to read or mutate a gameplay key. Each public lookup reloads its tenant from + * an owned durable source before it can reuse or create the immutable tag mapping. + */ +public final class CanonicalGameplayTenantGameplayTagRepository { + private static final String MAPPING = "game_session_canonical_tenant_gameplay_tag"; + private static final Set TRANSITION_STATES = + Set.of("PREPARED", "PROVISIONAL", "COMMITTED"); + private static final Set INVENTORY_STATES = + Set.of("CANDIDATE_PREPARED", "PROVISIONAL", "ACTIVE"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final String workloadNamespace; + private final int allocationVersion; + + public CanonicalGameplayTenantGameplayTagRepository( + DSLContext dsl, String workloadNamespace, int allocationVersion) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "A fixed valid Game Session workload namespace is required"); + } + if (allocationVersion <= 0) { + throw new IllegalArgumentException("allocationVersion must be positive"); + } + this.workloadNamespace = workloadNamespace; + this.allocationVersion = allocationVersion; + } + + /** Loads or allocates a mapping only for the persisted candidate of this exact transition. */ + public Assignment assignmentForTransition(UUID transitionId) { + requireNonNil(transitionId, "transitionId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BindingTarget source = loadBindingTarget(transaction, transitionId); + requireTenantClaim(transaction, source.tenantId()); + return resolveMapping( + transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); + }); + } + + /** + * Resolves one still-current V1027 acquisition-intent target. A REQUIRED row is only a durable + * target; returning its tag does not mean that a Redis barrier was written or read back. + */ + public Assignment assignmentForBarrierTarget(UUID operationId, long targetOrdinal) { + requireNonNil(operationId, "operationId"); + if (targetOrdinal < 0) { + throw new IllegalArgumentException("targetOrdinal must not be negative"); + } + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + Record lockedControl = + transaction.fetchOne( + "SELECT control.account_id" + + " FROM game_session_canonical_account_admission_fence_intent intent" + + " JOIN game_session_canonical_account_coverage_control control" + + " ON control.account_id = intent.account_id" + + " WHERE intent.operation_id = ?" + + " AND intent.intent_state = 'ACQUISITION_INTENT'" + + " AND control.state = 'ACQUISITION_INTENT'" + + " AND control.current_operation_id IS NULL" + + " AND control.current_fence_intent_id = intent.operation_id" + + " AND control.current_operation_fence = intent.operation_fence" + + " AND control.last_operation_fence = intent.operation_fence" + + " AND control.account_admission_fence = intent.planned_account_admission_fence" + + " AND control.inventory_snapshot_revision = intent.inventory_snapshot_revision" + + " AND control.coverage_fence IS NULL AND control.coverage_generation IS NULL" + + " FOR UPDATE OF control", + operationId); + if (lockedControl == null) { + throw conflict("The exact current acquisition-intent barrier target is unavailable"); + } + Record row = + transaction.fetchOne( + "SELECT target.operation_id, target.target_ordinal, target.account_id," + + " target.tenant_id, target.playable_state_namespace_id" + + " FROM game_session_canonical_account_admission_fence_intent_barrier_target target" + + " JOIN game_session_canonical_account_admission_fence_intent intent" + + " ON intent.operation_id = target.operation_id" + + " AND intent.account_id = target.account_id" + + " JOIN game_session_canonical_account_coverage_control control" + + " ON control.account_id = intent.account_id" + + " WHERE target.operation_id = ? AND target.target_ordinal = ?" + + " AND target.target_state = 'REQUIRED'" + + " AND intent.intent_state = 'ACQUISITION_INTENT'" + + " AND control.state = 'ACQUISITION_INTENT'" + + " AND control.current_operation_id IS NULL" + + " AND control.current_fence_intent_id = intent.operation_id" + + " AND control.current_operation_fence = intent.operation_fence" + + " AND control.last_operation_fence = intent.operation_fence" + + " AND control.account_admission_fence = intent.planned_account_admission_fence" + + " AND control.inventory_snapshot_revision = intent.inventory_snapshot_revision" + + " AND control.coverage_fence IS NULL AND control.coverage_generation IS NULL" + + " FOR SHARE OF target, intent", + operationId, + targetOrdinal); + if (row == null) { + throw conflict("The exact current acquisition-intent barrier target is unavailable"); + } + BarrierTarget source = + new BarrierTarget( + requiredUuid(row, "operation_id"), + requiredLong(row, "target_ordinal"), + requiredUuid(row, "account_id"), + requiredUuid(row, "tenant_id"), + requiredUuid(row, "playable_state_namespace_id")); + requireTenantClaim(transaction, source.tenantId()); + return resolveMapping( + transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); + }); + } + + /** + * Narrow package-private collision path for native database proof. The tenant still comes from + * the exact persisted transition; only the candidate output is controlled to exercise the global + * unique-tag conflict branch. + */ + Assignment assignmentForTransitionWithCandidate( + UUID transitionId, int candidateVersion, String candidateTag) { + requireNonNil(transitionId, "transitionId"); + requirePositive(candidateVersion, "candidateVersion"); + requireCanonicalTag(candidateTag); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BindingTarget source = loadBindingTarget(transaction, transitionId); + requireTenantClaim(transaction, source.tenantId()); + return resolveMapping(transaction, source, candidateVersion, candidateTag); + }); + } + + private BindingTarget loadBindingTarget(DSLContext transaction, UUID transitionId) { + Record row = + transaction.fetchOne( + "SELECT transition.transition_id, transition.tenant_id AS transition_tenant_id," + + " transition.playable_state_namespace_id AS transition_namespace_id," + + " transition.character_id AS transition_character_id," + + " transition.candidate_binding_ref, transition.candidate_binding_generation," + + " transition.candidate_account_index_fence AS transition_account_index_fence," + + " transition.issuer_reservation_id AS transition_reservation_id," + + " transition.inventory_revision AS transition_inventory_revision," + + " transition.status, inventory.binding_ref, inventory.account_id," + + " inventory.tenant_id AS inventory_tenant_id," + + " inventory.playable_state_namespace_id AS inventory_namespace_id," + + " inventory.character_id AS inventory_character_id, inventory.game_instance_id," + + " inventory.session_id, inventory.binding_generation, inventory.account_index_fence," + + " inventory.issuer_reservation_id AS inventory_reservation_id," + + " inventory.inventory_revision, inventory.lifecycle" + + " FROM game_session_canonical_binding_transition transition" + + " JOIN game_session_canonical_gameplay_binding_inventory inventory" + + " ON inventory.transition_id = transition.transition_id" + + " AND inventory.binding_ref = transition.candidate_binding_ref" + + " WHERE transition.transition_id = ? FOR UPDATE OF transition, inventory", + transitionId); + if (row == null) { + throw conflict("The exact durable canonical binding transition is unavailable"); + } + + UUID tenantId = requiredUuid(row, "transition_tenant_id"); + UUID namespaceId = requiredUuid(row, "transition_namespace_id"); + UUID characterId = requiredUuid(row, "transition_character_id"); + UUID inventoryTenantId = requiredUuid(row, "inventory_tenant_id"); + UUID inventoryNamespaceId = requiredUuid(row, "inventory_namespace_id"); + UUID inventoryCharacterId = requiredUuid(row, "inventory_character_id"); + UUID accountId = requiredUuid(row, "account_id"); + UUID gameInstanceId = requiredUuid(row, "game_instance_id"); + String sessionId = requiredString(row, "session_id"); + byte[] transitionRefBytes = requiredBytes(row, "candidate_binding_ref"); + byte[] inventoryRefBytes = requiredBytes(row, "binding_ref"); + String transitionState = requiredString(row, "status"); + String inventoryState = requiredString(row, "lifecycle"); + if (!tenantId.equals(inventoryTenantId) + || !namespaceId.equals(inventoryNamespaceId) + || !characterId.equals(inventoryCharacterId) + || !requiredUuid(row, "transition_account_index_fence") + .equals(requiredUuid(row, "account_index_fence")) + || !requiredUuid(row, "transition_reservation_id") + .equals(requiredUuid(row, "inventory_reservation_id")) + || !TRANSITION_STATES.contains(transitionState) + || !INVENTORY_STATES.contains(inventoryState) + || !transitionRefMatches( + transitionRefBytes, inventoryRefBytes, tenantId, gameInstanceId, sessionId) + || !requiredBigInteger(row, "candidate_binding_generation") + .equals(requiredBigInteger(row, "binding_generation")) + || !requiredBigInteger(row, "transition_inventory_revision") + .equals(requiredBigInteger(row, "inventory_revision"))) { + throw conflict( + "The persisted transition and candidate inventory do not form one exact target"); + } + + if (("PREPARED".equals(transitionState) && !"CANDIDATE_PREPARED".equals(inventoryState)) + || ("PROVISIONAL".equals(transitionState) && !"PROVISIONAL".equals(inventoryState)) + || ("COMMITTED".equals(transitionState) && !"ACTIVE".equals(inventoryState))) { + throw conflict("The durable transition and candidate inventory lifecycle disagree"); + } + + CanonicalGameplayBindingRef bindingRef = + CanonicalGameplayBindingRef.fromExactBytes(transitionRefBytes); + return new BindingTarget( + requiredUuid(row, "transition_id"), + accountId, + tenantId, + namespaceId, + characterId, + gameInstanceId, + sessionId, + bindingRef); + } + + private void requireTenantClaim(DSLContext transaction, UUID tenantId) { + Record row = + transaction.fetchOne( + "SELECT claim.association_kind" + + " FROM game_session_tenant_canonical_claim claim" + + " WHERE claim.target_namespace = ? AND claim.canonical_tenant_id = ?" + + " AND ((claim.association_kind = 'FRESH_SOURCE_BOUND' AND EXISTS (" + + " SELECT 1 FROM game_session_fresh_tenant_association fresh" + + " WHERE fresh.target_namespace = claim.target_namespace" + + " AND fresh.canonical_tenant_id = claim.canonical_tenant_id" + + " AND fresh.association_operation_id = claim.association_operation_id" + + " AND fresh.association_request_id = claim.association_request_id" + + " AND fresh.association_kind = claim.association_kind))" + + " OR (claim.association_kind = 'RETAINED_V8_1' AND EXISTS (" + + " SELECT 1 FROM game_session_retained_tenant_association retained" + + " WHERE retained.target_namespace = claim.target_namespace" + + " AND retained.canonical_tenant_id = claim.canonical_tenant_id" + + " AND retained.operation_id = claim.association_operation_id" + + " AND retained.association_request_id = claim.association_request_id)))", + workloadNamespace, + tenantId); + if (row == null) { + throw conflict( + "The durable tenant claim is not associated with this configured Game Session workload"); + } + } + + private Assignment resolveMapping( + DSLContext transaction, Target source, int candidateVersion, String candidateTag) { + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + MAPPING + + " WHERE tenant_id = ? FOR UPDATE", + source.tenantId()); + if (mapping == null) { + transaction.fetchOne( + "INSERT INTO " + + MAPPING + + " (tenant_id, allocation_version, tenant_gameplay_tag) VALUES (?, ?, ?)" + + " ON CONFLICT DO NOTHING RETURNING tenant_id", + source.tenantId(), + candidateVersion, + candidateTag); + mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + MAPPING + + " WHERE tenant_id = ? FOR UPDATE", + source.tenantId()); + } + if (mapping == null) { + throw conflict("A gameplay tag candidate is already owned by a different tenant"); + } + + Integer storedVersion = mapping.get("allocation_version", Integer.class); + String storedTag = mapping.get("tenant_gameplay_tag", String.class); + if (storedVersion == null || storedVersion <= 0) { + throw conflict("Persisted tenant gameplay tag allocation version is invalid"); + } + requireCanonicalTag(storedTag); + if (!tagFor(source.tenantId(), storedVersion).equals(storedTag)) { + throw conflict("Persisted tenant tag differs from its immutable tenant/version assignment"); + } + return new Assignment(source, workloadNamespace, storedVersion, storedTag); + } + + private static boolean transitionRefMatches( + byte[] transitionBytes, + byte[] inventoryBytes, + UUID tenantId, + UUID gameInstanceId, + String sessionId) { + if (!java.util.Arrays.equals(transitionBytes, inventoryBytes)) { + return false; + } + UUID parsedSession; + try { + parsedSession = UUID.fromString(sessionId); + } catch (IllegalArgumentException malformed) { + return false; + } + if (!parsedSession.toString().equals(sessionId) || NIL_UUID.equals(parsedSession)) { + return false; + } + CanonicalGameplayBindingRef persisted = + CanonicalGameplayBindingRef.fromExactBytes(transitionBytes); + return persisted.equals(CanonicalGameplayBindingRef.of(tenantId, gameInstanceId, sessionId)); + } + + private static String tagFor(UUID tenantId, int version) { + return "g" + version + "-" + tenantId.toString().replace("-", ""); + } + + static void requireCanonicalTag(String tag) { + if (tag == null + || tag.length() > 44 + || !tag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}") + || tag.indexOf('{') >= 0 + || tag.indexOf('}') >= 0 + || tag.indexOf(':') >= 0) { + throw conflict("Tenant gameplay tag is not a bounded canonical opaque value"); + } + } + + private static UUID requiredUuid(Record row, String name) { + UUID value = row.get(name, UUID.class); + if (value == null || NIL_UUID.equals(value)) { + throw conflict("Persisted canonical target has a missing or nil " + name); + } + return value; + } + + private static String requiredString(Record row, String name) { + String value = row.get(name, String.class); + if (value == null || value.isEmpty()) { + throw conflict("Persisted canonical target is missing " + name); + } + return value; + } + + private static byte[] requiredBytes(Record row, String name) { + byte[] value = row.get(name, byte[].class); + if (value == null || value.length == 0) { + throw conflict("Persisted canonical target is missing " + name); + } + return value; + } + + private static long requiredLong(Record row, String name) { + Long value = row.get(name, Long.class); + if (value == null || value < 0L) { + throw conflict("Persisted canonical target has an invalid " + name); + } + return value; + } + + private static java.math.BigInteger requiredBigInteger(Record row, String name) { + java.math.BigDecimal value = row.get(name, java.math.BigDecimal.class); + if (value == null || value.signum() <= 0) { + throw conflict("Persisted canonical target has an invalid " + name); + } + return value.toBigIntegerExact(); + } + + private static void requirePositive(int value, String name) { + if (value <= 0) { + 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 not be nil"); + } + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + private sealed interface Target permits BindingTarget, BarrierTarget { + UUID tenantId(); + + UUID accountId(); + + UUID namespaceId(); + } + + private record BindingTarget( + UUID sourceId, + UUID accountId, + UUID tenantId, + UUID namespaceId, + UUID characterId, + UUID gameInstanceId, + String sessionId, + CanonicalGameplayBindingRef bindingRef) + implements Target {} + + private record BarrierTarget( + UUID sourceId, long ordinal, UUID accountId, UUID tenantId, UUID namespaceId) + implements Target {} + + /** Owner-issued immutable mapping plus the exact SQL source needed by the key builder. */ + public static final class Assignment { + private final Target source; + private final String workloadNamespace; + private final int allocationVersion; + private final String tenantGameplayTag; + + private Assignment( + Target source, String workloadNamespace, int allocationVersion, String tenantGameplayTag) { + this.source = Objects.requireNonNull(source, "source"); + this.workloadNamespace = Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + this.allocationVersion = allocationVersion; + this.tenantGameplayTag = Objects.requireNonNull(tenantGameplayTag, "tenantGameplayTag"); + } + + public UUID tenantId() { + return source.tenantId(); + } + + public UUID accountId() { + return source.accountId(); + } + + public UUID playableStateNamespaceId() { + return source.namespaceId(); + } + + public int allocationVersion() { + return allocationVersion; + } + + public String tenantGameplayTag() { + return tenantGameplayTag; + } + + public String workloadNamespace() { + return workloadNamespace; + } + + public boolean isBindingTransition() { + return source instanceof BindingTarget; + } + + public UUID transitionId() { + return source instanceof BindingTarget binding ? binding.sourceId() : null; + } + + public UUID admissionFenceIntentOperationId() { + return source instanceof BarrierTarget barrier ? barrier.sourceId() : null; + } + + public Long barrierTargetOrdinal() { + return source instanceof BarrierTarget barrier ? barrier.ordinal() : null; + } + + public UUID characterId() { + return source instanceof BindingTarget binding ? binding.characterId() : null; + } + + public UUID gameInstanceId() { + return source instanceof BindingTarget binding ? binding.gameInstanceId() : null; + } + + public String sessionId() { + return source instanceof BindingTarget binding ? binding.sessionId() : null; + } + + public CanonicalGameplayBindingRef bindingRef() { + return source instanceof BindingTarget binding ? binding.bindingRef() : null; + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/StoredClosedBarrierReceipt.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/StoredClosedBarrierReceipt.java new file mode 100644 index 0000000000..6dd72fd32b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/StoredClosedBarrierReceipt.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.time.OffsetDateTime; +import java.util.UUID; + +/** Plain historical SQL row view; it is not a current-incarnation or installed-fence capability. */ +record StoredClosedBarrierReceipt( + UUID operationId, + UUID requestId, + UUID accountId, + BigInteger operationFence, + UUID plannedAccountAdmissionFence, + BigInteger inventorySnapshotRevision, + String cohortDigest, + String barrierTargetDigest, + long targetOrdinal, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + String workloadNamespace, + int allocationVersion, + String barrierKey, + String barrierSchema, + String incarnationDigest, + String barrierState, + String acceptedAttestationDigest, + String barrierFieldsDigest, + String beforeSourcePayloadDigest, + long beforeObservationIssuedAtEpochMillis, + long beforeObservationObservedAtEpochMillis, + long beforeObservationExpiresAtEpochMillis, + String afterSourcePayloadDigest, + long afterObservationIssuedAtEpochMillis, + long afterObservationObservedAtEpochMillis, + long afterObservationExpiresAtEpochMillis, + OffsetDateTime createdAt) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountClosedBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountClosedBarrierRedisScriptContribution.java new file mode 100644 index 0000000000..b3f3e0fe4a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountClosedBarrierRedisScriptContribution.java @@ -0,0 +1,52 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive descriptor contribution for the one-key CLOSED account barrier script. */ +public final class CanonicalGameplayAccountClosedBarrierRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.account-admission-barrier-close.v1"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-account-admission-barrier-close.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-account-admission-barrier-close.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + var descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) { + throw unavailable(); + } + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account admission barrier descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountMemberRepairRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountMemberRepairRedisScriptContribution.java new file mode 100644 index 0000000000..f07d4faa58 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountMemberRepairRedisScriptContribution.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Passive owner-local registration for the binding-local account member projection script. */ +public final class CanonicalGameplayAccountMemberRepairRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.account-member-repair-add.v1"; + public static final String RESOURCE_PATH = "redis/lua/game-session-account-member-repair-add.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-account-member-repair-add.json"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + try (InputStream input = getClass().getResourceAsStream(DESCRIPTOR_PATH)) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(16 * 1024 + 1); + if (bytes.length == 0 || bytes.length > 16 * 1024) throw unavailable(); + var descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!ownerId().equals(descriptor.owner()) || !SCRIPT_ID.equals(descriptor.scriptId())) + throw unavailable(); + return List.of(descriptor); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Account member repair Redis descriptor is unavailable"); + } +} diff --git a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution index 901c7f3541..c9317c80ea 100644 --- a/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution +++ b/services/game-session-service/src/main/resources/META-INF/services/net.firedevops.firemud.common.redis.contracts.RedisScriptContribution @@ -1 +1,3 @@ net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisScriptContribution +net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution +net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountClosedBarrierRedisScriptContribution diff --git a/services/game-session-service/src/main/resources/db/migration/V1025__canonical_account_issuer_identity.sql b/services/game-session-service/src/main/resources/db/migration/V1025__canonical_account_issuer_identity.sql new file mode 100644 index 0000000000..82e4fbc32f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1025__canonical_account_issuer_identity.sql @@ -0,0 +1,237 @@ +-- Account is the only canonical JWT issuer. Retain the old UUID spellings as historical +-- evidence; this migration changes storage only and does not infer an Account issuer from them. +ALTER TABLE game_session_canonical_gameplay_binding_inventory + DROP CONSTRAINT chk_gs_canonical_gameplay_binding_inventory_identity; + +ALTER TABLE game_session_canonical_issuer_partition_reservation + DROP CONSTRAINT chk_gs_canonical_issuer_partition_reservation; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_inventory + DROP CONSTRAINT chk_gs_canonical_account_coverage_snapshot_inventory; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_reservation + DROP CONSTRAINT chk_gs_canonical_account_coverage_snapshot_reservation; + +ALTER TABLE game_session_canonical_gameplay_binding_inventory + ALTER COLUMN issuer_id TYPE character varying(64) + -- [jooq ignore start] + USING issuer_id::text + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_issuer_partition_reservation + ALTER COLUMN issuer_id TYPE character varying(64) + -- [jooq ignore start] + USING issuer_id::text + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_inventory + ALTER COLUMN issuer_id TYPE character varying(64) + -- [jooq ignore start] + USING issuer_id::text + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_transition + ALTER COLUMN candidate_issuer_id TYPE character varying(64) + -- [jooq ignore start] + USING candidate_issuer_id::text + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_reservation + ALTER COLUMN issuer_id TYPE character varying(64) + -- [jooq ignore start] + USING issuer_id::text + -- [jooq ignore stop] +; + +-- Keep the prior identity/state predicates in place. The non-nil check still applies to the +-- retained UUID spelling; the separate NOT VALID checks below gate every new or changed row on +-- the exact Account issuer while leaving unproven historical rows untouched. +ALTER TABLE game_session_canonical_gameplay_binding_inventory + ADD 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' + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + -- [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); + +ALTER TABLE game_session_canonical_issuer_partition_reservation + ADD 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' + 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 + -- [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); + +ALTER TABLE game_session_canonical_account_coverage_snapshot_inventory + ADD 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' + 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))); + +ALTER TABLE game_session_canonical_account_coverage_snapshot_reservation + ADD 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' + 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); + +-- NOT VALID preserves the historical UUID text without admitting it as an Account issuer. +-- PostgreSQL still checks each new or changed row against these exact issuer predicates. +ALTER TABLE game_session_canonical_gameplay_binding_inventory + ADD CONSTRAINT chk_gs_gameplay_inventory_account_issuer + CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C") + -- [jooq ignore start] + NOT VALID + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_issuer_partition_reservation + ADD CONSTRAINT chk_gs_issuer_reservation_account_issuer + CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C") + -- [jooq ignore start] + NOT VALID + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_inventory + ADD CONSTRAINT chk_gs_snapshot_inventory_account_issuer + CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C") + -- [jooq ignore start] + NOT VALID + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_transition + ADD CONSTRAINT chk_gs_snapshot_transition_account_issuer + CHECK ( + candidate_issuer_id COLLATE "C" + = 'firemud-account-service'::character varying COLLATE "C") + -- [jooq ignore start] + NOT VALID + -- [jooq ignore stop] +; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_reservation + ADD CONSTRAINT chk_gs_snapshot_reservation_account_issuer + CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C") + -- [jooq ignore start] + NOT VALID + -- [jooq ignore stop] +; diff --git a/services/game-session-service/src/main/resources/db/migration/V1026__binding_local_account_member_repair.sql b/services/game-session-service/src/main/resources/db/migration/V1026__binding_local_account_member_repair.sql new file mode 100644 index 0000000000..e626be9e15 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1026__binding_local_account_member_repair.sql @@ -0,0 +1,184 @@ +-- Ordinary NEW bindings in NO_ACTIVE_ACCOUNT_WIDE_FLOW can complete only their exact member +-- obligation. The new acknowledgement is binding-local and never writes account-wide coverage. + +ALTER TABLE game_session_canonical_binding_account_index_obligation + DROP CONSTRAINT chk_gs_canonical_binding_account_index_obligation; + +ALTER TABLE game_session_canonical_binding_account_index_obligation + DROP CONSTRAINT chk_gs_canonical_binding_account_index_projection; + +ALTER TABLE game_session_canonical_binding_account_index_obligation + ADD 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 IN ('REQUIRED', 'ACKNOWLEDGED') + AND inventory_revision > 0 + AND (status = 'REQUIRED' + OR (status = 'ACKNOWLEDGED' + AND obligation_ordinal = 0 + AND action = 'ADD_OR_RETAIN' + AND execution_phase = 'BEFORE_FINAL_CAS' + AND projection_state = 'PRESENT_AWAITING_COVERAGE' + AND projection_member IS NOT NULL + AND projection_inventory_revision IS NOT NULL + AND projection_inventory_revision > 0))); + +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 IN ('REQUIRED', 'ACKNOWLEDGED') + 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)); + +ALTER TABLE game_session_canonical_account_coverage_snapshot_obligation + DROP CONSTRAINT chk_gs_canonical_account_coverage_snapshot_obligation; + +ALTER TABLE game_session_canonical_account_coverage_snapshot_obligation + ADD 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 IN ('REQUIRED', 'ACKNOWLEDGED') + 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_member_repair_control ( + account_id uuid NOT NULL, + last_operation_fence numeric NOT NULL DEFAULT 0, + last_coverage_generation numeric NOT NULL DEFAULT 0, + CONSTRAINT pk_gs_canonical_account_member_repair_control PRIMARY KEY (account_id), + CONSTRAINT fk_gs_canonical_account_member_repair_control_account + FOREIGN KEY (account_id) + REFERENCES game_session_canonical_account_coverage_control (account_id), + CONSTRAINT chk_gs_canonical_account_member_repair_control CHECK ( + account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND last_operation_fence >= 0 + AND last_coverage_generation >= 0) +); + +CREATE TABLE game_session_canonical_account_member_repair_operation ( + operation_id uuid NOT NULL, + transition_id uuid NOT NULL, + obligation_ordinal integer NOT NULL, + operation_fence numeric NOT NULL, + coverage_fence uuid NOT NULL, + inventory_snapshot_revision numeric 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, + original_action character varying(16) NOT NULL, + original_expected_prior_generation numeric, + original_execution_phase character varying(24) NOT NULL, + original_status character varying(16) NOT NULL, + original_inventory_revision numeric NOT NULL, + original_projection_state character varying(32) NOT NULL, + original_projection_member text, + original_projection_inventory_revision numeric, + desired_action character varying(16) NOT NULL, + member text NOT NULL, + account_control_state character varying(32) NOT NULL, + account_control_epoch numeric NOT NULL, + status character varying(16) NOT NULL DEFAULT 'PENDING', + coverage_generation numeric, + readback_state character varying(16), + readback_member text, + completed_inventory_revision numeric, + 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_member_repair_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_canonical_account_member_repair_transition + UNIQUE (transition_id, obligation_ordinal), + CONSTRAINT uq_gs_canonical_account_member_repair_fence + UNIQUE (account_id, operation_fence), + CONSTRAINT fk_gs_canonical_account_member_repair_transition + FOREIGN KEY (transition_id) + REFERENCES game_session_canonical_binding_transition (transition_id), + CONSTRAINT fk_gs_canonical_account_member_repair_obligation + FOREIGN KEY (transition_id, obligation_ordinal) + REFERENCES game_session_canonical_binding_account_index_obligation + (transition_id, obligation_ordinal), + CONSTRAINT fk_gs_canonical_account_member_repair_control + FOREIGN KEY (account_id) + REFERENCES game_session_canonical_account_member_repair_control (account_id), + CONSTRAINT chk_gs_canonical_account_member_repair_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND operation_id <> transition_id + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND obligation_ordinal = 0 + AND operation_fence > 0 + AND coverage_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND coverage_fence <> operation_id + AND coverage_fence <> transition_id + AND inventory_snapshot_revision > 0 + AND octet_length(binding_ref) > 0 + 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 <> account_index_fence + AND original_action = 'ADD_OR_RETAIN' + AND original_expected_prior_generation IS NULL + AND original_execution_phase = 'BEFORE_FINAL_CAS' + AND original_status = 'REQUIRED' + AND original_inventory_revision > 0 + AND original_inventory_revision <= inventory_snapshot_revision + AND ((original_projection_state = 'REQUIRED' + AND original_projection_member IS NULL + AND original_projection_inventory_revision IS NULL) + OR (original_projection_state = 'PRESENT_AWAITING_COVERAGE' + AND original_projection_member IS NOT NULL + AND original_projection_inventory_revision IS NOT NULL + AND original_projection_inventory_revision > 0 + AND original_projection_inventory_revision <= original_inventory_revision)) + AND desired_action = 'ADD_OR_RETAIN' + AND length(member) > 0 + AND account_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND account_control_epoch >= 0 + AND ((status = 'PENDING' + AND coverage_generation IS NULL + AND readback_state IS NULL + AND readback_member IS NULL + AND completed_inventory_revision IS NULL) + OR (status = 'ACKNOWLEDGED' + AND coverage_generation IS NOT NULL + AND coverage_generation > inventory_snapshot_revision + AND readback_state IS NOT NULL + AND readback_state = 'PRESENT' + AND readback_member IS NOT NULL + AND readback_member = member + AND completed_inventory_revision IS NOT NULL + AND completed_inventory_revision > inventory_snapshot_revision))) +); + +CREATE INDEX ix_gs_canonical_account_member_repair_pending + ON game_session_canonical_account_member_repair_operation (account_id, status, operation_fence); diff --git a/services/game-session-service/src/main/resources/db/migration/V1027__canonical_account_admission_fence_intent.sql b/services/game-session-service/src/main/resources/db/migration/V1027__canonical_account_admission_fence_intent.sql new file mode 100644 index 0000000000..9ef3abf368 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1027__canonical_account_admission_fence_intent.sql @@ -0,0 +1,179 @@ +-- Acquisition intent closes Game Session NEW preparation while the exact tenant-local barriers +-- are installed by their separate owner. This record is not an installed barrier or coverage proof. + +CREATE TABLE game_session_canonical_account_admission_fence_intent ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + account_id uuid NOT NULL, + operation_fence numeric NOT NULL, + planned_account_admission_fence uuid NOT NULL, + inventory_snapshot_revision numeric 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, + intent_state character varying(32) NOT NULL, + cohort_row_count bigint NOT NULL, + cohort_digest character varying(71) NOT NULL, + barrier_target_count bigint NOT NULL, + barrier_target_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_account_admission_fence_intent PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_canonical_account_admission_fence_intent_operation_account + UNIQUE (operation_id, account_id), + CONSTRAINT uq_gs_canonical_account_admission_fence_intent_request + UNIQUE (account_id, request_id), + CONSTRAINT uq_gs_canonical_account_admission_fence_intent_fence + UNIQUE (account_id, operation_fence), + CONSTRAINT fk_gs_canonical_account_admission_fence_intent_account + FOREIGN KEY (account_id) + REFERENCES game_session_canonical_account_coverage_control (account_id), + CONSTRAINT chk_gs_canonical_account_admission_fence_intent 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 operation_fence > 0 + AND planned_account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND inventory_snapshot_revision > 0 + 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_canonical_inventory_revision <= inventory_snapshot_revision + AND legacy_namespace_index_readback_revision > 0 + AND legacy_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND intent_state = 'ACQUISITION_INTENT' + AND cohort_row_count >= 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$' + AND barrier_target_count >= 0 + AND barrier_target_digest ~ '^sha256:[0-9a-f]{64}$') +); + +ALTER TABLE game_session_canonical_account_coverage_control + ADD COLUMN current_fence_intent_id uuid; + +ALTER TABLE game_session_canonical_account_coverage_control + DROP CONSTRAINT chk_gs_canonical_account_coverage_control_state; + +ALTER TABLE game_session_canonical_account_coverage_control + ADD 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_fence_intent_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_fence_intent_id IS 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_fence_intent_id IS 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) + OR (state = 'ACQUISITION_INTENT' + AND current_operation_id IS NULL + AND current_fence_intent_id IS NOT NULL + AND current_operation_fence 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 NULL + AND inventory_snapshot_revision IS NOT NULL + AND inventory_snapshot_revision > 0 + AND coverage_generation IS NULL)) +); + +ALTER TABLE game_session_canonical_account_coverage_control + ADD CONSTRAINT fk_gs_canonical_account_coverage_control_fence_intent + FOREIGN KEY (current_fence_intent_id, account_id) + REFERENCES game_session_canonical_account_admission_fence_intent (operation_id, account_id); + +CREATE TABLE game_session_canonical_account_admission_fence_intent_cohort_row ( + operation_id uuid NOT NULL, + account_id uuid NOT NULL, + row_ordinal bigint NOT NULL, + source_kind character varying(40) NOT NULL, + source_key text NOT NULL, + tenant_id uuid, + playable_state_namespace_id uuid, + source_row jsonb NOT NULL, + CONSTRAINT pk_gs_canonical_account_admission_fence_intent_cohort_row + PRIMARY KEY (operation_id, row_ordinal), + -- [jooq ignore start] + CONSTRAINT uq_gs_canonical_account_admission_fence_intent_cohort_source + UNIQUE (operation_id, source_kind, source_key), + -- [jooq ignore stop] + CONSTRAINT fk_gs_canonical_account_admission_fence_intent_cohort_operation + FOREIGN KEY (operation_id, account_id) + REFERENCES game_session_canonical_account_admission_fence_intent (operation_id, account_id), + CONSTRAINT chk_gs_canonical_account_admission_fence_intent_cohort_row CHECK ( + row_ordinal >= 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_kind IN ( + 'BINDING', 'TRANSITION', 'RESERVATION', 'ACCOUNT_OBLIGATION', + 'ISSUER_OBLIGATION', 'REGION_OBLIGATION', 'MEMBER_REPAIR_CONTROL', + 'MEMBER_REPAIR_OPERATION') + AND length(source_key) > 0 + AND ((tenant_id IS NULL AND playable_state_namespace_id IS NULL) + OR (tenant_id IS NOT NULL + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id IS NOT NULL + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid)) + AND jsonb_typeof(source_row) = 'object') +); + +CREATE TABLE game_session_canonical_account_admission_fence_intent_barrier_target ( + operation_id uuid NOT NULL, + account_id uuid NOT NULL, + target_ordinal bigint NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + target_state character varying(16) NOT NULL, + CONSTRAINT pk_gs_canonical_account_admission_fence_intent_barrier_target + PRIMARY KEY (operation_id, target_ordinal), + CONSTRAINT uq_gs_canonical_account_admission_fence_intent_barrier_scope + UNIQUE (operation_id, tenant_id, playable_state_namespace_id), + CONSTRAINT fk_gs_canonical_account_admission_fence_intent_barrier_operation + FOREIGN KEY (operation_id, account_id) + REFERENCES game_session_canonical_account_admission_fence_intent (operation_id, account_id), + CONSTRAINT chk_gs_canonical_account_admission_fence_intent_barrier_target CHECK ( + target_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 target_state = 'REQUIRED') +); + +ALTER TABLE game_session_canonical_account_admission_fence_intent_cohort_row + ADD CONSTRAINT fk_gs_canonical_account_admission_fence_intent_cohort_barrier_target + FOREIGN KEY (operation_id, tenant_id, playable_state_namespace_id) + REFERENCES game_session_canonical_account_admission_fence_intent_barrier_target + (operation_id, tenant_id, playable_state_namespace_id); diff --git a/services/game-session-service/src/main/resources/db/migration/V1028__canonical_tenant_gameplay_tag_mapping.sql b/services/game-session-service/src/main/resources/db/migration/V1028__canonical_tenant_gameplay_tag_mapping.sql new file mode 100644 index 0000000000..28f5536d4c --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1028__canonical_tenant_gameplay_tag_mapping.sql @@ -0,0 +1,35 @@ +-- Immutable tenant-to-tag assignments for tenant-local gameplay Redis key co-location. +-- The mapping provides topology only; it is not admission or storage-incarnation evidence. +CREATE TABLE game_session_canonical_tenant_gameplay_tag ( + tenant_id UUID NOT NULL, + allocation_version INTEGER NOT NULL, + tenant_gameplay_tag VARCHAR(44) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_canonical_tenant_gameplay_tag PRIMARY KEY (tenant_id), + CONSTRAINT uq_gs_canonical_tenant_gameplay_tag_value UNIQUE (tenant_gameplay_tag), + CONSTRAINT chk_gs_canonical_tenant_gameplay_tag CHECK ( + tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND allocation_version > 0 + AND tenant_gameplay_tag ~ '^g[1-9][0-9]{0,9}-[0-9a-f]{32}$' + AND octet_length(tenant_gameplay_tag) BETWEEN 35 AND 44) +); + +-- [jooq ignore start] +CREATE FUNCTION reject_gs_canonical_tenant_gameplay_tag_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Canonical tenant gameplay tag assignments are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER gs_canonical_tenant_gameplay_tag_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_tenant_gameplay_tag +FOR EACH ROW EXECUTE FUNCTION reject_gs_canonical_tenant_gameplay_tag_mutation(); + +CREATE TRIGGER gs_canonical_tenant_gameplay_tag_no_truncate +BEFORE TRUNCATE ON game_session_canonical_tenant_gameplay_tag +FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_canonical_tenant_gameplay_tag_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1029__canonical_account_closed_barrier_receipt.sql b/services/game-session-service/src/main/resources/db/migration/V1029__canonical_account_closed_barrier_receipt.sql new file mode 100644 index 0000000000..1945211907 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1029__canonical_account_closed_barrier_receipt.sql @@ -0,0 +1,120 @@ +-- This is immutable per-target evidence of a physical CLOSED readback as of two protected +-- observations. It does not advance ACQUISITION_INTENT or prove the barrier is currently installed. +ALTER TABLE game_session_canonical_account_admission_fence_intent_barrier_target + ADD CONSTRAINT uq_gs_admission_barrier_target_receipt_ref + UNIQUE (operation_id, target_ordinal, account_id, tenant_id, playable_state_namespace_id); + +CREATE TABLE game_session_canonical_account_closed_barrier_receipt ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + account_id uuid NOT NULL, + operation_fence numeric NOT NULL, + planned_account_admission_fence uuid NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + cohort_digest character varying(71) NOT NULL, + barrier_target_digest character varying(71) NOT NULL, + target_ordinal bigint NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + tenant_gameplay_tag character varying(44) NOT NULL, + workload_namespace character varying(63) NOT NULL, + allocation_version integer NOT NULL, + barrier_key text NOT NULL, + barrier_schema character varying(64) NOT NULL, + incarnation_digest character varying(71) NOT NULL, + barrier_state character varying(16) NOT NULL, + accepted_attestation_digest character varying(71) NOT NULL, + barrier_fields_digest character varying(71) NOT NULL, + before_source_payload_digest character varying(71) NOT NULL, + before_observation_issued_at_epoch_millis bigint NOT NULL, + before_observation_observed_at_epoch_millis bigint NOT NULL, + before_observation_expires_at_epoch_millis bigint NOT NULL, + after_source_payload_digest character varying(71) NOT NULL, + after_observation_issued_at_epoch_millis bigint NOT NULL, + after_observation_observed_at_epoch_millis bigint NOT NULL, + after_observation_expires_at_epoch_millis bigint NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_admission_closed_barrier_receipt + PRIMARY KEY (operation_id, target_ordinal), + CONSTRAINT fk_gs_admission_closed_receipt_intent + FOREIGN KEY (operation_id, account_id) + REFERENCES game_session_canonical_account_admission_fence_intent (operation_id, account_id), + CONSTRAINT fk_gs_admission_closed_receipt_target + FOREIGN KEY ( + operation_id, + target_ordinal, + account_id, + tenant_id, + playable_state_namespace_id) + REFERENCES game_session_canonical_account_admission_fence_intent_barrier_target ( + operation_id, + target_ordinal, + account_id, + tenant_id, + playable_state_namespace_id), + CONSTRAINT chk_gs_admission_closed_barrier_receipt 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 operation_id <> account_id + AND operation_id <> request_id + AND planned_account_admission_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND planned_account_admission_fence <> operation_id + AND planned_account_admission_fence <> request_id + AND planned_account_admission_fence <> account_id + AND operation_fence > 0 + AND inventory_snapshot_revision > 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$' + AND barrier_target_digest ~ '^sha256:[0-9a-f]{64}$' + AND target_ordinal >= 0 + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_gameplay_tag ~ '^g[1-9][0-9]{0,9}-[0-9a-f]{32}$' + AND length(tenant_gameplay_tag) BETWEEN 35 AND 44 + AND length(workload_namespace) BETWEEN 1 AND 63 + AND allocation_version > 0 + AND barrier_key = 'session:game:account-admission:{' || tenant_gameplay_tag || '}:' + || account_id::text || ':' || playable_state_namespace_id::text + AND barrier_schema = 'gs_account_admission_barrier/v1' + AND incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND barrier_state = 'CLOSED' + AND accepted_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + AND barrier_fields_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_source_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_observation_issued_at_epoch_millis > 0 + AND before_observation_observed_at_epoch_millis + >= before_observation_issued_at_epoch_millis + AND before_observation_expires_at_epoch_millis + > before_observation_observed_at_epoch_millis + AND after_source_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND after_observation_issued_at_epoch_millis + >= before_observation_issued_at_epoch_millis + AND after_observation_observed_at_epoch_millis + >= after_observation_issued_at_epoch_millis + AND after_observation_observed_at_epoch_millis + >= before_observation_observed_at_epoch_millis + AND after_observation_expires_at_epoch_millis + > after_observation_observed_at_epoch_millis) +); + +-- The service owner only inserts receipts. Retain the accepted physical postimage as immutable +-- historical evidence; a later installation retry still requires fresh protected readback. +-- [jooq ignore start] +CREATE FUNCTION reject_gs_canonical_account_closed_barrier_receipt_mutation() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Canonical CLOSED barrier receipts are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER gs_canonical_account_closed_barrier_receipt_immutable +BEFORE UPDATE OR DELETE ON game_session_canonical_account_closed_barrier_receipt +FOR EACH ROW EXECUTE FUNCTION reject_gs_canonical_account_closed_barrier_receipt_mutation(); + +CREATE TRIGGER gs_canonical_account_closed_barrier_receipt_no_truncate +BEFORE TRUNCATE ON game_session_canonical_account_closed_barrier_receipt +FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_canonical_account_closed_barrier_receipt_mutation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-close.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-close.lua new file mode 100644 index 0000000000..61b56d84e2 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-close.lua @@ -0,0 +1,129 @@ +-- Install or monotonically advance one exact tenant-local CLOSED account barrier. +-- One hash-tagged key only; this script never opens admission or touches the global account index. +local prefix = 'session:game:account-admission:' +local schemaValue = 'gs_account_admission_barrier/v1' +local fields = { + 'schema', 'accountId', 'tenantId', 'playableStateNamespaceId', 'tenantGameplayTag', + 'ownerOperationId', 'ownerFenceEpoch', 'incarnationDigest', 'state' +} +local maxDecimalBytes = 256 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positiveDecimal(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function nonnegativeDecimal(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and (value == '0' or string.match(value, '^[1-9][0-9]*$') ~= nil) +end + +local function decimalLess(left, right) + if #left ~= #right then return #left < #right end + for index = 1, #left do + local leftDigit = string.byte(left, index) + local rightDigit = string.byte(right, index) + if leftDigit ~= rightDigit then return leftDigit < rightDigit end + end + return false +end + +local function tag(value) + if type(value) ~= 'string' or #value > 44 then return false end + local version, opaque = string.match(value, '^g([1-9][0-9]*)%-([0-9a-f]+)$') + return version ~= nil and #version <= 10 and #opaque == 32 +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +if #KEYS ~= 1 or #ARGV ~= 9 then return -2 end +local schema = ARGV[1] +local accountId = ARGV[2] +local tenantId = ARGV[3] +local namespaceId = ARGV[4] +local gameplayTag = ARGV[5] +local ownerOperationId = ARGV[6] +local ownerFenceEpoch = ARGV[7] +local incarnationDigest = ARGV[8] +local state = ARGV[9] + +if schema ~= schemaValue or not uuid(accountId) or not uuid(tenantId) or not uuid(namespaceId) + or not tag(gameplayTag) or not uuid(ownerOperationId) or not positiveDecimal(ownerFenceEpoch) + or not digest(incarnationDigest) or state ~= 'CLOSED' then return -2 end +local expectedKey = prefix .. '{' .. gameplayTag .. '}:' .. accountId .. ':' .. namespaceId +if KEYS[1] ~= expectedKey then return -2 end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind == 'none' then + if redis.call('PTTL', KEYS[1]) ~= -2 then return -1 end + redis.call('HSET', KEYS[1], + fields[1], schema, + fields[2], accountId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], ownerOperationId, + fields[7], ownerFenceEpoch, + fields[8], incarnationDigest, + fields[9], 'CLOSED') + return 1 +end +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end + +local existing = redis.call('HGETALL', KEYS[1]) +if #existing ~= 18 then return -1 end +local values = {} +for index = 1, #existing, 2 do + local field = existing[index] + local value = existing[index + 1] + if #field > 32 or #value > maxDecimalBytes then return -1 end + if values[field] ~= nil then return -1 end + local known = false + for fieldIndex = 1, #fields do + if field == fields[fieldIndex] then known = true break end + end + if not known then return -1 end + values[field] = value +end +for fieldIndex = 1, #fields do + if values[fields[fieldIndex]] == nil then return -1 end +end + +local oldFence = values.ownerFenceEpoch +if values.schema ~= schemaValue or values.accountId ~= accountId or values.tenantId ~= tenantId + or values.playableStateNamespaceId ~= namespaceId or values.tenantGameplayTag ~= gameplayTag + or not uuid(values.ownerOperationId) + or (values.state == 'CLOSED' and not positiveDecimal(oldFence)) + or (values.state == 'OPEN' and not nonnegativeDecimal(oldFence)) + or not digest(values.incarnationDigest) + or (values.state ~= 'CLOSED' and values.state ~= 'OPEN') then return -1 end + +if oldFence == ownerFenceEpoch then + if values.ownerOperationId == ownerOperationId and values.incarnationDigest == incarnationDigest + and values.state == 'CLOSED' then return 2 end + return -3 +end +if not decimalLess(oldFence, ownerFenceEpoch) then return -3 end +if values.ownerOperationId == ownerOperationId then return -3 end + +redis.call('HSET', KEYS[1], + fields[1], schema, + fields[2], accountId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], ownerOperationId, + fields[7], ownerFenceEpoch, + fields[8], incarnationDigest, + fields[9], 'CLOSED') +return 3 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-account-member-repair-add.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-account-member-repair-add.lua new file mode 100644 index 0000000000..67e0925454 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-account-member-repair-add.lua @@ -0,0 +1,114 @@ +-- Binding-local ADD_OR_RETAIN on the one untagged account index key. +-- KEYS[1] account key; ARGV carries the pinned SQL operation tuple and exact member. +local prefix = 'session:game:index:account:' +local memberPrefix = 'accountIndexMember/v1:' +local maxRefBytes = 6144 +local maxMemberBytes = 8192 +local maxDecimalBytes = 256 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + if type(value) ~= 'string' or #value == 0 or #value > maxDecimalBytes + or not string.match(value, '^[1-9][0-9]*$') then return false end + return true +end + +local function nonnegative(value) + if value == '0' then return true end + return positive(value) +end + +local function readSegment(bytes, offset) + local start = offset + while offset <= #bytes do + local char = string.byte(bytes, offset) + if char < 48 or char > 57 then break end + offset = offset + 1 + end + if offset == start or offset > #bytes or string.byte(bytes, offset) ~= 58 then return nil end + if offset - start > 1 and string.byte(bytes, start) == 48 then return nil end + local lengthText = string.sub(bytes, start, offset - 1) + if #lengthText > 5 then return nil end + local length = tonumber(lengthText) + if not length or length < 0 or length > maxRefBytes or offset + length > #bytes then return nil end + local valueStart = offset + 1 + local valueEnd = offset + length + return string.sub(bytes, valueStart, valueEnd), valueEnd + 1 +end + +local function bindingRef(bytes, expectedTenantId) + if type(bytes) ~= 'string' or #bytes == 0 or #bytes > maxRefBytes then return false end + local domain, offset = readSegment(bytes, 1) + if domain ~= 'bindingRef/v1' or not offset then return false end + local tenant, afterTenant = readSegment(bytes, offset) + if not tenant or not afterTenant then return false end + local gameInstance, afterInstance = readSegment(bytes, afterTenant) + if not gameInstance or not afterInstance then return false end + local session, afterSession = readSegment(bytes, afterInstance) + if not session or not afterSession or afterSession ~= #bytes + 1 then return false end + return tenant == expectedTenantId and uuid(tenant) and uuid(gameInstance) and uuid(session) +end + +local function base64url(bytes) + local alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' + local output = {} + for index = 1, #bytes, 3 do + local first = string.byte(bytes, index) + local second = string.byte(bytes, index + 1) + local third = string.byte(bytes, index + 2) + local combined = first * 65536 + (second or 0) * 256 + (third or 0) + local a = math.floor(combined / 262144) % 64 + 1 + local b = math.floor(combined / 4096) % 64 + 1 + local c = math.floor(combined / 64) % 64 + 1 + local d = combined % 64 + 1 + output[#output + 1] = string.sub(alphabet, a, a) + output[#output + 1] = string.sub(alphabet, b, b) + if second then output[#output + 1] = string.sub(alphabet, c, c) end + if third then output[#output + 1] = string.sub(alphabet, d, d) end + end + return table.concat(output) +end + +if #KEYS ~= 1 or #ARGV ~= 12 then return -2 end +local accountId = ARGV[1] +local tenantId = ARGV[2] +local refBytes = ARGV[3] +local generation = ARGV[4] +local accountIndexFence = ARGV[5] +local member = ARGV[6] +local transitionId = ARGV[7] +local operationId = ARGV[8] +local operationFence = ARGV[9] +local coverageFence = ARGV[10] +local snapshotRevision = ARGV[11] +local accountControlEpoch = ARGV[12] + +if not uuid(accountId) or not uuid(tenantId) or not bindingRef(refBytes, tenantId) + or not positive(generation) or not uuid(accountIndexFence) + or not uuid(transitionId) or not uuid(operationId) or not positive(operationFence) + or not uuid(coverageFence) or not positive(snapshotRevision) + or not nonnegative(accountControlEpoch) + or operationId == transitionId or coverageFence == operationId + or coverageFence == transitionId or coverageFence == accountIndexFence then return -2 end + +local expectedMember = memberPrefix .. base64url(refBytes) .. ':' .. generation .. ':' .. accountIndexFence +if type(member) ~= 'string' or #member == 0 or #member > maxMemberBytes + or member ~= expectedMember then return -2 end +if KEYS[1] ~= prefix .. accountId then return -2 end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'none' and kind ~= 'set' then return -1 end +local ttl = redis.call('PTTL', KEYS[1]) +if kind == 'none' and ttl ~= -2 or kind == 'set' and ttl ~= -1 then return -1 end + +-- SADD is idempotent and adds only this exact generation/fence-qualified member. +-- It never removes, replaces, or enumerates other account members. +local added = redis.call('SADD', KEYS[1], member) +if added == 1 then return 1 end +return 2 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-close.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-close.json new file mode 100644 index 0000000000..d3e31109af --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-close.json @@ -0,0 +1,43 @@ +{ + "scriptId": "game-session.account-admission-barrier-close.v1", + "resourcePath": "redis/lua/game-session-account-admission-barrier-close.lua", + "sha256": "25044c5fbee57edba7158d993772dddb946f38c22f1545a3449b694ee5bb3197", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "accountAdmissionBarrier", + "ownedPrefix": "session:game:account-admission:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "schema"}, + {"name": "accountId"}, + {"name": "tenantId"}, + {"name": "playableStateNamespaceId"}, + {"name": "tenantGameplayTag"}, + {"name": "ownerOperationId"}, + {"name": "ownerFenceEpoch"}, + {"name": "incarnationDigest"}, + {"name": "state"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "CLOSED_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "CLOSED_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "CLOSED_ADVANCED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDS_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "STALE_OR_CONFLICTING_OWNER", "category": "STALE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "tailLossBehavior": "This tenant-local CLOSED barrier fails admission when missing or malformed. A CLOSED install is not OPEN authorization, an installed account-fence receipt, or coverage evidence. Reset-sensitive storage observations must be reverified before an owner retries the same durable operation. An AOF-retained barrier with the same operation and epoch but a changed stable incarnation is refused without mutation; a fresh observation does not authorize an in-place rewrite. The original intent remains unresolved and the target CLOSED until Game Session account-wide fenced recovery resolves replacement under the canonical reset/recovery contract. This local installer does not implement that replacement or intent settlement and never opens a barrier or touches the global account index.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-account-member-repair-add.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-member-repair-add.json new file mode 100644 index 0000000000..202ce9cf2c --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-member-repair-add.json @@ -0,0 +1,60 @@ +{ + "scriptId": "game-session.account-member-repair-add.v1", + "resourcePath": "redis/lua/game-session-account-member-repair-add.lua", + "sha256": "aae96f084121a4a8eb73e18203c08ab1a34efca2fdcbd36d526bedc091249423", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "accountIndex", + "ownedPrefix": "session:game:index:account:", + "hashTagDeclaration": "NOT_REQUIRED" + } + ], + "arguments": [ + {"name": "accountId"}, + {"name": "tenantId"}, + {"name": "canonicalBindingRefBytes"}, + {"name": "bindingGeneration"}, + {"name": "accountIndexFence"}, + {"name": "exactAccountIndexMember"}, + {"name": "transitionId"}, + {"name": "operationId"}, + {"name": "operationFence"}, + {"name": "coverageFence"}, + {"name": "inventorySnapshotRevision"}, + {"name": "accountControlEpoch"} + ], + "category": "SESSION_ACCOUNT_INDEX", + "outcomes": [ + { + "code": "MEMBER_ADDED", + "category": "SUCCESS", + "effect": "MUTATING" + }, + { + "code": "MEMBER_ALREADY_PRESENT", + "category": "REPLAY", + "effect": "NON_MUTATING" + }, + { + "code": "WRONG_KEY_TYPE_OR_EXPIRY", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + }, + { + "code": "INVALID_ARGUMENTS", + "category": "VALIDATION_FAILURE", + "effect": "NON_MUTATING" + } + ], + "resetSensitivity": "CLUSTER", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "tailLossBehavior": "This untagged account key is reset-sensitive and is never rebuilt by a binding-local operation. Region/tenant resets leave it untouched; cluster loss requires the complete account-wide durable inventory, owner-defined coverage, and exact member-set readback before release. A member projection is not authorization or whole-account coverage. Ambiguous or unavailable write/readback leaves the original durable obligation unresolved for exact retry.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java new file mode 100644 index 0000000000..784342800f --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java @@ -0,0 +1,541 @@ +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.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.EnumSet; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +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 net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +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.CanonicalGameplayLegacyMigrationReadback; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationSourceSnapshot; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationStorageIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +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 CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest { + 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 OTHER_ACCOUNT_ID = + UUID.fromString("12121212-1212-4212-8212-121212121212"); + 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 OTHER_TENANT_ID = + UUID.fromString("23232323-2323-4323-8323-232323232323"); + private static final UUID OTHER_NAMESPACE_ID = + UUID.fromString("34343434-3434-4434-8434-343434343434"); + 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"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void intentRetryRestartAndNewPrepareUseOneFrozenActualOwnerCohort() { + TestSchema testSchema = newTestSchema("gs_account_fence_retry_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + CanonicalGameplayBindingInventoryRepository inventory = + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + var first = prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var owner = new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()); + UUID requestId = UUID.randomUUID(); + + var intent = owner.beginFenceIntent(ACCOUNT_ID, requestId); + + assertThat(intent.state()) + .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT); + assertThat(intent.operationFence()).isEqualTo(BigInteger.ONE); + assertThat(intent.inventorySnapshotRevision()).isEqualTo(first.inventoryRevision()); + var currentByOperationId = owner.readCurrentFenceIntent(intent.operationId()); + assertThat(currentByOperationId.operationId()).isEqualTo(intent.operationId()); + assertThat(currentByOperationId.requestId()).isEqualTo(requestId); + assertThat(currentByOperationId.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertThat(intent.cohortRows()) + .extracting(CanonicalGameplayAccountAdmissionFenceIntent.CohortRow::kind) + .contains( + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.BINDING, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.TRANSITION, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.RESERVATION, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.ACCOUNT_OBLIGATION, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.ISSUER_OBLIGATION, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.REGION_OBLIGATION); + assertThat(intent.barrierTargets()) + .singleElement() + .satisfies( + target -> { + assertThat(target.tenantId()).isEqualTo(TENANT_ID); + assertThat(target.playableStateNamespaceId()).isEqualTo(NAMESPACE_ID); + }); + assertNoInstalledOrCoverageClaim(testSchema.dsl(), intent); + var originalCohortRow = intent.cohortRows().get(0); + assertThatThrownBy( + () -> + testSchema + .dsl() + .execute( + "INSERT INTO" + + " game_session_canonical_account_admission_fence_intent_cohort_row" + + " (operation_id, account_id, row_ordinal, source_kind, source_key," + + " tenant_id, playable_state_namespace_id, source_row)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + intent.operationId(), + intent.accountId(), + intent.cohortRows().size() + 1L, + originalCohortRow.kind().name(), + originalCohortRow.sourceKey(), + originalCohortRow.tenantId(), + originalCohortRow.playableStateNamespaceId(), + originalCohortRow.sourceRecordJson())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23505")); + var afterDuplicateCohortInsert = owner.readFenceIntent(ACCOUNT_ID, requestId); + assertThat(afterDuplicateCohortInsert.cohortRows()).hasSameSizeAs(intent.cohortRows()); + assertThat(afterDuplicateCohortInsert.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertThat(afterDuplicateCohortInsert.barrierTargetDigest()) + .isEqualTo(intent.barrierTargetDigest()); + assertCheckConstraintViolation( + testSchema.dsl(), + "UPDATE game_session_canonical_account_coverage_control" + + " SET current_operation_fence = NULL WHERE account_id = ?", + ACCOUNT_ID); + assertCheckConstraintViolation( + testSchema.dsl(), + "UPDATE game_session_canonical_account_coverage_control" + + " SET inventory_snapshot_revision = NULL WHERE account_id = ?", + ACCOUNT_ID); + var afterRejectedNulls = owner.readFenceIntent(ACCOUNT_ID, requestId); + assertThat(afterRejectedNulls.operationId()).isEqualTo(intent.operationId()); + assertThat(afterRejectedNulls.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertThat(afterRejectedNulls.barrierTargetDigest()).isEqualTo(intent.barrierTargetDigest()); + assertNoInstalledOrCoverageClaim(testSchema.dsl(), afterRejectedNulls); + + // A later unrelated account write advances the global clock but cannot replace this account's + // original frozen cohort or tenant/namespace target list. + prepare(inventory, OTHER_ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID, 3); + var restartedOwner = new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()); + var retried = restartedOwner.beginFenceIntent(ACCOUNT_ID, requestId); + var read = restartedOwner.readFenceIntent(ACCOUNT_ID, requestId); + + assertThat(retried.operationId()).isEqualTo(intent.operationId()); + assertThat(retried.operationFence()).isEqualTo(intent.operationFence()); + assertThat(retried.plannedAccountAdmissionFence()) + .isEqualTo(intent.plannedAccountAdmissionFence()); + assertThat(retried.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertThat(retried.barrierTargetDigest()).isEqualTo(intent.barrierTargetDigest()); + assertThat(read.operationId()).isEqualTo(intent.operationId()); + assertThat(read.cohortRows()).hasSameSizeAs(intent.cohortRows()); + assertThat(read.cohortDigest()).isEqualTo(intent.cohortDigest()); + assertNoInstalledOrCoverageClaim(testSchema.dsl(), read); + + var beforeRejectedPrepare = inventory.readSnapshot(); + assertThatThrownBy(() -> prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 2)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Account-fence acquisition intent blocks a new binding transition"); + assertThat(inventory.readSnapshot()).isEqualTo(beforeRejectedPrepare); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void intentCapturesEveryExistingTenantNamespaceForTheAccountOnly() { + TestSchema testSchema = newTestSchema("gs_account_fence_tenants_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + CanonicalGameplayBindingInventoryRepository inventory = + new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + prepare(inventory, ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID, 2); + prepare(inventory, OTHER_ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID, 3); + var owner = new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()); + + var intent = owner.beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); + var otherAccountIntent = owner.beginFenceIntent(OTHER_ACCOUNT_ID, UUID.randomUUID()); + + assertThat(intent.barrierTargets()) + .extracting( + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::tenantId, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::playableStateNamespaceId) + .containsExactly( + org.assertj.core.groups.Tuple.tuple(TENANT_ID, NAMESPACE_ID), + org.assertj.core.groups.Tuple.tuple(OTHER_TENANT_ID, OTHER_NAMESPACE_ID)); + assertThat(intent.cohortRows()) + .filteredOn( + row -> row.kind() == CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.BINDING) + .hasSize(2); + assertThat(otherAccountIntent.accountId()).isEqualTo(OTHER_ACCOUNT_ID); + assertThat(otherAccountIntent.barrierTargets()) + .singleElement() + .satisfies( + target -> { + assertThat(target.tenantId()).isEqualTo(OTHER_TENANT_ID); + assertThat(target.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); + }); + assertThat(otherAccountIntent.cohortRows()) + .filteredOn( + row -> row.kind() == CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.BINDING) + .hasSize(1); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void preparationRacingIntentIsEitherCapturedOrRefused() throws Exception { + TestSchema testSchema = newTestSchema("gs_account_fence_race_"); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var owner = new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()); + CountDownLatch start = new CountDownLatch(1); + Future prepareFuture = + executor.submit( + () -> { + start.await(); + return prepare(inventory, ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID, 2); + }); + Future intentFuture = + executor.submit( + () -> { + start.await(); + return owner.beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); + }); + start.countDown(); + + var intent = intentFuture.get(30, TimeUnit.SECONDS); + CanonicalGameplayBindingTransitionSnapshot racedPrepare = null; + try { + racedPrepare = prepareFuture.get(30, TimeUnit.SECONDS); + } catch (ExecutionException refusedAfterIntent) { + assertThat(refusedAfterIntent.getCause()) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining( + "Account-fence acquisition intent blocks a new binding transition"); + } + + if (racedPrepare != null) { + UUID racedTransitionId = racedPrepare.transitionId(); + assertThat(intent.cohortRows()) + .anySatisfy( + row -> assertThat(row.sourceRecordJson()).contains(racedTransitionId.toString())); + assertThat(intent.barrierTargets()) + .extracting( + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::tenantId, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget + ::playableStateNamespaceId) + .contains(org.assertj.core.groups.Tuple.tuple(OTHER_TENANT_ID, OTHER_NAMESPACE_ID)); + } + assertNoInstalledOrCoverageClaim(testSchema.dsl(), intent); + } finally { + executor.shutdownNow(); + dropSchema(testSchema.schema()); + } + } + + @Test + void missingPositiveControlAndUnverifiedLegacyDispositionCannotStartIntent() { + TestSchema testSchema = newTestSchema("gs_account_fence_missing_"); + try { + var owner = new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()); + // The owner refuses revision zero before looking up the account control row. Establish the + // actual complete-empty legacy disposition first so this assertion reaches the missing-row + // gate rather than failing at the earlier inventory-clock precondition. + establishActualLegacyDisposition(testSchema.dsl()); + + assertThatThrownBy(() -> owner.beginFenceIntent(ACCOUNT_ID, UUID.randomUUID())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Positive account-control row is missing"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition" + + " WHERE singleton_id = 1") + .get("disposition_state", String.class)) + .isEqualTo("VERIFIED"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT count(*) AS row_count FROM " + + "game_session_canonical_account_admission_fence_intent") + .get("row_count", Long.class)) + .isZero(); + + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_binding_legacy_disposition" + + " SET disposition_state = 'REQUIRED', cohort_id = NULL, owner_operation_id = NULL," + + " legacy_writer_fence = NULL, source_snapshot_revision = NULL," + + " canonical_inventory_revision = NULL, namespace_index_readback_revision = NULL," + + " evidence_digest = NULL WHERE singleton_id = 1"); + assertThatThrownBy(() -> owner.beginFenceIntent(ACCOUNT_ID, UUID.randomUUID())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("VERIFIED legacy-index migration disposition"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + ACCOUNT_ID) + .get("state", String.class)) + .isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT count(*) AS row_count FROM" + + " game_session_canonical_account_admission_fence_intent") + .get("row_count", Long.class)) + .isZero(); + } finally { + dropSchema(testSchema.schema()); + } + } + + private static void assertNoInstalledOrCoverageClaim( + DSLContext dsl, CanonicalGameplayAccountAdmissionFenceIntent intent) { + var control = + dsl.fetchSingle( + "SELECT state, current_operation_id, current_fence_intent_id," + + " current_operation_fence, account_admission_fence, coverage_fence," + + " coverage_generation FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + intent.accountId()); + assertThat(control.get("state", String.class)).isEqualTo("ACQUISITION_INTENT"); + assertThat(control.get("current_operation_id", UUID.class)).isNull(); + assertThat(control.get("current_fence_intent_id", UUID.class)).isEqualTo(intent.operationId()); + assertThat(control.get("current_operation_fence", BigDecimal.class).toBigIntegerExact()) + .isEqualTo(intent.operationFence()); + assertThat(control.get("account_admission_fence", UUID.class)) + .isEqualTo(intent.plannedAccountAdmissionFence()); + assertThat(control.get("coverage_fence", UUID.class)).isNull(); + assertThat(control.get("coverage_generation", BigDecimal.class)).isNull(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) AS row_count FROM" + + " game_session_canonical_account_coverage_operation" + + " WHERE account_id = ?", + intent.accountId()) + .get("row_count", Long.class)) + .isZero(); + } + + private static CanonicalGameplayBindingTransitionSnapshot prepare( + CanonicalGameplayBindingInventoryRepository repository, + UUID accountId, + UUID tenantId, + UUID namespaceId, + int number) { + UUID characterId = + UUID.nameUUIDFromBytes(("character-" + number).getBytes(StandardCharsets.UTF_8)); + UUID transitionId = + UUID.nameUUIDFromBytes(("transition-" + number).getBytes(StandardCharsets.UTF_8)); + UUID reservationId = + UUID.nameUUIDFromBytes(("reservation-" + number).getBytes(StandardCharsets.UTF_8)); + UUID reservationFence = + UUID.nameUUIDFromBytes(("reservation-fence-" + number).getBytes(StandardCharsets.UTF_8)); + UUID issuerCoverageOperationId = + UUID.nameUUIDFromBytes(("issuer-operation-" + number).getBytes(StandardCharsets.UTF_8)); + var candidate = + new CanonicalGameplayBindingIdentity( + accountId, + tenantId, + namespaceId, + characterId, + "SHARED", + GAME_INSTANCE_ID, + 23L, + UUID.nameUUIDFromBytes(("session-" + number).getBytes(StandardCharsets.UTF_8)) + .toString(), + REGION_ID, + BigInteger.valueOf(12), + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.valueOf(7), + BigInteger.valueOf(3), + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + reservationId, + reservationFence, + issuerCoverageOperationId, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + return repository.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), candidate, reservation, null, null)); + } + + private static void establishActualLegacyDisposition(DSLContext dsl) { + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); + UUID cohortId = UUID.randomUUID(); + UUID writerFence = UUID.randomUUID(); + var storageIdentity = + new CanonicalGameplayLegacyMigrationStorageIdentity( + "test-cluster-uid", + "test-namespace-uid", + "test-producer-pod-uid", + "test-container-id", + "test-node-uid", + "123456789", + 42L, + "test-postgres-volume-uid", + "test-redis-run-id", + "test-redis-volume-uid"); + var fencedCohort = + new CanonicalGameplayLegacyMigrationOwner.FencedCohort() { + @Override + public UUID cohortId() { + return cohortId; + } + + @Override + public UUID legacyWriterFence() { + return writerFence; + } + + @Override + public CanonicalGameplayLegacyMigrationStorageIdentity storageIdentity() { + return storageIdentity; + } + + @Override + public void requireStillFenced( + CanonicalGameplayLegacyMigrationStorageIdentity expectedIdentity) { + if (!storageIdentity.equals(expectedIdentity)) { + throw new IllegalStateException("Test fixture storage identity changed"); + } + } + }; + var owner = + new CanonicalGameplayLegacyMigrationOwner( + migration, + inventory, + () -> fencedCohort, + // Controlled complete-empty-source adapter: the actual legacy owner and SQL publisher + // run, while physical Redis/storage incarnation evidence remains outside this test. + ignored -> + 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()), + new CanonicalGameplayLegacyMigrationOwner.NamespaceIndexOwner() { + @Override + public void rebuildExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + CanonicalGameplayLegacyMigrationSourceSnapshot source, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + assertThat(canonical.transitions()).isEmpty(); + assertThat(canonical.reservations()).isEmpty(); + } + + @Override + public CanonicalGameplayLegacyMigrationReadback readBackExact( + CanonicalGameplayLegacyMigrationOwner.FencedCohort ignoredCohort, + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventorySnapshot + canonical) { + assertThat(canonical.bindings()).isEmpty(); + return new CanonicalGameplayLegacyMigrationReadback( + List.of(), List.of(), List.of(), List.of()); + } + }); + assertThat(owner.migrate().state()) + .isEqualTo(CanonicalGameplayLegacyMigrationOperation.State.VERIFIED); + } + + private static TestSchema newTestSchema(String prefix) { + String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new TestSchema(schema, dsl); + } + + 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 (Connection connection = dataSource("public").getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } catch (SQLException failure) { + throw new IllegalStateException("Could not drop the owned test schema " + schema, failure); + } + } + + private static void assertCheckConstraintViolation( + DSLContext dsl, String statement, Object... values) { + assertThatThrownBy(() -> dsl.execute(statement, values)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + } + + private record TestSchema(String schema, DSLContext dsl) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionIntentMigrationPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionIntentMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..c037fde7dd --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionIntentMigrationPostgresIntegrationTest.java @@ -0,0 +1,294 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +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-only retained-row proof for V1027 acquisition intent and the V1028 continuation. + * Seeded ACTIVE/HISTORICAL owners are controlled historical inputs, not producer-authority proofs. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayAccountAdmissionIntentMigrationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String CONTROL = "game_session_canonical_account_coverage_control"; + private static final String COVERAGE_OPERATION = + "game_session_canonical_account_coverage_operation"; + private static final String LEGACY_DIGEST = "sha256:" + "1".repeat(64); + private static final String MEMBER_DIGEST = "sha256:" + "2".repeat(64); + private static final OffsetDateTime RETAINED_UPDATED_AT = + OffsetDateTime.parse("2026-10-26T00:00:00Z"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void v1027AndV1028PreserveRetainedV31ControlPostimagesWithoutInferringIntent() { + String schema = + "gs_admission_intent_migration_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + try { + Flyway throughV1026 = flyway(dataSource, schema, MigrationVersion.fromVersion("1026")); + throughV1026.migrate(); + throughV1026.validate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + assertLatestMigration(dsl, "1026"); + + RetainedControls controls = seedRetainedControls(dsl); + Map originalPostimages = readControlPostimages(dsl, false); + assertThat(originalPostimages).hasSize(3); + assertThat(originalPostimages.keySet()) + .containsExactlyInAnyOrder( + controls.noActiveAccountId(), + controls.activeAccountId(), + controls.historicalAccountId()); + + Flyway throughV1028 = flyway(dataSource, schema, MigrationVersion.fromVersion("1028")); + throughV1028.migrate(); + throughV1028.validate(); + assertRetainedState(dsl, originalPostimages); + + // A newly constructed Flyway instance models a process restart against the retained schema. + Flyway restarted = flyway(dataSource, schema, MigrationVersion.fromVersion("1028")); + restarted.validate(); + restarted.migrate(); + restarted.validate(); + assertRetainedState(dsl, originalPostimages); + } finally { + dropSchema(schema); + } + } + + private static RetainedControls seedRetainedControls(DSLContext dsl) { + UUID noActiveAccountId = UUID.randomUUID(); + UUID activeAccountId = UUID.randomUUID(); + UUID historicalAccountId = UUID.randomUUID(); + UUID activeOperationId = UUID.randomUUID(); + UUID historicalOperationId = UUID.randomUUID(); + UUID activeAdmissionFence = UUID.randomUUID(); + UUID activeCoverageFence = UUID.randomUUID(); + UUID historicalAdmissionFence = UUID.randomUUID(); + UUID historicalCoverageFence = UUID.randomUUID(); + + // These are deliberate V31-shaped migration inputs. They do not assert that a live account + // coverage producer ran or that any account is eligible for admission. + dsl.execute( + "INSERT INTO " + + CONTROL + + " (account_id, state, last_operation_fence, updated_at)" + + " VALUES (?, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0, CAST(? AS timestamp with time zone))," + + " (?, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0, CAST(? AS timestamp with time zone))," + + " (?, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0, CAST(? AS timestamp with time zone))", + noActiveAccountId, + RETAINED_UPDATED_AT, + activeAccountId, + RETAINED_UPDATED_AT, + historicalAccountId, + RETAINED_UPDATED_AT); + + insertCoverageOperation( + dsl, + activeOperationId, + activeAccountId, + "ACTIVE", + 5, + activeCoverageFence, + activeAdmissionFence, + null, + null, + null, + null, + null); + insertCoverageOperation( + dsl, + historicalOperationId, + historicalAccountId, + "HISTORICAL", + 7, + historicalCoverageFence, + null, + historicalAdmissionFence, + 17, + 23, + 0L, + MEMBER_DIGEST); + + dsl.execute( + "UPDATE " + + CONTROL + + " SET state = 'ACTIVE', last_operation_fence = 5, current_operation_id = ?," + + " current_operation_fence = 5, account_admission_fence = ?, coverage_fence = ?," + + " inventory_snapshot_revision = NULL, coverage_generation = NULL, updated_at = CAST(? AS timestamp with time zone)" + + " WHERE account_id = ?", + activeOperationId, + activeAdmissionFence, + activeCoverageFence, + RETAINED_UPDATED_AT, + activeAccountId); + dsl.execute( + "UPDATE " + + CONTROL + + " SET state = 'HISTORICAL', last_operation_fence = 7, current_operation_id = ?," + + " current_operation_fence = 7, historical_account_admission_fence = ?," + + " coverage_fence = ?, inventory_snapshot_revision = 17, coverage_generation = 23," + + " updated_at = CAST(? AS timestamp with time zone) WHERE account_id = ?", + historicalOperationId, + historicalAdmissionFence, + historicalCoverageFence, + RETAINED_UPDATED_AT, + historicalAccountId); + + return new RetainedControls(noActiveAccountId, activeAccountId, historicalAccountId); + } + + private static void insertCoverageOperation( + DSLContext dsl, + UUID operationId, + UUID accountId, + String lifecycle, + int operationFence, + UUID coverageFence, + UUID accountAdmissionFence, + UUID historicalAccountAdmissionFence, + Integer inventorySnapshotRevision, + Integer coverageGeneration, + Long redisMemberCount, + String redisMemberSetDigest) { + dsl.execute( + "INSERT INTO " + + COVERAGE_OPERATION + + " (operation_id, request_id, account_id, legacy_cohort_id," + + " legacy_owner_operation_id, legacy_writer_fence," + + " legacy_source_snapshot_revision, legacy_canonical_inventory_revision," + + " legacy_namespace_index_readback_revision, legacy_evidence_digest, lifecycle," + + " operation_fence, coverage_fence, account_admission_fence," + + " historical_account_admission_fence, resolved_scope_kind, snapshot_state," + + " blocked_reason, inventory_snapshot_revision, coverage_generation," + + " redis_member_count, redis_member_set_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, 1, 1, 1, ?, ?, ?, ?, ?, ?, 'ACCOUNT_WIDE'," + + " 'COMPLETE', NULL, ?, ?, ?, ?)", + operationId, + UUID.randomUUID(), + accountId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + LEGACY_DIGEST, + lifecycle, + operationFence, + coverageFence, + accountAdmissionFence, + historicalAccountAdmissionFence, + inventorySnapshotRevision, + coverageGeneration, + redisMemberCount, + redisMemberSetDigest); + } + + private static void assertRetainedState(DSLContext dsl, Map originalPostimages) { + assertLatestMigration(dsl, "1028"); + assertThat(readControlPostimages(dsl, true)).isEqualTo(originalPostimages); + assertThat( + dsl.fetchSingle( + "SELECT count(*) AS row_count FROM " + + CONTROL + + " WHERE current_fence_intent_id IS NOT NULL") + .get("row_count", Long.class)) + .isZero(); + assertEmptyTable(dsl, "game_session_canonical_account_admission_fence_intent"); + assertEmptyTable(dsl, "game_session_canonical_account_admission_fence_intent_cohort_row"); + assertEmptyTable(dsl, "game_session_canonical_account_admission_fence_intent_barrier_target"); + } + + private static Map readControlPostimages( + DSLContext dsl, boolean removeAddedIntentColumn) { + String imageExpression = + removeAddedIntentColumn + ? "(to_jsonb(c) - 'current_fence_intent_id')::text" + : "to_jsonb(c)::text"; + Map postimages = new LinkedHashMap<>(); + for (Record row : + dsl.fetch( + "SELECT c.account_id, " + + imageExpression + + " AS row_image FROM " + + CONTROL + + " c ORDER BY c.account_id")) { + postimages.put(row.get("account_id", UUID.class), row.get("row_image", String.class)); + } + return Map.copyOf(postimages); + } + + private static void assertEmptyTable(DSLContext dsl, String table) { + assertThat( + dsl.fetchSingle("SELECT count(*) AS row_count FROM " + table) + .get("row_count", Long.class)) + .as(table) + .isZero(); + } + + private static void assertLatestMigration(DSLContext dsl, String expectedVersion) { + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get("version", String.class)) + .isEqualTo(expectedVersion); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + return target == null ? configuration.load() : configuration.target(target).load(); + } + + 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 account-admission intent test schema", failure); + } + } + + private record RetainedControls( + UUID noActiveAccountId, UUID activeAccountId, UUID historicalAccountId) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..0cb3d97611 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java @@ -0,0 +1,1359 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.sql.SQLException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +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.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +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.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Physical Coordination Redis and PostgreSQL composition proof using only a controlled local + * signer. It proves the local CLOSED-write/readback algorithm, not genuine attestor custody, + * operational OPEN authorization, an SQL installation receipt, or account-wide coverage. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final String PREFIX = "session:game:account-admission:"; + private static final int PORT = 6379; + private static final String KEY_ID = "controlled-barrier-attestor"; + private static final String ATTESTOR_BINDING = "controlled-local-barrier-attestor"; + private static final String ACCEPTED_ATTESTATION_DIGEST = "sha256:" + "a".repeat(64); + private static final String ACL_DIGEST = "sha256:" + "b".repeat(64); + private static final String CONFIG_DIGEST = "sha256:" + "c".repeat(64); + private static final Instant NOW = Instant.parse("2026-10-26T00:00:00Z"); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); + + @Test + void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedIncarnation() + throws Exception { + try (Fixture fixture = Fixture.open(); + RedisFixture redis = RedisFixture.open()) { + var initialReceiver = fixture.receiver(new ControlledSigner(fixture.keyPair(), false)); + var assignment = + fixture.tagRepository().assignmentForBarrierTarget(fixture.intent().operationId(), 0L); + String key = CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); + byte[] redisKey = ascii(key); + var initialProof = initialReceiver.observeForFenceTarget(fixture.intent().operationId(), 0L); + + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> + fixture + .owner(initialReceiver, redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clear(); + } + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + try { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy( + () -> + fixture + .owner(initialReceiver, redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(redis.admin().type(redisKey)).isEqualTo("none"); + + // Simulate a valid lower-epoch OPEN hash. The actual operation fence is seeded at 10 by the + // test fixture's existing NO_ACTIVE control high-water; the script must replace it CLOSED. + Map previousOpen = + withPriorOperation(barrierFields(fixture, assignment, initialProof, "9", "OPEN")); + redis.admin().hset(redisKey, encoded(previousOpen)); + var firstOwner = fixture.owner(initialReceiver, redis); + var installed = firstOwner.installAndRead(fixture.intent().operationId(), 0L); + assertThat(fixture.intent().operationFence()).isEqualTo(java.math.BigInteger.TEN); + assertThat(installed.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.ADVANCED_TO_CLOSED); + assertThat(installed.key()).isEqualTo(key); + assertThat(installed.barrierFields()) + .containsEntry("ownerOperationId", fixture.intent().operationId().toString()) + .containsEntry("ownerFenceEpoch", "10") + .containsEntry("incarnationDigest", initialProof.incarnationDigest()) + .containsEntry("state", "CLOSED"); + assertExactHash(redis.admin(), redisKey, installed.barrierFields()); + assertThat( + redis + .admin() + .type(ascii("session:game:index:account:" + fixture.intent().accountId()))) + .isEqualTo("none"); + + // A lower CLOSED predecessor also advances; a restarted owner retries the same SQL tuple. + Map previousClosed = + withPriorOperation(barrierFields(fixture, assignment, initialProof, "9", "CLOSED")); + redis.admin().hset(redisKey, encoded(previousClosed)); + var advancedClosed = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L); + assertThat(advancedClosed.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.ADVANCED_TO_CLOSED); + assertThat(advancedClosed.barrierFields()).isEqualTo(installed.barrierFields()); + + var exactRetry = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L); + assertThat(exactRetry.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.EXACT_CLOSED_REPLAY); + assertThat(exactRetry.barrierFields()).isEqualTo(installed.barrierFields()); + + Map equalEpochOpen = new LinkedHashMap<>(installed.barrierFields()); + equalEpochOpen.put("state", "OPEN"); + redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); + redis.admin().hset(redisKey, encoded(equalEpochOpen)); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertExactHash(redis.admin(), redisKey, equalEpochOpen); + + Map equalEpochConflictingOwner = + new LinkedHashMap<>(installed.barrierFields()); + equalEpochConflictingOwner.put("ownerOperationId", UUID.randomUUID().toString()); + redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); + redis.admin().hset(redisKey, encoded(equalEpochConflictingOwner)); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertExactHash(redis.admin(), redisKey, equalEpochConflictingOwner); + + Map unknownField = new LinkedHashMap<>(installed.barrierFields()); + unknownField.put("operatorExtension", "preserve"); + redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); + redis.admin().hset(redisKey, encoded(unknownField)); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertThat(stringMap(redis.admin().hgetall(redisKey))).isEqualTo(unknownField); + assertThat(redis.admin().type(redisKey)).isEqualTo("hash"); + assertThat(redis.admin().pttl(redisKey)).isEqualTo(-1L); + assertThat(redis.admin().hlen(redisKey)).isEqualTo(10L); + + // A lost Redis key may be recreated CLOSED under the same original operation and fence. + redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); + var recreated = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L); + assertThat(recreated.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.CREATED_CLOSED); + assertThat(recreated.barrierFields()).isEqualTo(installed.barrierFields()); + + // The write may have happened, but changed protected evidence on the post-read observation + // prevents an owner readback capability from being returned. The stored barrier stays closed. + var changingReceiver = fixture.receiver(new ControlledSigner(fixture.keyPair(), true)); + assertThatThrownBy( + () -> + fixture + .owner(changingReceiver, redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("CLOSED account barrier is unavailable"); + assertExactHash(redis.admin(), redisKey, installed.barrierFields()); + + // A newer OPEN owner/fence is never overwritten by this stale installer. + Map newerOpen = + new LinkedHashMap<>(barrierFields(fixture, assignment, initialProof, "11", "OPEN")); + newerOpen.put("ownerOperationId", UUID.randomUUID().toString()); + redis.admin().hset(redisKey, encoded(newerOpen)); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertExactHash(redis.admin(), redisKey, newerOpen); + + // Wrong Redis type, foreign scope, and TTL-bearing hashes are non-mutating refusals. + redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); + redis.admin().set(redisKey, ascii("operator-owned")); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertThat(redis.admin().get(redisKey)).isEqualTo(ascii("operator-owned")); + + redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); + Map foreignScope = + new LinkedHashMap<>(barrierFields(fixture, assignment, initialProof, "9", "CLOSED")); + foreignScope.put("tenantId", UUID.randomUUID().toString()); + redis.admin().hset(redisKey, encoded(foreignScope)); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertExactHash(redis.admin(), redisKey, foreignScope); + + redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); + redis.admin().hset(redisKey, encoded(previousClosed)); + redis.admin().pexpire(redisKey, 60_000L); + Map expiringBefore = redis.admin().hgetall(redisKey); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertThat(stringMap(redis.admin().hgetall(redisKey))).isEqualTo(stringMap(expiringBefore)); + assertThat(redis.admin().pttl(redisKey)).isPositive(); + + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(UUID.randomUUID(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 1L)) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void comparesVeryLargeFenceEpochsAsCanonicalDecimalStrings() throws Exception { + java.math.BigInteger highWater = + new java.math.BigInteger("900719925474099312345678901234567890"); + try (Fixture fixture = Fixture.open(highWater); + RedisFixture redis = RedisFixture.open()) { + var receiver = fixture.receiver(new ControlledSigner(fixture.keyPair(), false)); + var assignment = + fixture.tagRepository().assignmentForBarrierTarget(fixture.intent().operationId(), 0L); + byte[] key = ascii(CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment)); + var proof = receiver.observeForFenceTarget(fixture.intent().operationId(), 0L); + java.math.BigInteger fence = fixture.intent().operationFence(); + assertThat(fence).isGreaterThan(new java.math.BigInteger("9007199254740992")); + + String priorEpoch = fence.subtract(java.math.BigInteger.ONE).toString(); + Map lowerClosed = + withPriorOperation(barrierFields(fixture, assignment, proof, priorEpoch, "CLOSED")); + redis.admin().hset(key, encoded(lowerClosed)); + + var advanced = + fixture.owner(receiver, redis).installAndRead(fixture.intent().operationId(), 0L); + String exactFence = fixture.intent().operationFence().toString(); + assertThat(exactFence).matches("[1-9][0-9]*"); + assertThat(advanced.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.ADVANCED_TO_CLOSED); + assertThat(advanced.barrierFields().get("ownerFenceEpoch")).isEqualTo(exactFence); + + var replay = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L); + assertThat(replay.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.EXACT_CLOSED_REPLAY); + assertThat(replay.barrierFields().get("ownerFenceEpoch")).isEqualTo(exactFence); + + String greaterEpoch = + fixture.intent().operationFence().add(java.math.BigInteger.ONE).toString(); + Map newerOwner = + new LinkedHashMap<>(barrierFields(fixture, assignment, proof, greaterEpoch, "OPEN")); + newerOwner.put("ownerOperationId", UUID.randomUUID().toString()); + redis.admin().hset(key, encoded(newerOwner)); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertThat(stringMap(redis.admin().hgetall(key))).isEqualTo(newerOwner); + assertThat(newerOwner.get("ownerFenceEpoch")).isEqualTo(greaterEpoch); + assertThat(greaterEpoch).matches("[1-9][0-9]*"); + } + } + + @Test + void closesPriorOpenAtZeroFromPositiveControlAndRejectsPriorClosedAtZero() throws Exception { + try (Fixture fixture = Fixture.open(java.math.BigInteger.ZERO); + RedisFixture redis = RedisFixture.open()) { + assertThat(fixture.intent().operationFence()).isEqualTo(java.math.BigInteger.ONE); + var receiver = fixture.receiver(new ControlledSigner(fixture.keyPair(), false)); + var assignment = + fixture.tagRepository().assignmentForBarrierTarget(fixture.intent().operationId(), 0L); + byte[] key = ascii(CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment)); + var proof = receiver.observeForFenceTarget(fixture.intent().operationId(), 0L); + + // This controlled prior hash demonstrates the script's epoch-zero OPEN handling. It is not + // evidence that an actual OPEN producer installed the fixture value. + Map priorOpen = + withPriorOperation(barrierFields(fixture, assignment, proof, "0", "OPEN")); + redis.admin().hset(key, encoded(priorOpen)); + var installed = + fixture.owner(receiver, redis).installAndRead(fixture.intent().operationId(), 0L); + assertThat(installed.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.ADVANCED_TO_CLOSED); + assertThat(installed.barrierFields()) + .containsEntry("ownerFenceEpoch", "1") + .containsEntry("state", "CLOSED"); + assertExactHash(redis.admin(), key, installed.barrierFields()); + + var retry = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L); + assertThat(retry.mutationOutcome()) + .isEqualTo( + CanonicalGameplayAccountClosedBarrierRedisOwner.MutationOutcome.EXACT_CLOSED_REPLAY); + assertThat(retry.barrierFields()).isEqualTo(installed.barrierFields()); + + Map priorClosed = + withPriorOperation(barrierFields(fixture, assignment, proof, "0", "CLOSED")); + redis.admin().del(List.of(key).toArray(byte[][]::new)); + redis.admin().hset(key, encoded(priorClosed)); + assertThatThrownBy( + () -> + fixture + .owner( + fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) + .isInstanceOf(IllegalStateException.class); + assertExactHash(redis.admin(), key, priorClosed); + } + } + + @Test + void acceptsOneClosedReceiptAndExactRetryReturnsTheOriginalSqlPostimage() throws Exception { + try (Fixture fixture = Fixture.open(); + RedisFixture redis = RedisFixture.open()) { + UUID operationId = fixture.intent().operationId(); + var sqlOwner = + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW, ZoneOffset.UTC)); + + var firstReadback = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(operationId, 0L); + // Deliberately discard the first acceptance result; this models loss of the caller's local + // result only, not a simulated network or response-loss event. + sqlOwner.acceptClosedBarrierReadback(operationId, 0L, firstReadback); + String originalPostimage = closedReceiptPostimage(fixture, operationId, 0L); + + var freshRetryReadback = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(operationId, 0L); + var restartedSqlOwner = + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW, ZoneOffset.UTC)); + StoredClosedBarrierReceipt retry = + restartedSqlOwner.acceptClosedBarrierReadback(operationId, 0L, freshRetryReadback); + + assertThat(retry.operationId()).isEqualTo(operationId); + assertThat(retry.barrierState()).isEqualTo("CLOSED"); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + + assertThatThrownBy( + () -> + restartedSqlOwner.acceptClosedBarrierReadback( + UUID.randomUUID(), 0L, freshRetryReadback)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + restartedSqlOwner.acceptClosedBarrierReadback( + operationId, 1L, freshRetryReadback)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + + // The receipt is as-of evidence only. SQL remains ACQUISITION_INTENT and the target remains + // REQUIRED; this test does not publish INSTALLED or imply current physical presence later. + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + fixture.intent().accountId()) + .get("state", String.class)) + .isEqualTo("ACQUISITION_INTENT"); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT target_state FROM" + + " game_session_canonical_account_admission_fence_intent_barrier_target" + + " WHERE operation_id = ? AND target_ordinal = 0", + operationId) + .get("target_state", String.class)) + .isEqualTo("REQUIRED"); + } + } + + @Test + void acceptsClosedReadbackAfterConcurrentPrepareCommitsWhileWaitingOnInventoryClock() + throws Exception { + try (Fixture fixture = Fixture.open(); + RedisFixture redis = RedisFixture.open()) { + UUID operationId = fixture.intent().operationId(); + var readback = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(operationId, 0L); + + String prepareApplicationName = + "gs_closed_receipt_prepare_" + UUID.randomUUID().toString().replace("-", ""); + String acceptApplicationName = + "gs_closed_receipt_accept_" + UUID.randomUUID().toString().replace("-", ""); + DSLContext prepareDsl = fixture.dslForApplication(prepareApplicationName); + DSLContext acceptDsl = fixture.dslForApplication(acceptApplicationName); + + // A distinct account can still prepare while this account's acquisition intent is pending. + // That real owner operation advances the shared inventory revision. + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( + fixture.dataSource, UUID.randomUUID()); + UUID otherAccountId = UUID.randomUUID(); + CanonicalGameplayBindingIdentity otherCandidate = + new CanonicalGameplayBindingIdentity( + otherAccountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + UUID.randomUUID(), + "SHARED", + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + UUID.randomUUID(), + java.math.BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + java.math.BigInteger.ONE, + java.math.BigInteger.ONE, + java.math.BigInteger.valueOf(16), + java.math.BigInteger.valueOf(32)); + CanonicalGameplayBindingTransitionRequest otherRequest = + new CanonicalGameplayBindingTransitionRequest( + UUID.randomUUID(), + UUID.randomUUID(), + otherCandidate, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + java.math.BigInteger.ONE, + java.math.BigInteger.ONE, + java.math.BigInteger.ONE), + null, + null); + java.math.BigInteger startingRevision = + Objects.requireNonNull( + fixture + .dsl + .fetchSingle( + "SELECT inventory_revision FROM" + + " game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1") + .get("inventory_revision", java.math.BigDecimal.class), + "starting inventory revision") + .toBigIntegerExact(); + + CountDownLatch inventoryClockHeld = new CountDownLatch(1); + CountDownLatch releaseInventoryClock = new CountDownLatch(1); + try (ExecutorService executor = Executors.newFixedThreadPool(3)) { + Future clockHolder = + executor.submit( + () -> + fixture.dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + if (transaction.fetchOne( + "SELECT inventory_revision FROM" + + " game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE") + == null) { + throw new IllegalStateException("Inventory clock row is missing"); + } + inventoryClockHeld.countDown(); + awaitLatch(releaseInventoryClock); + return Boolean.TRUE; + })); + try { + assertThat(inventoryClockHeld.await(5, TimeUnit.SECONDS)).isTrue(); + Future prepare = + executor.submit( + () -> + new CanonicalGameplayBindingInventoryRepository(prepareDsl) + .prepare(otherRequest)); + awaitInventoryClockLockWait(fixture.dsl, prepareApplicationName); + + Future accepted = + executor.submit( + () -> + new CanonicalGameplayAccountAdmissionBarrierRepository( + acceptDsl, Clock.fixed(NOW, ZoneOffset.UTC)) + .acceptClosedBarrierReadback(operationId, 0L, readback)); + awaitInventoryClockLockWait(fixture.dsl, acceptApplicationName); + + // PostgreSQL's row-lock queue releases the actual prepare first, then lets the receipt + // owner take a fresh READ COMMITTED snapshot after that commit. + releaseInventoryClock.countDown(); + prepare.get(10, TimeUnit.SECONDS); + assertThat(accepted.get(10, TimeUnit.SECONDS).operationId()).isEqualTo(operationId); + } finally { + releaseInventoryClock.countDown(); + clockHolder.get(10, TimeUnit.SECONDS); + } + } + + java.math.BigInteger endingRevision = + Objects.requireNonNull( + fixture + .dsl + .fetchSingle( + "SELECT inventory_revision FROM" + + " game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1") + .get("inventory_revision", java.math.BigDecimal.class), + "ending inventory revision") + .toBigIntegerExact(); + assertThat(endingRevision).isEqualTo(startingRevision.add(java.math.BigInteger.ONE)); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + } + } + + @Test + void expiredTrustedAcceptanceClockCannotReplaceAnExistingClosedReceipt() throws Exception { + try (Fixture fixture = Fixture.open(); + RedisFixture redis = RedisFixture.open()) { + UUID operationId = fixture.intent().operationId(); + var actualOwner = + fixture.owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis); + var validReadback = actualOwner.installAndRead(operationId, 0L); + var currentSqlOwner = + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW, ZoneOffset.UTC)); + currentSqlOwner.acceptClosedBarrierReadback(operationId, 0L, validReadback); + String originalPostimage = closedReceiptPostimage(fixture, operationId, 0L); + + // The Redis owner still performs an actual install/readback. Acceptance occurs at the exact + // expiry boundary under a controlled trusted clock, so the stale capability cannot overwrite. + var nowExpiredReadback = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(operationId, 0L); + var expiredSqlOwner = + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW.plusSeconds(30), ZoneOffset.UTC)); + assertThatThrownBy( + () -> + expiredSqlOwner.acceptClosedBarrierReadback(operationId, 0L, nowExpiredReadback)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("expired"); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + } + } + + @Test + void changedCurrentControlOwnerCannotAddOrReplaceTheClosedReceipt() throws Exception { + try (Fixture fixture = Fixture.open(); + RedisFixture redis = RedisFixture.open()) { + UUID operationId = fixture.intent().operationId(); + var actualOwner = + fixture.owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis); + var initial = actualOwner.installAndRead(operationId, 0L); + var sqlOwner = + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW, ZoneOffset.UTC)); + sqlOwner.acceptClosedBarrierReadback(operationId, 0L, initial); + String originalPostimage = closedReceiptPostimage(fixture, operationId, 0L); + + var staleCurrentProof = actualOwner.installAndRead(operationId, 0L); + // Controlled SQL displacement is a refusal fixture, not a claimed release lifecycle. + fixture.dsl.execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', current_operation_id = NULL," + + " current_fence_intent_id = NULL, current_operation_fence = NULL," + + " account_admission_fence = NULL, historical_account_admission_fence = NULL," + + " coverage_fence = NULL, inventory_snapshot_revision = NULL," + + " coverage_generation = NULL WHERE account_id = ?", + fixture.intent().accountId()); + + assertThatThrownBy( + () -> sqlOwner.acceptClosedBarrierReadback(operationId, 0L, staleCurrentProof)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + } + } + + @Test + void changedPersistedCohortCannotAddOrReplaceTheClosedReceipt() throws Exception { + try (Fixture fixture = Fixture.open(); + RedisFixture redis = RedisFixture.open()) { + UUID operationId = fixture.intent().operationId(); + var actualOwner = + fixture.owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis); + var initial = actualOwner.installAndRead(operationId, 0L); + var sqlOwner = + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW, ZoneOffset.UTC)); + sqlOwner.acceptClosedBarrierReadback(operationId, 0L, initial); + String originalPostimage = closedReceiptPostimage(fixture, operationId, 0L); + + var staleCurrentProof = actualOwner.installAndRead(operationId, 0L); + fixture.dsl.execute( + "UPDATE game_session_canonical_account_admission_fence_intent" + + " SET cohort_digest = CASE WHEN cohort_digest = ? THEN ? ELSE ? END" + + " WHERE operation_id = ?", + "sha256:" + "f".repeat(64), + "sha256:" + "e".repeat(64), + "sha256:" + "f".repeat(64), + operationId); + + assertThatThrownBy( + () -> sqlOwner.acceptClosedBarrierReadback(operationId, 0L, staleCurrentProof)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("cohort"); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + } + } + + private static long closedReceiptCount(Fixture fixture, UUID operationId) { + Long count = + fixture + .dsl + .fetchSingle( + "SELECT count(*) AS row_count FROM" + + " game_session_canonical_account_closed_barrier_receipt" + + " WHERE operation_id = ?", + operationId) + .get("row_count", Long.class); + return java.util.Objects.requireNonNull(count, "receipt count"); + } + + private static void awaitInventoryClockLockWait(DSLContext observer, String applicationName) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Boolean waiting = + Objects.requireNonNull( + observer.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE pid <> pg_backend_pid() AND application_name = ?" + + " AND state = 'active' AND wait_event_type = 'Lock'" + + " AND query ILIKE '%game_session_canonical_binding_inventory_clock%')", + applicationName), + "inventory clock lock wait query") + .get(0, Boolean.class); + if (Boolean.TRUE.equals(waiting)) { + return; + } + Thread.sleep(10); + } + throw new AssertionError("Owner did not wait on the held inventory clock row"); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to release inventory clock row"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while holding inventory clock row", interrupted); + } + } + + private static String closedReceiptPostimage( + Fixture fixture, UUID operationId, long targetOrdinal) { + return fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(receipt)::text AS row_image FROM" + + " game_session_canonical_account_closed_barrier_receipt receipt" + + " WHERE operation_id = ? AND target_ordinal = ?", + operationId, + targetOrdinal) + .get("row_image", String.class); + } + + @Test + void upgradesPopulatedV1028IntentAndAcceptsReceiptWithoutChangingRetainedRows() throws Exception { + try (Fixture fixture = Fixture.open(java.math.BigInteger.valueOf(9), "1028"); + RedisFixture redis = RedisFixture.open()) { + UUID operationId = fixture.intent().operationId(); + var assignment = fixture.tagRepository().assignmentForBarrierTarget(operationId, 0L); + RetainedV1028Postimage originalRows = retainedV1028Postimage(fixture, assignment); + assertThat(originalRows.intent()).hasSize(1); + assertThat(originalRows.cohort()).isNotEmpty(); + assertThat(originalRows.targets()).isNotEmpty(); + assertThat(originalRows.control()).hasSize(1); + assertThat(originalRows.mapping()).hasSize(1); + + fixture.migrateTo("1029"); + assertThat(retainedV1028Postimage(fixture, assignment)).isEqualTo(originalRows); + + var readback = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(operationId, 0L); + StoredClosedBarrierReceipt receipt = + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW, ZoneOffset.UTC)) + .acceptClosedBarrierReadback(operationId, 0L, readback); + assertThat(receipt.operationId()).isEqualTo(operationId); + assertThat(receipt.barrierState()).isEqualTo("CLOSED"); + assertThat(retainedV1028Postimage(fixture, assignment)).isEqualTo(originalRows); + + String receiptPostimage = closedReceiptPostimage(fixture, operationId, 0L); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + fixture.validateAndMigrateTo("1029"); + assertThat(retainedV1028Postimage(fixture, assignment)).isEqualTo(originalRows); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(receiptPostimage); + } + } + + @Test + void databaseRejectsReceiptUpdateDeleteAndTruncateWithoutChangingItsPostimage() throws Exception { + try (Fixture fixture = Fixture.open(); + RedisFixture redis = RedisFixture.open()) { + UUID operationId = fixture.intent().operationId(); + var readback = + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(operationId, 0L); + new CanonicalGameplayAccountAdmissionBarrierRepository( + fixture.dsl, Clock.fixed(NOW, ZoneOffset.UTC)) + .acceptClosedBarrierReadback(operationId, 0L, readback); + String originalPostimage = closedReceiptPostimage(fixture, operationId, 0L); + + // created_at is outside the row CHECK constraints, so 23514 proves the immutable trigger. + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_account_closed_barrier_receipt" + + " SET created_at = created_at + INTERVAL '1 second'" + + " WHERE operation_id = ? AND target_ordinal = 0", + operationId)) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_account_closed_barrier_receipt" + + " WHERE operation_id = ? AND target_ordinal = 0", + operationId)) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + + assertThatThrownBy( + () -> + fixture.dsl.execute( + "TRUNCATE TABLE game_session_canonical_account_closed_barrier_receipt")) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); + assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); + } + } + + private record RetainedV1028Postimage( + List intent, + List cohort, + List targets, + List control, + List mapping) { + private RetainedV1028Postimage { + intent = List.copyOf(intent); + cohort = List.copyOf(cohort); + targets = List.copyOf(targets); + control = List.copyOf(control); + mapping = List.copyOf(mapping); + } + } + + private static RetainedV1028Postimage retainedV1028Postimage( + Fixture fixture, CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { + UUID operationId = fixture.intent().operationId(); + return new RetainedV1028Postimage( + rowImages( + fixture, + "SELECT to_jsonb(source_row)::text AS row_image" + + " FROM game_session_canonical_account_admission_fence_intent source_row" + + " WHERE operation_id = ?", + operationId), + rowImages( + fixture, + "SELECT to_jsonb(source_row)::text AS row_image" + + " FROM game_session_canonical_account_admission_fence_intent_cohort_row source_row" + + " WHERE operation_id = ? ORDER BY row_ordinal", + operationId), + rowImages( + fixture, + "SELECT to_jsonb(source_row)::text AS row_image" + + " FROM game_session_canonical_account_admission_fence_intent_barrier_target" + + " source_row WHERE operation_id = ? ORDER BY target_ordinal", + operationId), + rowImages( + fixture, + "SELECT to_jsonb(source_row)::text AS row_image" + + " FROM game_session_canonical_account_coverage_control source_row" + + " WHERE account_id = ?", + fixture.intent().accountId()), + rowImages( + fixture, + "SELECT to_jsonb(source_row)::text AS row_image" + + " FROM game_session_canonical_tenant_gameplay_tag source_row" + + " WHERE tenant_id = ?", + assignment.tenantId())); + } + + private static List rowImages(Fixture fixture, String query, Object... bindings) { + return fixture.dsl.fetch(query, bindings).map(row -> row.get("row_image", String.class)); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException) { + return sqlException.getSQLState(); + } + } + return null; + } + + private static Map barrierFields( + Fixture fixture, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation incarnation, + String epoch, + String state) { + Map fields = new LinkedHashMap<>(); + fields.put("schema", "gs_account_admission_barrier/v1"); + fields.put("accountId", fixture.intent().accountId().toString()); + fields.put("tenantId", assignment.tenantId().toString()); + fields.put("playableStateNamespaceId", assignment.playableStateNamespaceId().toString()); + fields.put("tenantGameplayTag", assignment.tenantGameplayTag()); + fields.put("ownerOperationId", fixture.intent().operationId().toString()); + fields.put("ownerFenceEpoch", epoch); + fields.put("incarnationDigest", incarnation.incarnationDigest()); + fields.put("state", state); + return Map.copyOf(fields); + } + + private static Map encoded(Map fields) { + Map encoded = new LinkedHashMap<>(); + fields.forEach((field, value) -> encoded.put(ascii(field), ascii(value))); + return encoded; + } + + private static Map withPriorOperation(Map fields) { + Map prior = new LinkedHashMap<>(fields); + prior.put("ownerOperationId", UUID.randomUUID().toString()); + return Map.copyOf(prior); + } + + private static Map stringMap(Map fields) { + Map decoded = new LinkedHashMap<>(); + fields.forEach( + (field, value) -> + decoded.put( + new String(field, StandardCharsets.US_ASCII), + new String(value, StandardCharsets.US_ASCII))); + return decoded; + } + + private static void assertExactHash( + RedisCommands admin, byte[] key, Map expected) { + Map actual = stringMap(admin.hgetall(key)); + assertThat(actual).isEqualTo(expected); + assertThat(admin.type(key)).isEqualTo("hash"); + assertThat(admin.pttl(key)).isEqualTo(-1L); + assertThat(admin.hlen(key)).isEqualTo(9L); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static final class ControlledSigner + implements CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel { + private final KeyPair keyPair; + private final boolean changeSecondObservation; + private int calls; + + private ControlledSigner(KeyPair keyPair, boolean changeSecondObservation) { + this.keyPair = keyPair; + this.changeSecondObservation = changeSecondObservation; + } + + @Override + public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + try { + Map root = payload(request); + calls++; + if (changeSecondObservation && calls > 1) { + asMap(root.get("targetDeploymentEvidence")).put("storageGeneration", "storage-changed"); + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keyPair.getPrivate()); + signer.update(canonical); + return new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + KEY_ID, canonical, signer.sign()); + } catch (Exception failure) { + throw new IllegalStateException("Controlled local test signer failed", failure); + } + } + } + + private static Map payload( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var context = request.context(); + var evidence = request.expectedEvidence(); + Map owner = new LinkedHashMap<>(); + owner.put("operationId", context.operationId().toString()); + owner.put("requestId", context.requestId().toString()); + owner.put("accountId", context.accountId().toString()); + owner.put("operationFence", context.operationFence()); + owner.put("plannedAccountAdmissionFence", context.plannedAccountAdmissionFence().toString()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("cohortDigest", context.cohortDigest()); + owner.put("barrierTargetDigest", context.barrierTargetDigest()); + + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", context.targetOrdinal()); + target.put("tenantId", context.tenantId().toString()); + target.put("playableStateNamespaceId", context.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", context.tenantGameplayTag()); + target.put("workloadNamespace", context.workloadNamespace()); + target.put("allocationVersion", context.allocationVersion()); + + Map targetEvidence = new LinkedHashMap<>(); + targetEvidence.put("deploymentIdentity", evidence.deploymentIdentity()); + targetEvidence.put("deploymentGeneration", evidence.deploymentGeneration()); + targetEvidence.put("canonicalNodeSet", evidence.canonicalNodeSet()); + targetEvidence.put("redisBuildIdentity", evidence.redisBuildIdentity()); + targetEvidence.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + targetEvidence.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + targetEvidence.put("startupState", evidence.startupState()); + targetEvidence.put("bootGeneration", evidence.bootGeneration()); + targetEvidence.put("startupGeneration", evidence.startupGeneration()); + targetEvidence.put("storageGeneration", evidence.storageGeneration()); + targetEvidence.put("aofGeneration", evidence.aofGeneration()); + + Map root = new LinkedHashMap<>(); + root.put("schema", "firemud.gs.protected-incarnation-read/v1"); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", targetEvidence); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + return root; + } + + @SuppressWarnings("unchecked") + private static Map asMap(Object value) { + return (Map) value; + } + + private static final tools.jackson.databind.json.JsonMapper JSON = + tools.jackson.databind.json.JsonMapper.builder().build(); + + private static final class Fixture implements AutoCloseable { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private final String schema; + private final DriverManagerDataSource dataSource; + private final DSLContext dsl; + private final CanonicalGameplayAccountAdmissionFenceIntent intent; + private final String workloadNamespace; + private final KeyPair keyPair; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence; + private final CanonicalGameplayAccountAdmissionBarrierRepository intentRepository; + private final CanonicalGameplayTenantGameplayTagRepository tagRepository; + + private Fixture( + String schema, + DriverManagerDataSource dataSource, + DSLContext dsl, + CanonicalGameplayAccountAdmissionFenceIntent intent, + String workloadNamespace, + KeyPair keyPair, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence) { + this.schema = schema; + this.dataSource = dataSource; + this.dsl = dsl; + this.intent = intent; + this.workloadNamespace = workloadNamespace; + this.keyPair = keyPair; + this.expectedEvidence = expectedEvidence; + this.intentRepository = new CanonicalGameplayAccountAdmissionBarrierRepository(dsl); + this.tagRepository = + new CanonicalGameplayTenantGameplayTagRepository(dsl, workloadNamespace, 1); + } + + static Fixture open() throws Exception { + return open(java.math.BigInteger.valueOf(9), null); + } + + static Fixture open(java.math.BigInteger lastOperationFence) throws Exception { + return open(lastOperationFence, null); + } + + static Fixture open(java.math.BigInteger lastOperationFence, String migrationTarget) + throws Exception { + String schema = "gs_closed_barrier_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + flyway(dataSource, schema, migrationTarget).migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + UUID tenantId = UUID.randomUUID(); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest + .seedSyntheticVerifiedLegacyDisposition(dsl); + + UUID accountId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + UUID.randomUUID(), + "SHARED", + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + UUID.randomUUID(), + java.math.BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + java.math.BigInteger.ONE, + java.math.BigInteger.ONE, + java.math.BigInteger.valueOf(16), + java.math.BigInteger.valueOf(32)); + CanonicalIssuerReservationFenceEvidence reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + java.math.BigInteger.ONE, + java.math.BigInteger.ONE, + java.math.BigInteger.ONE); + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, reservation, null, null)); + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control SET last_operation_fence = ?" + + " WHERE account_id = ? AND state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'", + lastOperationFence, + accountId); + CanonicalGameplayAccountAdmissionFenceIntent intent = + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(accountId, UUID.randomUUID()); + if (!intent.operationFence().equals(lastOperationFence.add(java.math.BigInteger.ONE))) { + throw new IllegalStateException("Test fixture did not establish the intended fence epoch"); + } + + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + var evidence = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-target-deployment", + "generation-7", + List.of("redis-node-a"), + "redis-test-build", + "registry-test-v1", + "sha256:" + "d".repeat(64), + "READY", + "boot-7", + "startup-7", + "storage-7", + "aof-7"); + return new Fixture( + schema, dataSource, dsl, intent, runtime.targetNamespace(), keyPair, evidence); + } + + private void migrateTo(String migrationTarget) { + flyway(dataSource, schema, migrationTarget).migrate(); + } + + private void validateAndMigrateTo(String migrationTarget) { + Flyway flyway = flyway(dataSource, schema, migrationTarget); + flyway.validate(); + flyway.migrate(); + } + + private DSLContext dslForApplication(String applicationName) { + return DSL.using(dataSource(schema, applicationName), SQLDialect.POSTGRES); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, String migrationTarget) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (migrationTarget != null) { + configuration.target(MigrationVersion.fromVersion(migrationTarget)); + } + return configuration.load(); + } + + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel) { + var trusted = + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + ATTESTOR_BINDING, + ACCEPTED_ATTESTATION_DIGEST, + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), + expectedEvidence, + ACL_DIGEST, + CONFIG_DIGEST, + 16 * 1024, + 1, + Duration.ofSeconds(30)); + return new CanonicalGameplayProtectedIncarnationReceiver( + intentRepository, tagRepository, channel, trusted, Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private CanonicalGameplayAccountClosedBarrierRedisOwner owner( + CanonicalGameplayProtectedIncarnationReceiver receiver, RedisFixture redis) { + return new CanonicalGameplayAccountClosedBarrierRedisOwner( + intentRepository, + tagRepository, + receiver, + redis.ownerClient(), + redis.catalog(), + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private CanonicalGameplayAccountAdmissionFenceIntent intent() { + return intent; + } + + private KeyPair keyPair() { + return keyPair; + } + + private CanonicalGameplayTenantGameplayTagRepository tagRepository() { + return tagRepository; + } + + @Override + public void close() { + 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("Could not dispose test database schema", failure); + } + } + + private static DriverManagerDataSource dataSource(String schema) { + return dataSource(schema, null); + } + + private static DriverManagerDataSource dataSource(String schema, String applicationName) { + DriverManagerDataSource source = new DriverManagerDataSource(); + source.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + String applicationNameParameter = + applicationName == null ? "" : "&ApplicationName=" + applicationName; + source.setUrl( + jdbcUrl + + (jdbcUrl.contains("?") ? "&" : "?") + + "currentSchema=" + + schema + + applicationNameParameter); + source.setUsername(POSTGRES.getUsername()); + source.setPassword(POSTGRES.getPassword()); + return source; + } + } + + private static final class RedisFixture implements AutoCloseable { + private final RedisClient administrator; + private final RedisClient ownerClient; + private final StatefulRedisConnection adminConnection; + private final RedisCommands admin; + private final RedisScriptCatalog catalog; + + private RedisFixture( + RedisClient administrator, + RedisClient ownerClient, + StatefulRedisConnection adminConnection, + RedisCommands admin, + RedisScriptCatalog catalog) { + this.administrator = administrator; + this.ownerClient = ownerClient; + this.adminConnection = adminConnection; + this.admin = admin; + this.catalog = catalog; + } + + static RedisFixture open() { + RedisClient administrator = createClient(null, null); + StatefulRedisConnection adminConnection = + administrator.connect(ByteArrayCodec.INSTANCE); + RedisCommands admin = adminConnection.sync(); + admin.flushdb(); + admin.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern(PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + RedisClient ownerClient = createClient(PRINCIPAL, PASSWORD); + RedisScriptCatalog catalog = + RedisScriptCatalog.loadInstalled( + CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.class + .getClassLoader()); + return new RedisFixture(administrator, ownerClient, adminConnection, admin, catalog); + } + + private static RedisClient createClient(String username, String password) { + RedisURI.Builder builder = + RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(PORT)) + .withTimeout(Duration.ofSeconds(3)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private RedisClient ownerClient() { + return ownerClient; + } + + private RedisCommands admin() { + return admin; + } + + private RedisScriptCatalog catalog() { + return catalog; + } + + @Override + public void close() { + adminConnection.close(); + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java new file mode 100644 index 0000000000..97853e6b97 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java @@ -0,0 +1,705 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +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.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.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberAcknowledgement; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; +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.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical one-key Coordination Redis proof for the binding-local member projection. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String PASSWORD = UUID.randomUUID().toString(); + private static final String PREFIX = "session:game:index:account:"; + private static final int PORT = 6379; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final UUID ACCOUNT_ID = UUID.randomUUID(); + private static final UUID CHARACTER_ID = UUID.randomUUID(); + private static final UUID REGION_ID = UUID.randomUUID(); + private static final UUID TRANSITION_ID = UUID.randomUUID(); + private static final UUID ACCOUNT_INDEX_FENCE = UUID.randomUUID(); + private static final String ISSUER_ID = GameSessionAccountDelegationProfile.ISSUER; + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(PORT); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private RedisClient administrator; + private RedisClient ownerClient; + private CanonicalGameplayAccountMemberRepairRedisOwner owner; + private RedisScriptCatalog catalog; + private StatefulRedisConnection adminConnection; + private RedisCommands admin; + + @BeforeEach + void setUp() { + administrator = createClient(null, null); + adminConnection = administrator.connect(ByteArrayCodec.INSTANCE); + admin = adminConnection.sync(); + admin.flushdb(); + admin.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern(PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.SADD) + .addCommand(CommandType.SISMEMBER)); + ownerClient = createClient(PRINCIPAL, PASSWORD); + catalog = RedisScriptCatalog.loadInstalled(getClass().getClassLoader()); + owner = new CanonicalGameplayAccountMemberRepairRedisOwner(ownerClient, catalog); + } + + @AfterEach + void tearDown() { + if (adminConnection != null) adminConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + @Test + void addsExactMemberOnOneGlobalKeyAndExactRetryPreservesOtherTenantsAndNewerGeneration() { + CanonicalGameplayAccountMemberRepairOperation operation = operation(); + byte[] key = key(operation.accountId()); + var unrelated = + new CanonicalGameplayAccountIndexMember( + CanonicalGameplayBindingRef.of( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID().toString()), + BigInteger.valueOf(3), + UUID.randomUUID()) + .value(); + var newer = + new CanonicalGameplayAccountIndexMember( + operation.bindingRef(), + operation.bindingGeneration().add(BigInteger.ONE), + UUID.randomUUID()) + .value(); + admin.sadd(key, ascii(unrelated), ascii(newer)); + + var first = owner.projectAndRead(operation); + var retry = owner.projectAndRead(operation); + + assertThat(first.operation()).isSameAs(operation); + assertThat(first.member()).isEqualTo(operation.member()); + assertThat(retry.operation()).isSameAs(operation); + assertThat(retry.member()).isEqualTo(operation.member()); + assertThat(admin.type(key)).isEqualTo("set"); + assertThat(admin.sismember(key, ascii(operation.member()))).isTrue(); + assertThat(admin.sismember(key, ascii(unrelated))).isTrue(); + assertThat(admin.sismember(key, ascii(newer))).isTrue(); + assertThat(admin.scard(key)).isEqualTo(3L); + assertThat(admin.pttl(key)).isEqualTo(-1L); + } + + @Test + void refusesWrongPhysicalTypeAndPreservesItsValue() { + CanonicalGameplayAccountMemberRepairOperation operation = operation(); + byte[] key = key(operation.accountId()); + admin.set(key, ascii("operator-owned-string")); + + assertThatThrownBy(() -> owner.projectAndRead(operation)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("projection is unavailable"); + + assertThat(admin.type(key)).isEqualTo("string"); + assertThat(admin.get(key)).isEqualTo(ascii("operator-owned-string")); + } + + @Test + void refusesWrongRedisPrincipalWithoutCreatingTheAccountKey() { + CanonicalGameplayAccountMemberRepairOperation operation = operation(); + byte[] key = key(operation.accountId()); + var wrongOwner = new CanonicalGameplayAccountMemberRepairRedisOwner(administrator, catalog); + + assertThatThrownBy(() -> wrongOwner.projectAndRead(operation)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("projection is unavailable"); + + assertThat(admin.type(key)).isEqualTo("none"); + } + + @Test + void refusesMalformedMemberAtTheLuaBoundaryWithoutCreatingTheKey() throws IOException { + CanonicalGameplayAccountMemberRepairOperation operation = operation(); + byte[] key = key(operation.accountId()); + byte[] source; + try (InputStream input = + getClass() + .getClassLoader() + .getResourceAsStream( + CanonicalGameplayAccountMemberRepairRedisScriptContribution.RESOURCE_PATH)) { + if (input == null) throw new IllegalStateException("Redis script resource is missing"); + source = input.readAllBytes(); + } + String sha = admin.scriptLoad(source); + byte[][] arguments = arguments(operation); + arguments[5] = ascii(operation.member() + "-conflict"); + + Long reply = admin.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments); + + assertThat(reply).isEqualTo(-2L); + assertThat(admin.type(key)).isEqualTo("none"); + + arguments = arguments(operation); + arguments[0] = ascii(UUID.randomUUID().toString()); + reply = admin.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments); + assertThat(reply).isEqualTo(-2L); + assertThat(admin.type(key)).isEqualTo("none"); + + arguments = arguments(operation); + arguments[1] = ascii(UUID.randomUUID().toString()); + reply = admin.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments); + assertThat(reply).isEqualTo(-2L); + assertThat(admin.type(key)).isEqualTo("none"); + } + + @Test + void refusesRedisProjectionWhileSqlTransactionIsAmbient() { + CanonicalGameplayAccountMemberRepairOperation operation = operation(); + byte[] key = key(operation.accountId()); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> owner.projectAndRead(operation)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("projection is unavailable"); + } finally { + TransactionSynchronizationManager.clear(); + } + + assertThat(admin.type(key)).isEqualTo("none"); + } + + @Test + void acknowledgementLocksLeaseBoundRuntimeBeforeTransitionAgainstRuntimeMutation() + throws Exception { + String applicationName = + "gs_account_member_runtime_lock_" + UUID.randomUUID().toString().replace("-", ""); + TestSchema testSchema = newTestSchema(applicationName); + CountDownLatch runtimeRowLocked = new CountDownLatch(1); + CountDownLatch allowRuntimeMutation = new CountDownLatch(1); + try { + // Controlled Account lease and legacy fixtures exercise owner locks, not production + // authority. + LeaseBoundMemberRepairFixture fixture = + prepareLeaseBoundMemberRepair(testSchema.dataSource(), testSchema.dsl()); + CanonicalGameplayAccountMemberRepairOperation operation = + fixture.repository().beginAccountMemberRepair(TRANSITION_ID); + var actualReadback = owner.projectAndRead(operation); + 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()), + "current runtime row") + .get("row_version", Long.class); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + 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 status = 'STOPPED'," + + " row_version = row_version + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + })); + + try { + assertThat(runtimeRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future acknowledgement = + executor.submit( + () -> + fixture + .repository() + .acknowledgeAccountMemberRepair(operation, actualReadback)); + awaitRuntimeRowLockWait(testSchema.dsl(), applicationName); + allowRuntimeMutation.countDown(); + + assertThatThrownBy(() -> runtimeMutation.get(10, TimeUnit.SECONDS)) + .hasStackTraceContaining("runtime row is fenced"); + var accepted = acknowledgement.get(10, TimeUnit.SECONDS); + assertThat(accepted.operation()).isEqualTo(operation); + assertThat(accepted.member()).isEqualTo(operation.member()); + assertThat(fixture.repository().acknowledgeAccountMemberRepair(operation, actualReadback)) + .isEqualTo(accepted); + var exactPrepareRetry = fixture.repository().prepare(fixture.request()); + assertThat(exactPrepareRetry.transitionId()).isEqualTo(TRANSITION_ID); + assertThat(exactPrepareRetry.status().name()).isEqualTo("PROVISIONAL"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT account_index_state FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE transition_id = ?", + TRANSITION_ID) + .get("account_index_state", String.class)) + .isEqualTo("ACKNOWLEDGED"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_account_member_repair_operation" + + " WHERE operation_id = ?", + accepted.operation().operationId()) + .get("status", String.class)) + .isEqualTo("ACKNOWLEDGED"); + assertThat( + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT status, row_version FROM game_instances" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()), + "current runtime row") + .get("status", String.class)) + .isEqualTo("RUNNING"); + assertThat( + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT row_version FROM game_instances" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()), + "current runtime row") + .get("row_version", Long.class)) + .isEqualTo(initialRowVersion); + } finally { + allowRuntimeMutation.countDown(); + } + } + } finally { + allowRuntimeMutation.countDown(); + dropSchema(testSchema.schema()); + } + } + + private static LeaseBoundMemberRepairFixture prepareLeaseBoundMemberRepair( + DriverManagerDataSource dataSource, DSLContext dsl) { + var runtimeTarget = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); + seedSyntheticVerifiedLegacyDisposition(dsl); + CanonicalGameplayBindingInventoryRepository repository = + new CanonicalGameplayBindingInventoryRepository(dsl); + CanonicalGameplayBindingIdentity candidate = + identity(UUID.randomUUID().toString(), runtimeTarget); + CanonicalGameplayBindingTransitionRequest request = + new CanonicalGameplayBindingTransitionRequest( + TRANSITION_ID, + ACCOUNT_INDEX_FENCE, + candidate, + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.valueOf(13), + BigInteger.valueOf(17), + BigInteger.valueOf(41)), + null, + null); + repository.prepare(request); + CanonicalGameplayBindingProvisionalCasEvidence prepared = + repository.readProvisionalCasEvidence(TRANSITION_ID); + AccountGameplayAdmissionLeaseEvidence leaseEvidence = + leaseEvidence( + prepared.candidate().identity(), + prepared.transition().bindingGeneration(), + runtimeTarget.playableTarget()); + CanonicalGameplayAdmissionDecision decision = + new CanonicalGameplayAdmissionDecision( + TRANSITION_ID, + leaseEvidence, + prepared.candidate().identity(), + prepared.transition().bindingGeneration(), + null, + runtimeTarget.playableTarget()); + repository.markProvisional(prepared, decision); + return new LeaseBoundMemberRepairFixture(repository, runtimeTarget, request); + } + + private static CanonicalGameplayBindingIdentity identity( + String sessionId, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target) { + return new CanonicalGameplayBindingIdentity( + ACCOUNT_ID, + target.canonicalTenantId(), + target.playableStateNamespaceId(), + CHARACTER_ID, + target.playableStateScope(), + target.gameInstanceUuid(), + target.gameInstanceId(), + sessionId, + REGION_ID, + BigInteger.valueOf(12), + ISSUER_ID, + BigInteger.valueOf(7), + BigInteger.valueOf(3), + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + } + + 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", UUID.randomUUID().toString()); + carrier.put("leaseId", UUID.randomUUID().toString()); + 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"); + + carrier.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(candidate.tenantId().toString(), "1"), + "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", UUID.randomUUID().toString()); + tokenIdentity.put("issuanceRequestId", UUID.randomUUID().toString()); + tokenIdentity.put("tokenJti", UUID.randomUUID().toString()); + 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 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 TestSchema newTestSchema(String applicationName) { + String schema = "gs_account_member_lock_" + 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(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new TestSchema(schema, dataSource, dsl); + } + + private static DriverManagerDataSource dataSource(String schema, String applicationName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + String url = POSTGRES.getJdbcUrl(); + String separator = url.contains("?") ? "&" : "?"; + dataSource.setUrl( + url + separator + "currentSchema=" + schema + "&ApplicationName=" + applicationName); + 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 account-member lock-order schema", failure); + } + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for runtime lock-order test gate"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for runtime lock-order gate", interrupted); + } + } + + private static void awaitRuntimeRowLockWait(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%'" + + " AND query ILIKE '%FOR UPDATE%')", + applicationName), + "runtime lock wait query") + .get(0, Boolean.class); + if (Boolean.TRUE.equals(waiting)) return; + Thread.sleep(10); + } + throw new AssertionError("Member acknowledgement did not wait on the held runtime row"); + } + + private record LeaseBoundMemberRepairFixture( + CanonicalGameplayBindingInventoryRepository repository, + CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget, + CanonicalGameplayBindingTransitionRequest request) {} + + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} + + private static CanonicalGameplayAccountMemberRepairOperation operation() { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + CanonicalGameplayBindingRef bindingRef = + CanonicalGameplayBindingRef.of(tenantId, UUID.randomUUID(), UUID.randomUUID().toString()); + UUID accountIndexFence = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID coverageFence = UUID.randomUUID(); + BigInteger generation = BigInteger.valueOf(17); + BigInteger snapshotRevision = BigInteger.valueOf(23); + String member = + new CanonicalGameplayAccountIndexMember(bindingRef, generation, accountIndexFence).value(); + var obligation = + new CanonicalGameplayBindingAccountIndexObligation( + transitionId, + 0, + bindingRef, + accountId, + tenantId, + CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN, + generation, + null, + accountIndexFence, + CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS, + CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED, + BigInteger.valueOf(22), + CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED, + null, + null); + return new CanonicalGameplayAccountMemberRepairOperation( + transitionId, + operationId, + BigInteger.valueOf(4), + coverageFence, + snapshotRevision, + bindingRef, + accountId, + tenantId, + generation, + accountIndexFence, + obligation, + member, + BigInteger.valueOf(5)); + } + + private static byte[][] arguments(CanonicalGameplayAccountMemberRepairOperation operation) { + return new byte[][] { + ascii(operation.accountId().toString()), + ascii(operation.tenantId().toString()), + operation.bindingRef().bytes(), + ascii(operation.bindingGeneration().toString()), + ascii(operation.accountIndexFence().toString()), + ascii(operation.member()), + ascii(operation.transitionId().toString()), + ascii(operation.operationId().toString()), + ascii(operation.operationFence().toString()), + ascii(operation.coverageFence().toString()), + ascii(operation.inventorySnapshotRevision().toString()), + ascii(operation.accountControlEpoch().toString()) + }; + } + + private RedisClient createClient(String username, String password) { + RedisURI.Builder builder = + RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(PORT)) + .withTimeout(Duration.ofSeconds(3)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static byte[] key(UUID accountId) { + return ascii(PREFIX + accountId); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } +} 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 index b3084a7252..ba45bfd0b1 100644 --- 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 @@ -3,8 +3,18 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolVersion; import java.math.BigInteger; import java.nio.file.Path; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -18,7 +28,10 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingProvisionalCasEvidence; @@ -33,6 +46,7 @@ import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -49,7 +63,7 @@ class CanonicalGameplayBindingInventoryRepositoryIntegrationTest { 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 String ISSUER_ID = GameSessionAccountDelegationProfile.ISSUER; 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"); @@ -65,11 +79,18 @@ class CanonicalGameplayBindingInventoryRepositoryIntegrationTest { UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); private static final UUID PRIOR_TRANSITION_ID = UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final String MEMBER_REPAIR_PRINCIPAL = "gamesession_coord_app"; + private static final String MEMBER_REPAIR_PASSWORD = UUID.randomUUID().toString(); + private static final String MEMBER_REPAIR_ACCOUNT_KEY_PREFIX = "session:game:index:account:"; @Container static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + @Test void failsClosedWhenInventoryAbsenceCannotProveLegacyControllerAbsence() { String schema = "gs_binding_inventory_" + UUID.randomUUID().toString().replace("-", ""); @@ -211,6 +232,668 @@ void persistsFirstBindingAccountIndexReadbackWithoutPriorObligation() { } } + @Test + void acknowledgesOnlyTheFrozenNewBindingMemberAfterPhysicalRedisReadback() { + TestSchema testSchema = newTestSchema("gs_binding_local_member_"); + RedisMemberFixture redisFixture = null; + try { + redisFixture = startMemberRepairRedisFixture(); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); + var before = fixture.repository().readSnapshot(); + CanonicalGameplayAccountMemberRepairOperation operation = + fixture.repository().beginAccountMemberRepair(TRANSITION_ID); + assertThat(operation.transitionId()).isEqualTo(TRANSITION_ID); + assertThat(operation.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(operation.tenantId()).isEqualTo(TENANT_ID); + assertThat(operation.originalObligation().ordinal()).isZero(); + assertThat(operation.originalObligation().expectedPriorGeneration()).isNull(); + assertThat(operation.originalObligation().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED); + assertThat(operation.operationFence()).isEqualTo(BigInteger.ONE); + assertThat(operation.coverageFence()).isNotEqualTo(operation.accountIndexFence()); + assertThat(operation.accountControlEpoch()).isZero(); + assertThat(operation.inventorySnapshotRevision()).isEqualTo(before.inventoryRevision()); + assertThat(fixture.repository().beginAccountMemberRepair(TRANSITION_ID)).isEqualTo(operation); + assertThat(fixture.repository().readSnapshot()).isEqualTo(before); + + BigInteger candidateCoverageGeneration = + operation.inventorySnapshotRevision().add(BigInteger.ONE); + BigInteger candidateCompletedRevision = + operation.inventorySnapshotRevision().add(BigInteger.ONE); + String memberRepairOperationTable = "game_session_canonical_account_member_repair_operation"; + assertCheckConstraintViolation( + testSchema.dsl(), + "UPDATE " + + memberRepairOperationTable + + " SET status = 'ACKNOWLEDGED', coverage_generation = NULL," + + " readback_state = 'PRESENT', readback_member = ?," + + " completed_inventory_revision = ? WHERE operation_id = ? AND status = 'PENDING'", + operation.member(), + candidateCompletedRevision, + operation.operationId()); + assertCheckConstraintViolation( + testSchema.dsl(), + "UPDATE " + + memberRepairOperationTable + + " SET status = 'ACKNOWLEDGED', coverage_generation = ?," + + " readback_state = NULL, readback_member = ?," + + " completed_inventory_revision = ? WHERE operation_id = ? AND status = 'PENDING'", + candidateCoverageGeneration, + operation.member(), + candidateCompletedRevision, + operation.operationId()); + assertCheckConstraintViolation( + testSchema.dsl(), + "UPDATE " + + memberRepairOperationTable + + " SET status = 'ACKNOWLEDGED', coverage_generation = ?," + + " readback_state = 'PRESENT', readback_member = NULL," + + " completed_inventory_revision = ? WHERE operation_id = ? AND status = 'PENDING'", + candidateCoverageGeneration, + candidateCompletedRevision, + operation.operationId()); + assertCheckConstraintViolation( + testSchema.dsl(), + "UPDATE " + + memberRepairOperationTable + + " SET original_projection_state = 'PRESENT_AWAITING_COVERAGE'," + + " original_projection_member = ?, original_projection_inventory_revision = NULL" + + " WHERE operation_id = ? AND status = 'PENDING'", + operation.member(), + operation.operationId()); + var pendingAfterMalformedCompletions = + testSchema + .dsl() + .fetchOne( + "SELECT status, coverage_generation, readback_state, readback_member," + + " original_projection_state, original_projection_inventory_revision" + + " FROM " + + memberRepairOperationTable + + " WHERE operation_id = ?", + operation.operationId()); + assertThat(pendingAfterMalformedCompletions.get("status", String.class)).isEqualTo("PENDING"); + assertThat(pendingAfterMalformedCompletions.get("coverage_generation")).isNull(); + assertThat(pendingAfterMalformedCompletions.get("readback_state", String.class)).isNull(); + assertThat(pendingAfterMalformedCompletions.get("readback_member", String.class)).isNull(); + assertThat(pendingAfterMalformedCompletions.get("original_projection_state", String.class)) + .isEqualTo("REQUIRED"); + assertThat(pendingAfterMalformedCompletions.get("original_projection_inventory_revision")) + .isNull(); + + var controlBefore = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + ACCOUNT_ID), + "preparation positively persisted account coverage control"); + assertThat(controlBefore.get("state", String.class)).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat( + Objects.requireNonNull( + controlBefore.get("last_operation_fence"), "account coverage control fence") + .toString()) + .isEqualTo("0"); + assertThat(controlBefore.get("current_operation_id", UUID.class)).isNull(); + assertThat(controlBefore.get("account_admission_fence", UUID.class)).isNull(); + + var redisOwner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + redisFixture.applicationClient(), + RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + var acknowledgement = + new CanonicalGameplayAccountMemberRepairOwner( + testSchema.dsl(), + redisFixture.applicationClient(), + RedisScriptCatalog.loadInstalled(getClass().getClassLoader())) + .repair(TRANSITION_ID); + assertThat(acknowledgement.schemaVersion()).isEqualTo(2); + assertThat(acknowledgement.operationId()).isEqualTo(operation.operationId()); + assertThat(acknowledgement.action()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN); + assertThat(acknowledgement.readback().member()).isEqualTo(operation.member()); + assertThat(acknowledgement.coverageGeneration()) + .isGreaterThan(operation.inventorySnapshotRevision()); + assertThat(acknowledgement.accountCoverageState().name()) + .isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(acknowledgement.accountCoverageOperationId().name()).isEqualTo("NOT_APPLICABLE"); + assertThat(acknowledgement.accountCoverageLifecycle().name()).isEqualTo("NOT_APPLICABLE"); + assertThat(acknowledgement.accountCoverageOperationFence().name()) + .isEqualTo("NOT_APPLICABLE"); + assertThat(acknowledgement.accountAdmissionFence().name()).isEqualTo("NOT_APPLICABLE"); + assertThat(acknowledgement.historicalAccountAdmissionFence().name()) + .isEqualTo("NOT_APPLICABLE"); + assertThat(acknowledgement.resolvedScope().name()).isEqualTo("NOT_APPLICABLE"); + + var completed = fixture.repository().readSnapshot(); + assertThat(completed.transitions()) + .singleElement() + .satisfies( + transition -> + assertThat(transition.status()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL)); + assertThat(completed.bindings()) + .singleElement() + .satisfies( + candidate -> { + assertThat(candidate.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL); + assertThat(candidate.accountIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); + }); + assertThat(completed.accountIndexObligations()) + .singleElement() + .satisfies( + obligation -> { + assertThat(obligation.status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED); + assertThat(obligation.projectionState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE); + assertThat(obligation.projectedMember()).isEqualTo(operation.member()); + }); + + var controlAfter = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT * FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + ACCOUNT_ID), + "account coverage control remains durably present"); + assertThat(controlAfter.get("state", String.class)).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat( + Objects.requireNonNull( + controlAfter.get("last_operation_fence"), "account coverage control fence") + .toString()) + .isEqualTo( + Objects.requireNonNull( + controlBefore.get("last_operation_fence"), "account coverage control fence") + .toString()); + assertThat(controlAfter.get("current_operation_id", UUID.class)).isNull(); + assertThat(controlAfter.get("account_admission_fence", UUID.class)).isNull(); + var persistedOperation = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT * FROM game_session_canonical_account_member_repair_operation" + + " WHERE operation_id = ?", + operation.operationId()), + "binding-local repair operation is persisted"); + assertThat(persistedOperation.get("status", String.class)).isEqualTo("ACKNOWLEDGED"); + assertThat(persistedOperation.get("coverage_generation").toString()) + .isEqualTo(acknowledgement.coverageGeneration().toString()); + assertThat(persistedOperation.get("readback_member", String.class)) + .isEqualTo(operation.member()); + assertThat(persistedOperation.get("account_control_state", String.class)) + .isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(persistedOperation.get("account_control_epoch").toString()).isEqualTo("0"); + assertThat(persistedOperation.get("inventory_snapshot_revision").toString()) + .isEqualTo(operation.inventorySnapshotRevision().toString()); + assertThat(persistedOperation.get("operation_fence").toString()) + .isEqualTo(operation.operationFence().toString()); + assertThat(persistedOperation.get("coverage_fence", UUID.class)) + .isEqualTo(operation.coverageFence()); + + var completedEvidence = fixture.repository().readProvisionalCasEvidence(TRANSITION_ID); + assertThat(completedEvidence.candidate().accountIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .IndexState.ACKNOWLEDGED); + assertThat(completedEvidence.candidate().issuerIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingInventoryEntry + .IndexState.REPAIR_REQUIRED); + + // Recreate the package-private SQL owner to model a worker restart after a lost response. + var restartedRepository = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + var retryOperation = restartedRepository.beginAccountMemberRepair(TRANSITION_ID); + assertThat(retryOperation).isEqualTo(operation); + var retryReadback = redisOwner.projectAndRead(retryOperation); + var retryAcknowledgement = + restartedRepository.acknowledgeAccountMemberRepair(retryOperation, retryReadback); + assertThat(retryAcknowledgement).isEqualTo(acknowledgement); + assertThat(fixture.repository().readSnapshot()).isEqualTo(completed); + } finally { + if (redisFixture != null) { + redisFixture.deleteAccountKey(ACCOUNT_ID); + redisFixture.close(); + } + dropSchema(testSchema.schema()); + } + } + + @Test + void missingAccountCoverageControlRowCannotAuthorizeMemberRepair() { + TestSchema testSchema = newTestSchema("gs_member_missing_"); + try { + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); + assertThat( + testSchema + .dsl() + .execute( + "DELETE FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ?", + ACCOUNT_ID)) + .isEqualTo(1); + + assertThatThrownBy(() -> fixture.repository().beginAccountMemberRepair(TRANSITION_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("account-coverage fence is missing"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT count(*) AS row_count FROM" + + " game_session_canonical_account_member_repair_operation") + .get("row_count", Long.class)) + .isZero(); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void memberRepairPreservesAnEarlierPresentObservationUntilActualAcknowledgement() { + TestSchema testSchema = newTestSchema("gs_member_present_"); + RedisMemberFixture redisFixture = null; + try { + redisFixture = startMemberRepairRedisFixture(); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); + String member = + CanonicalGameplayAccountIndexMember.of(fixture.evidence().candidate()).value(); + + // The old owner records PRESENT_AWAITING_COVERAGE but does not satisfy the obligation. + var historicalObservation = + fixture.repository().markCandidateAccountIndexPresent(fixture.evidence(), member); + assertThat(historicalObservation.state()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexProjectionReceipt.State + .PRESENT_AWAITING_COVERAGE); + var beforeRepair = fixture.repository().readSnapshot(); + assertThat(beforeRepair.accountIndexObligations().getFirst().status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED); + + var operation = fixture.repository().beginAccountMemberRepair(TRANSITION_ID); + assertThat(operation.originalObligation().projectionState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE); + assertThat(operation.originalObligation().projectedMember()).isEqualTo(member); + assertThat(operation.originalObligation().inventoryRevision()) + .isEqualTo(historicalObservation.projectionInventoryRevision()); + assertThat(fixture.repository().readSnapshot()).isEqualTo(beforeRepair); + + var redisOwner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + redisFixture.applicationClient(), + RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + var readback = redisOwner.projectAndRead(operation); + var acknowledgement = + fixture.repository().acknowledgeAccountMemberRepair(operation, readback); + assertThat(acknowledgement.member()).isEqualTo(member); + assertThat(fixture.repository().readSnapshot().accountIndexObligations()) + .singleElement() + .satisfies( + obligation -> { + assertThat(obligation.status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED); + assertThat(obligation.projectionState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE); + assertThat(obligation.projectedMember()).isEqualTo(member); + }); + } finally { + if (redisFixture != null) { + redisFixture.deleteAccountKey(ACCOUNT_ID); + redisFixture.close(); + } + dropSchema(testSchema.schema()); + } + } + + @Test + void changedNoActiveControlFenceRejectsRedisReadbackAcknowledgement() { + TestSchema testSchema = newTestSchema("gs_member_fence_"); + RedisMemberFixture redisFixture = null; + try { + redisFixture = startMemberRepairRedisFixture(); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); + // This is a legal NO_ACTIVE row after an earlier completed account-wide lifecycle. The + // fixture advances only the durable epoch; it does not manufacture ACTIVE coverage proof. + assertThat( + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 1" + + " WHERE account_id = ? AND state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'" + + " AND last_operation_fence = 0", + ACCOUNT_ID)) + .isEqualTo(1); + CanonicalGameplayAccountMemberRepairOperation operation = + fixture.repository().beginAccountMemberRepair(TRANSITION_ID); + assertThat(operation.accountControlEpoch()).isEqualTo(BigInteger.ONE); + var redisOwner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + redisFixture.applicationClient(), + RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + var readback = redisOwner.projectAndRead(operation); + + // A completed account-wide lifecycle may return to NO_ACTIVE with a later durable epoch. + // This controlled row advancement tests stale-result rejection only; it does not fabricate + // an ACTIVE operation or establish positive account-wide recovery proof. + assertThat( + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 2" + + " WHERE account_id = ? AND state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'" + + " AND last_operation_fence = 1", + ACCOUNT_ID)) + .isEqualTo(1); + + assertThatThrownBy( + () -> fixture.repository().acknowledgeAccountMemberRepair(operation, readback)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("control fence changed"); + var snapshot = fixture.repository().readSnapshot(); + assertThat(snapshot.accountIndexObligations()) + .singleElement() + .satisfies( + obligation -> + assertThat(obligation.status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED)); + assertThat(snapshot.bindings()) + .singleElement() + .satisfies( + candidate -> + assertThat(candidate.accountIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED)); + var pending = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT status, coverage_generation, readback_member" + + " FROM game_session_canonical_account_member_repair_operation" + + " WHERE operation_id = ?", + operation.operationId()), + "pending member-repair row remains retained"); + assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); + assertThat(pending.get("coverage_generation")).isNull(); + assertThat(pending.get("readback_member", String.class)).isNull(); + } finally { + if (redisFixture != null) { + redisFixture.deleteAccountKey(ACCOUNT_ID); + redisFixture.close(); + } + dropSchema(testSchema.schema()); + } + } + + @Test + void acknowledgedNewMemberRepairStaysRetainedAcrossLaterAccountControlEpoch() { + TestSchema testSchema = newTestSchema("gs_member_later_epoch_"); + RedisMemberFixture redisFixture = null; + try { + redisFixture = startMemberRepairRedisFixture(); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); + var repository = fixture.repository(); + CanonicalGameplayAccountMemberRepairOperation operation = + repository.beginAccountMemberRepair(TRANSITION_ID); + var redisOwner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + redisFixture.applicationClient(), + RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + var readback = redisOwner.projectAndRead(operation); + var acknowledgement = repository.acknowledgeAccountMemberRepair(operation, readback); + var operationTable = "game_session_canonical_account_member_repair_operation"; + var acknowledgedRow = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT * FROM " + operationTable + " WHERE operation_id = ?", + operation.operationId()), + "acknowledged member-repair operation remains persisted"); + var acknowledgedSnapshot = repository.readSnapshot(); + assertThat(acknowledgedRow.get("status", String.class)).isEqualTo("ACKNOWLEDGED"); + assertThat(acknowledgedRow.get("coverage_generation").toString()) + .isEqualTo(acknowledgement.coverageGeneration().toString()); + + // This valid synthetic intent row exercises the durable INTENT control state. It is not an + // account-wide owner operation or evidence that a later lifecycle completed successfully. + UUID intentId = UUID.randomUUID(); + UUID plannedAdmissionFence = UUID.randomUUID(); + String digest = "sha256:" + "0".repeat(64); + assertThat( + testSchema + .dsl() + .execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent " + + "(operation_id, request_id, account_id, operation_fence, " + + "planned_account_admission_fence, inventory_snapshot_revision, " + + "legacy_cohort_id, legacy_owner_operation_id, legacy_writer_fence, " + + "legacy_source_snapshot_revision, legacy_canonical_inventory_revision, " + + "legacy_namespace_index_readback_revision, legacy_evidence_digest, " + + "intent_state, cohort_row_count, cohort_digest, barrier_target_count, " + + "barrier_target_digest) " + + "VALUES (?, ?, ?, 1, ?, 1, ?, ?, ?, 1, 1, 1, ?, " + + "'ACQUISITION_INTENT', 0, ?, 0, ?)", + intentId, + UUID.randomUUID(), + ACCOUNT_ID, + plannedAdmissionFence, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + digest, + digest, + digest)) + .isEqualTo(1); + assertThat( + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_account_coverage_control " + + "SET state = 'ACQUISITION_INTENT', last_operation_fence = 1, " + + "current_operation_id = NULL, current_fence_intent_id = ?, " + + "current_operation_fence = 1, account_admission_fence = ?, " + + "historical_account_admission_fence = NULL, coverage_fence = NULL, " + + "inventory_snapshot_revision = 1, coverage_generation = NULL " + + "WHERE account_id = ? AND state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' " + + "AND last_operation_fence = 0", + intentId, + plannedAdmissionFence, + ACCOUNT_ID)) + .isEqualTo(1); + assertThatThrownBy(() -> repository.readProvisionalCasEvidence(TRANSITION_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy(() -> repository.beginAccountMemberRepair(TRANSITION_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + + // Model a controlled later return to NO_ACTIVE at a higher fence. This proves the old + // binding-local operation cannot be reanchored to the newer epoch; it is not release proof. + assertThat( + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_account_coverage_control " + + "SET state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', last_operation_fence = 2, " + + "current_operation_id = NULL, current_fence_intent_id = NULL, " + + "current_operation_fence = NULL, account_admission_fence = NULL, " + + "historical_account_admission_fence = NULL, coverage_fence = NULL, " + + "inventory_snapshot_revision = NULL, coverage_generation = NULL " + + "WHERE account_id = ? AND state = 'ACQUISITION_INTENT' " + + "AND last_operation_fence = 1", + ACCOUNT_ID)) + .isEqualTo(1); + assertThatThrownBy(() -> repository.readProvisionalCasEvidence(TRANSITION_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy(() -> repository.beginAccountMemberRepair(TRANSITION_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + + var retainedOperation = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT * FROM " + operationTable + " WHERE operation_id = ?", + operation.operationId()), + "original operation remains retained after account-control advancement"); + assertThat(retainedOperation).isEqualTo(acknowledgedRow); + assertThat(repository.readSnapshot()).isEqualTo(acknowledgedSnapshot); + assertThat(retainedOperation.get("operation_id", UUID.class)) + .isEqualTo(operation.operationId()); + assertThat(retainedOperation.get("operation_fence").toString()) + .isEqualTo(operation.operationFence().toString()); + assertThat(retainedOperation.get("coverage_fence", UUID.class)) + .isEqualTo(operation.coverageFence()); + assertThat(retainedOperation.get("inventory_snapshot_revision").toString()) + .isEqualTo(operation.inventorySnapshotRevision().toString()); + assertThat(retainedOperation.get("account_control_state", String.class)) + .isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(retainedOperation.get("account_control_epoch").toString()) + .isEqualTo(operation.accountControlEpoch().toString()); + assertThat(retainedOperation.get("status", String.class)).isEqualTo("ACKNOWLEDGED"); + assertThat(retainedOperation.get("coverage_generation").toString()) + .isEqualTo(acknowledgement.coverageGeneration().toString()); + assertThat(retainedOperation.get("readback_member", String.class)) + .isEqualTo(operation.member()); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_account_index_obligation " + + "WHERE transition_id = ? AND obligation_ordinal = 0", + TRANSITION_ID) + .get("status", String.class)) + .isEqualTo("ACKNOWLEDGED"); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT lifecycle FROM game_session_canonical_gameplay_binding_inventory " + + "WHERE transition_id = ?", + TRANSITION_ID) + .get("lifecycle", String.class)) + .isEqualTo("PROVISIONAL"); + } finally { + if (redisFixture != null) { + redisFixture.deleteAccountKey(ACCOUNT_ID); + redisFixture.close(); + } + dropSchema(testSchema.schema()); + } + } + + @Test + void leaseBoundRuntimeFenceTriggerRejectsRawAbortAfterAccountMemberProjection() { + TestSchema testSchema = newTestSchema("gs_member_stale_"); + RedisMemberFixture redisFixture = null; + try { + redisFixture = startMemberRepairRedisFixture(); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); + CanonicalGameplayAccountMemberRepairOperation operation = + fixture.repository().beginAccountMemberRepair(TRANSITION_ID); + var redisOwner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + redisFixture.applicationClient(), + RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + redisOwner.projectAndRead(operation); + + assertThatThrownBy( + () -> + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition" + + " SET status = 'ABORTED' WHERE transition_id = ?" + + " AND status = 'PROVISIONAL'", + TRANSITION_ID)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure) + .hasMessageContaining( + "A lease-bound runtime fence cannot be released without terminal owner reconciliation"); + }); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + TRANSITION_ID) + .get("status", String.class)) + .isEqualTo("PROVISIONAL"); + var pending = + Objects.requireNonNull( + testSchema + .dsl() + .fetchOne( + "SELECT status, coverage_generation, readback_member" + + " FROM game_session_canonical_account_member_repair_operation" + + " WHERE operation_id = ?", + operation.operationId()), + "original member operation remains retained after stale transition rejection"); + assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); + assertThat(pending.get("coverage_generation")).isNull(); + assertThat(pending.get("readback_member", String.class)).isNull(); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_account_index_obligation" + + " WHERE transition_id = ? AND obligation_ordinal = 0", + TRANSITION_ID) + .get("status", String.class)) + .isEqualTo("REQUIRED"); + } finally { + if (redisFixture != null) { + redisFixture.deleteAccountKey(ACCOUNT_ID); + redisFixture.close(); + } + dropSchema(testSchema.schema()); + } + } + @Test void readsLeaseBoundAdmissionDecisionInReadOnlyTransaction() { TestSchema testSchema = newTestSchema("gs_binding_readonly_decision_"); @@ -493,6 +1176,8 @@ void advancesGenerationAtomicallyAndKeepsPriorControllerActiveUntilExternalCas() assertThat(prepared.inventoryRevision()).isEqualTo(BigInteger.valueOf(9)); var snapshot = new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot(); assertThat(snapshot.bindings()).hasSize(2); + assertThat(snapshot.bindings()) + .allSatisfy(row -> assertThat(row.identity().issuerId()).isEqualTo(ISSUER_ID)); assertThat(snapshot.bindings()) .anySatisfy( row -> @@ -697,6 +1382,53 @@ private static TestSchema newTestSchema(String prefix, String applicationName) { return new TestSchema(schema, dataSource, dslForSchema(dataSource, schema)); } + private static RedisMemberFixture startMemberRepairRedisFixture() { + RedisURI bootstrapUri = + RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)).build(); + bootstrapUri.setTimeout(Duration.ofSeconds(5)); + RedisClient bootstrapClient = RedisClient.create(bootstrapUri); + try { + try (StatefulRedisConnection connection = + bootstrapClient.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + MEMBER_REPAIR_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(MEMBER_REPAIR_PASSWORD) + .keyPattern(MEMBER_REPAIR_ACCOUNT_KEY_PREFIX + "*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.SADD) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.SISMEMBER)); + } + } catch (RuntimeException failure) { + bootstrapClient.shutdown(); + throw failure; + } + + RedisURI applicationUri = + RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)) + .withAuthentication(MEMBER_REPAIR_PRINCIPAL, MEMBER_REPAIR_PASSWORD) + .build(); + applicationUri.setTimeout(Duration.ofSeconds(5)); + RedisClient applicationClient = RedisClient.create(applicationUri); + applicationClient.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(ProtocolVersion.RESP2) + .build()); + return new RedisMemberFixture(bootstrapClient, applicationClient); + } + private static void awaitLatch(CountDownLatch latch) { try { if (!latch.await(10, TimeUnit.SECONDS)) { @@ -746,6 +1478,21 @@ private record PreparedLeaseBoundFirstBinding( private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} + private record RedisMemberFixture(RedisClient bootstrapClient, RedisClient applicationClient) { + void deleteAccountKey(UUID accountId) { + String key = MEMBER_REPAIR_ACCOUNT_KEY_PREFIX + accountId; + try (StatefulRedisConnection connection = + bootstrapClient.connect(io.lettuce.core.codec.StringCodec.UTF8)) { + connection.sync().del(key); + } + } + + void close() { + applicationClient.shutdown(); + bootstrapClient.shutdown(); + } + } + private static CanonicalGameplayBindingTransitionRequest transferRequest( String candidateSessionId, CanonicalGameplayBindingIdentity prior) { return new CanonicalGameplayBindingTransitionRequest( @@ -919,6 +1666,14 @@ static void seedSyntheticVerifiedLegacyDisposition(DSLContext dsl) { + " WHERE singleton_id = 1"); } + private static void assertCheckConstraintViolation( + DSLContext dsl, String statement, Object... values) { + assertThatThrownBy(() -> dsl.execute(statement, values)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + } + private static CanonicalIssuerReservationFenceEvidence reservation(UUID reservationFence) { return new CanonicalIssuerReservationFenceEvidence( RESERVATION_ID, 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 index 9e029c8d3a..de13cb4d06 100644 --- 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 @@ -8,6 +8,7 @@ import java.sql.DriverManager; import java.sql.Timestamp; import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -476,7 +477,7 @@ private static byte[] seedCandidateAndPreparedTransition( UUID accountId = UUID.randomUUID(); UUID characterId = UUID.randomUUID(); UUID regionId = UUID.randomUUID(); - UUID issuerId = UUID.randomUUID(); + String issuerId = GameSessionAccountDelegationProfile.ISSUER; UUID accountIndexFence = UUID.randomUUID(); UUID issuerReservationId = UUID.randomUUID(); byte[] candidateRef = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..e4e505081c --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest.java @@ -0,0 +1,782 @@ +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.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +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 receiving proof for the forward-only canonical Account issuer storage migration. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String CANONICAL_ISSUER = "firemud-account-service"; + private static final String FOREIGN_ISSUER = "foreign-account-service"; + private static final String NON_CANONICAL_ACCOUNT_ISSUER = "Firemud-account-service"; + private static final String LEGACY_ISSUER = "77777777-7777-4777-8777-777777777777"; + private static final String SESSION_ID = "abababab-abab-4bab-8bab-abababababab"; + 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 LEGACY_ISSUER_ID = UUID.fromString(LEGACY_ISSUER); + 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 COVERAGE_OPERATION_ID = + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final long ISSUER_COVERAGE_FENCE = 13L; + private static final UUID COVERAGE_FENCE = + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID COVERAGE_REQUEST_ID = + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID LEGACY_COHORT_ID = + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID LEGACY_OWNER_OPERATION_ID = + UUID.fromString("12121212-1212-4212-8212-121212121212"); + private static final UUID LEGACY_WRITER_FENCE = + UUID.fromString("13131313-1313-4313-8313-131313131313"); + private static final UUID ADMISSION_FENCE = + UUID.fromString("14141414-1414-4414-8414-141414141414"); + private static final byte[] BINDING_REF = new byte[] {0x01, 0x23, 0x45}; + private static final List RECREATED_UUID_DEPENDENT_CONSTRAINTS = + List.of( + "chk_gs_canonical_gameplay_binding_inventory_identity", + "chk_gs_canonical_issuer_partition_reservation", + "chk_gs_canonical_account_coverage_snapshot_inventory", + "chk_gs_canonical_account_coverage_snapshot_reservation"); + private static final List ACCOUNT_ISSUER_CONSTRAINTS = + List.of( + "chk_gs_gameplay_inventory_account_issuer", + "chk_gs_issuer_reservation_account_issuer", + "chk_gs_snapshot_inventory_account_issuer", + "chk_gs_snapshot_transition_account_issuer", + "chk_gs_snapshot_reservation_account_issuer"); + private static final List PRESERVED_TABLES = + List.of( + "game_session_canonical_binding_inventory_clock", + "game_session_canonical_binding_legacy_disposition", + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_binding_transition", + "game_session_canonical_binding_account_index_obligation", + "game_session_canonical_issuer_partition_reservation", + "game_session_canonical_binding_issuer_index_obligation", + "game_session_canonical_binding_region_bridge_obligation", + "game_session_canonical_account_coverage_control", + "game_session_canonical_account_coverage_operation", + "game_session_canonical_account_coverage_snapshot_inventory", + "game_session_canonical_account_coverage_snapshot_transition", + "game_session_canonical_account_coverage_snapshot_obligation", + "game_session_canonical_account_coverage_snapshot_reservation", + "gs_canonical_account_coverage_snapshot_issuer_obligation", + "gs_canonical_account_coverage_snapshot_region_obligation"); + private static final List ISSUER_FIELDS = + List.of( + field( + "game_session_canonical_gameplay_binding_inventory", + "issuer_id", + "binding_ref = ?", + BINDING_REF), + field( + "game_session_canonical_issuer_partition_reservation", + "issuer_id", + "reservation_id = ?", + RESERVATION_ID), + field( + "game_session_canonical_account_coverage_snapshot_inventory", + "issuer_id", + "operation_id = ? AND row_ordinal = ?", + COVERAGE_OPERATION_ID, + 0L), + field( + "game_session_canonical_account_coverage_snapshot_transition", + "candidate_issuer_id", + "operation_id = ? AND row_ordinal = ?", + COVERAGE_OPERATION_ID, + 0L), + field( + "game_session_canonical_account_coverage_snapshot_reservation", + "issuer_id", + "operation_id = ? AND row_ordinal = ?", + COVERAGE_OPERATION_ID, + 0L)); + private static final List CANONICAL_INSERT_PROBES = + List.of( + "INSERT INTO game_session_canonical_gameplay_binding_inventory " + + "SELECT (jsonb_populate_record(NULL::game_session_canonical_gameplay_binding_inventory, " + + "to_jsonb(retained) || jsonb_build_object('binding_ref', decode('02468ace', 'hex'), " + + "'issuer_id', 'firemud-account-service', " + + "'issuer_reservation_id', '15151515-1515-4515-8515-151515151515', " + + "'transition_id', '16161616-1616-4616-8616-161616161616', 'inventory_revision', 18))).* " + + "FROM game_session_canonical_gameplay_binding_inventory retained " + + "WHERE binding_ref = decode('012345', 'hex')", + "INSERT INTO game_session_canonical_issuer_partition_reservation " + + "SELECT (jsonb_populate_record(NULL::game_session_canonical_issuer_partition_reservation, " + + "to_jsonb(retained) || jsonb_build_object(" + + "'reservation_id', '17171717-1717-4717-8717-171717171717', " + + "'issuer_id', 'firemud-account-service'))).* " + + "FROM game_session_canonical_issuer_partition_reservation retained " + + "WHERE reservation_id = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'", + "INSERT INTO game_session_canonical_account_coverage_snapshot_inventory " + + "SELECT (jsonb_populate_record(NULL::game_session_canonical_account_coverage_snapshot_inventory, " + + "to_jsonb(retained) || jsonb_build_object('row_ordinal', 1, " + + "'issuer_id', 'firemud-account-service'))).* " + + "FROM game_session_canonical_account_coverage_snapshot_inventory retained " + + "WHERE operation_id = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' AND row_ordinal = 0", + "INSERT INTO game_session_canonical_account_coverage_snapshot_transition " + + "SELECT (jsonb_populate_record(NULL::game_session_canonical_account_coverage_snapshot_transition, " + + "to_jsonb(retained) || jsonb_build_object('row_ordinal', 1, " + + "'candidate_issuer_id', 'firemud-account-service'))).* " + + "FROM game_session_canonical_account_coverage_snapshot_transition retained " + + "WHERE operation_id = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' AND row_ordinal = 0", + "INSERT INTO game_session_canonical_account_coverage_snapshot_reservation " + + "SELECT (jsonb_populate_record(NULL::game_session_canonical_account_coverage_snapshot_reservation, " + + "to_jsonb(retained) || jsonb_build_object('row_ordinal', 1, " + + "'reservation_id', '18181818-1818-4818-8818-181818181818', " + + "'issuer_id', 'firemud-account-service'))).* " + + "FROM game_session_canonical_account_coverage_snapshot_reservation retained " + + "WHERE operation_id = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc' AND row_ordinal = 0"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void convertsIssuerStorageWithoutRelabelingLegacyRowsOrChangingEvidence() throws Exception { + String schema = "gs_account_issuer_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + try { + Flyway oldSchema = flyway(dataSource, schema, MigrationVersion.fromVersion("1022")); + oldSchema.migrate(); + oldSchema.validate(); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1022"); + + seedLegacyUuidCohort(dsl); + Map> beforeMigration = rowSnapshots(dsl); + List historyBeforeMigration = historySnapshot(dsl); + Map constraintsBeforeMigration = constraintSnapshot(dsl); + Map indexesBeforeMigration = indexSnapshot(dsl); + for (String table : PRESERVED_TABLES) { + assertThat(beforeMigration.get(table)).as(table).hasSize(1); + } + + Flyway current = flyway(dataSource, schema, MigrationVersion.fromVersion("1025")); + current.migrate(); + current.validate(); + + assertThat( + dsl.fetchSingle("SELECT count(*) FROM flyway_schema_history WHERE version = '1025'") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1025'") + .get(0, String.class)) + .isEqualTo("V1025__canonical_account_issuer_identity.sql"); + assertIssuerColumnsAreBoundedText(dsl); + assertCanonicalIssuerGuardsAreNotValidated(dsl); + assertRecreatedIdentityChecksRemainValidated(dsl); + assertLegacyIssuerValues(dsl); + assertThatThrownBy(() -> new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot()) + .satisfies( + failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "Unsupported issuer identity; expected exact Account issuer " + + "firemud-account-service; legacy UUID issuer identities require " + + "explicit recovery"); + }); + assertThat(rowSnapshots(dsl)).isEqualTo(beforeMigration); + assertThat(historySnapshot(dsl).subList(0, historyBeforeMigration.size())) + .containsExactlyElementsOf(historyBeforeMigration); + assertThat(constraintSnapshot(dsl)).isEqualTo(constraintsBeforeMigration); + assertThat(indexSnapshot(dsl)).isEqualTo(indexesBeforeMigration); + assertThat( + dsl.fetchSingle( + "SELECT disposition_state FROM game_session_canonical_binding_legacy_disposition " + + "WHERE singleton_id = 1") + .get(0, String.class)) + .isEqualTo("REQUIRED"); + assertThat( + dsl.fetchSingle( + "SELECT state FROM game_session_canonical_account_coverage_control WHERE account_id = ?", + ACCOUNT_ID) + .get(0, String.class)) + .isEqualTo("ACTIVE"); + assertThat( + dsl.fetchSingle( + "SELECT snapshot_state FROM game_session_canonical_account_coverage_operation " + + "WHERE operation_id = ?", + COVERAGE_OPERATION_ID) + .get(0, String.class)) + .isEqualTo("BLOCKED"); + + assertExactIssuerValueIsAcceptedForNewRows(dataSource); + assertNonCanonicalIssuerWritesAreRejected(dsl); + assertLegacyIssuerValues(dsl); + assertThat(rowSnapshots(dsl)).isEqualTo(beforeMigration); + + List migratedHistory = historySnapshot(dsl); + Map> migratedRows = rowSnapshots(dsl); + Flyway restarted = flyway(dataSource, schema, MigrationVersion.fromVersion("1025")); + restarted.migrate(); + restarted.validate(); + assertThat(historySnapshot(dsl)).containsExactlyElementsOf(migratedHistory); + assertIssuerColumnsAreBoundedText(dsl); + assertCanonicalIssuerGuardsAreNotValidated(dsl); + assertRecreatedIdentityChecksRemainValidated(dsl); + assertLegacyIssuerValues(dsl); + assertThat(rowSnapshots(dsl)).isEqualTo(migratedRows); + assertThat(constraintSnapshot(dsl)).isEqualTo(constraintsBeforeMigration); + assertThat(indexSnapshot(dsl)).isEqualTo(indexesBeforeMigration); + } finally { + dropSchema(schema); + } + } + + private static void seedLegacyUuidCohort(DSLContext dsl) { + // These rows model the old UUID column encoding and retained repair evidence only. They do not + // assert Account, membership, grant, token, lease, issuer-source, or gameplay authority. + dsl.execute( + "UPDATE game_session_canonical_binding_inventory_clock " + + "SET inventory_revision = 17 WHERE singleton_id = 1"); + 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', ?, 23, ?, 5, ?, 2, ?, 7, 3, 4, 8, 2, ?, ?, ?, " + + "'CANDIDATE_PREPARED', 'REPAIR_REQUIRED', 'REPAIR_REQUIRED', 17)", + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + GAME_INSTANCE_ID, + SESSION_ID, + REGION_ID, + LEGACY_ISSUER_ID, + ACCOUNT_INDEX_FENCE, + RESERVATION_ID, + TRANSITION_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, ?, ?, 'PREPARED', 17)", + TRANSITION_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + BINDING_REF, + ACCOUNT_INDEX_FENCE, + RESERVATION_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 (?, ?, ?, ?, ?, 23, ?, 5, ?, ?, 7, ?, ?, 'SHARED', ?, 2, 2, 3, 4, 8, " + + "'RESERVED', ?, ?, 11, ?, 17, 17)", + RESERVATION_ID, + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + GAME_INSTANCE_ID, + SESSION_ID, + TRANSITION_ID, + LEGACY_ISSUER_ID, + NAMESPACE_ID, + CHARACTER_ID, + REGION_ID, + RESERVATION_FENCE, + COVERAGE_OPERATION_ID, + ISSUER_COVERAGE_FENCE); + + dsl.execute( + "INSERT INTO game_session_canonical_binding_account_index_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', 5, NULL, ?, 'BEFORE_FINAL_CAS', 'REQUIRED', 17)", + TRANSITION_ID, + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + ACCOUNT_INDEX_FENCE); + + dsl.execute( + "INSERT INTO game_session_canonical_binding_issuer_index_obligation (" + + "transition_id, binding_ref, binding_generation, reservation_id, status, inventory_revision) " + + "VALUES (?, ?, 5, ?, 'REQUIRED', 17)", + TRANSITION_ID, + BINDING_REF, + RESERVATION_ID); + + dsl.execute( + "INSERT INTO game_session_canonical_binding_region_bridge_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 (?, ?, 5, ?, ?, ?, 23, ?, ?, 2, 'REQUIRED', 17)", + TRANSITION_ID, + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + GAME_INSTANCE_ID, + SESSION_ID, + REGION_ID); + + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_control (account_id, state, last_operation_fence) " + + "VALUES (?, 'NO_ACTIVE_ACCOUNT_WIDE_FLOW', 0)", + ACCOUNT_ID); + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_operation (" + + "operation_id, request_id, account_id, legacy_cohort_id, legacy_owner_operation_id, " + + "legacy_writer_fence, legacy_source_snapshot_revision, " + + "legacy_canonical_inventory_revision, legacy_namespace_index_readback_revision, " + + "legacy_evidence_digest, lifecycle, operation_fence, coverage_fence, " + + "account_admission_fence, historical_account_admission_fence, resolved_scope_kind, " + + "snapshot_state, blocked_reason, inventory_snapshot_revision, coverage_generation, " + + "redis_member_count, redis_member_set_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, 13, 17, 19, ?, 'ACTIVE', 11, ?, ?, NULL, " + + "'ACCOUNT_WIDE', 'BLOCKED', 'UNRESOLVED_OBLIGATION', 17, NULL, NULL, NULL)", + COVERAGE_OPERATION_ID, + COVERAGE_REQUEST_ID, + ACCOUNT_ID, + LEGACY_COHORT_ID, + LEGACY_OWNER_OPERATION_ID, + LEGACY_WRITER_FENCE, + "sha256:" + "a".repeat(64), + COVERAGE_FENCE, + ADMISSION_FENCE); + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control " + + "SET state = 'ACTIVE', last_operation_fence = 11, current_operation_id = ?, " + + "current_operation_fence = 11, account_admission_fence = ?, coverage_fence = ?, " + + "inventory_snapshot_revision = 17 WHERE account_id = ?", + COVERAGE_OPERATION_ID, + ADMISSION_FENCE, + COVERAGE_FENCE, + ACCOUNT_ID); + + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_snapshot_inventory (" + + "operation_id, row_ordinal, 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, transition_id, member_transition_id, lifecycle, " + + "account_index_state, issuer_index_state, inventory_revision, action, exact_member, " + + "expected_readback_state, redis_readback_state, redis_readback_member) " + + "VALUES (?, 0, ?, ?, ?, ?, ?, 'SHARED', ?, 23, ?, 5, ?, 2, ?, 7, 3, 4, 8, 2, ?, ?, ?, " + + "'CANDIDATE_PREPARED', 'REPAIR_REQUIRED', 'REPAIR_REQUIRED', 17, 'BLOCKED', " + + "'synthetic-retained-member', 'BLOCKED', 'PENDING', NULL)", + COVERAGE_OPERATION_ID, + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + GAME_INSTANCE_ID, + SESSION_ID, + REGION_ID, + LEGACY_ISSUER_ID, + ACCOUNT_INDEX_FENCE, + TRANSITION_ID, + TRANSITION_ID); + + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_snapshot_transition (" + + "operation_id, row_ordinal, transition_id, candidate_binding_ref, " + + "expected_prior_binding_ref, expected_prior_binding_generation, " + + "candidate_binding_generation, candidate_account_index_fence, issuer_reservation_id, " + + "status, inventory_revision, candidate_account_id, candidate_tenant_id, " + + "candidate_namespace_id, candidate_character_id, candidate_playable_state_scope, " + + "candidate_game_instance_id, candidate_runtime_game_instance_id, candidate_session_id, " + + "candidate_region_id, candidate_region_epoch, candidate_issuer_id, " + + "candidate_issuer_auth_generation, candidate_issuer_index_layout_version, " + + "candidate_issuer_index_partition_count, candidate_issuer_index_partition_capacity, " + + "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, coverage_fence, coverage_generation, " + + "account_inventory_snapshot_revision) " + + "VALUES (?, 0, ?, ?, NULL, NULL, 5, ?, ?, 'PREPARED', 17, ?, ?, ?, ?, 'SHARED', ?, 23, ?, ?, 2, ?, 7, 3, 4, 8, " + + "'NO_ACTIVE_ACCOUNT_WIDE_FLOW', NULL, NULL, NULL, 'NOT_APPLICABLE', NULL, " + + "'NOT_APPLICABLE', NULL, 'NOT_APPLICABLE', NULL, NULL, NULL, NULL)", + COVERAGE_OPERATION_ID, + TRANSITION_ID, + BINDING_REF, + ACCOUNT_INDEX_FENCE, + RESERVATION_ID, + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + CHARACTER_ID, + GAME_INSTANCE_ID, + SESSION_ID, + REGION_ID, + LEGACY_ISSUER_ID); + + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_snapshot_obligation (" + + "operation_id, row_ordinal, transition_id, obligation_ordinal, binding_ref, account_id, " + + "tenant_id, action, binding_generation, expected_prior_generation, account_index_fence, " + + "execution_phase, status, inventory_revision, projection_state, projection_member, " + + "projection_inventory_revision, binding_lifecycle, transition_status, " + + "expected_readback_state, exact_member, redis_readback_state, redis_readback_member) " + + "VALUES (?, 0, ?, 0, ?, ?, ?, 'ADD_OR_RETAIN', 5, NULL, ?, 'BEFORE_FINAL_CAS', " + + "'REQUIRED', 17, 'REPAIR_REQUIRED', NULL, NULL, 'CANDIDATE_PREPARED', 'PREPARED', " + + "'PRESENT', 'synthetic-retained-member', 'PENDING', NULL)", + COVERAGE_OPERATION_ID, + TRANSITION_ID, + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + ACCOUNT_INDEX_FENCE); + + dsl.execute( + "INSERT INTO game_session_canonical_account_coverage_snapshot_reservation (" + + "operation_id, row_ordinal, reservation_id, binding_ref, account_id, tenant_id, " + + "binding_generation, transition_id, issuer_id, issuer_auth_generation, " + + "playable_state_namespace_id, character_id, playable_state_scope, game_instance_id, " + + "runtime_game_instance_id, session_id, 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 (?, 0, ?, ?, ?, ?, 5, ?, ?, 7, ?, ?, 'SHARED', ?, 23, ?, ?, 2, 2, 3, 4, 8, " + + "'RESERVED', ?, ?, 11, ?, 17, 17)", + COVERAGE_OPERATION_ID, + RESERVATION_ID, + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + TRANSITION_ID, + LEGACY_ISSUER_ID, + NAMESPACE_ID, + CHARACTER_ID, + GAME_INSTANCE_ID, + SESSION_ID, + REGION_ID, + RESERVATION_FENCE, + COVERAGE_OPERATION_ID, + ISSUER_COVERAGE_FENCE); + + dsl.execute( + "INSERT INTO gs_canonical_account_coverage_snapshot_issuer_obligation (" + + "operation_id, row_ordinal, transition_id, binding_ref, binding_generation, " + + "reservation_id, status, inventory_revision) " + + "VALUES (?, 0, ?, ?, 5, ?, 'REQUIRED', 17)", + COVERAGE_OPERATION_ID, + TRANSITION_ID, + BINDING_REF, + RESERVATION_ID); + + dsl.execute( + "INSERT INTO gs_canonical_account_coverage_snapshot_region_obligation (" + + "operation_id, row_ordinal, 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 (?, 0, ?, ?, 5, ?, ?, ?, 23, ?, ?, 2, 'REQUIRED', 17)", + COVERAGE_OPERATION_ID, + TRANSITION_ID, + BINDING_REF, + ACCOUNT_ID, + TENANT_ID, + GAME_INSTANCE_ID, + SESSION_ID, + REGION_ID); + } + + private static void assertIssuerColumnsAreBoundedText(DSLContext dsl) { + for (IssuerField field : ISSUER_FIELDS) { + var column = + dsl.fetchOne( + "SELECT data_type, character_maximum_length FROM information_schema.columns " + + "WHERE table_schema = current_schema() AND table_name = ? AND column_name = ?", + field.table(), + field.column()); + assertThat(column).isNotNull(); + assertThat(column.get("data_type", String.class)).isEqualTo("character varying"); + assertThat(column.get("character_maximum_length", Integer.class)).isEqualTo(64); + } + } + + private static void assertCanonicalIssuerGuardsAreNotValidated(DSLContext dsl) { + for (String constraintName : ACCOUNT_ISSUER_CONSTRAINTS) { + var constraint = + dsl.fetchOne( + "SELECT convalidated, pg_get_constraintdef(oid, true) AS definition " + + "FROM pg_constraint " + + "WHERE connamespace = current_schema()::regnamespace AND conname = ?", + constraintName); + assertThat(constraint).as(constraintName).isNotNull(); + assertThat(constraint.get("convalidated", Boolean.class)).as(constraintName).isFalse(); + assertThat(constraint.get("definition", String.class)) + .as(constraintName) + .contains(CANONICAL_ISSUER); + } + } + + private static void assertRecreatedIdentityChecksRemainValidated(DSLContext dsl) { + for (String constraintName : RECREATED_UUID_DEPENDENT_CONSTRAINTS) { + var constraint = + dsl.fetchOne( + "SELECT convalidated, pg_get_constraintdef(oid, true) AS definition " + + "FROM pg_constraint " + + "WHERE connamespace = current_schema()::regnamespace AND conname = ?", + constraintName); + assertThat(constraint).as(constraintName).isNotNull(); + assertThat(constraint.get("convalidated", Boolean.class)).as(constraintName).isTrue(); + assertThat(constraint.get("definition", String.class)) + .as(constraintName) + .contains("issuer_id::text <> '00000000-0000-0000-0000-000000000000'::text") + .contains("issuer_auth_generation > 0"); + } + } + + private static void assertLegacyIssuerValues(DSLContext dsl) { + for (IssuerField field : ISSUER_FIELDS) { + String issuer = + dsl.fetchSingle( + "SELECT " + + field.column() + + "::text FROM " + + field.table() + + " WHERE " + + field.where(), + field.keys().toArray()) + .get(0, String.class); + assertThat(issuer).as(field.table() + "." + field.column()).isEqualTo(LEGACY_ISSUER); + } + } + + private static void assertExactIssuerValueIsAcceptedForNewRows(DriverManagerDataSource dataSource) + throws Exception { + // These cloned rows prove only that bounded storage accepts the exact selected string. The + // synthetic fixtures are rolled back and are not issuer-source or admission evidence. + try (Connection connection = dataSource.getConnection()) { + connection.setAutoCommit(false); + try { + for (int index = 0; index < ISSUER_FIELDS.size(); index++) { + IssuerField field = ISSUER_FIELDS.get(index); + try (var statement = connection.createStatement()) { + assertThat(statement.executeUpdate(CANONICAL_INSERT_PROBES.get(index))).isEqualTo(1); + } + String read = + "SELECT count(*) FROM " + field.table() + " WHERE " + field.column() + " = ?"; + try (PreparedStatement statement = connection.prepareStatement(read)) { + statement.setString(1, CANONICAL_ISSUER); + try (ResultSet result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getLong(1)).isEqualTo(1L); + } + } + } + } finally { + connection.rollback(); + } + } + } + + private static void assertNonCanonicalIssuerWritesAreRejected(DSLContext dsl) { + for (IssuerField field : ISSUER_FIELDS) { + assertRejectedIssuerWrite(dsl, field, LEGACY_ISSUER); + assertRejectedIssuerWrite(dsl, field, FOREIGN_ISSUER); + assertRejectedIssuerWrite(dsl, field, NON_CANONICAL_ACCOUNT_ISSUER); + } + } + + private static void assertRejectedIssuerWrite( + DSLContext dsl, IssuerField field, String attemptedIssuer) { + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + + field.table() + + " SET " + + field.column() + + " = ? WHERE " + + field.where(), + parameters(attemptedIssuer, field.keys()))) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> assertThat(exception.sqlState()).isEqualTo("23514")); + } + + private static Object[] parameters(String first, List keys) { + Object[] parameters = new Object[keys.size() + 1]; + parameters[0] = first; + for (int index = 0; index < keys.size(); index++) { + parameters[index + 1] = keys.get(index); + } + return parameters; + } + + private static Map> rowSnapshots(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String table : PRESERVED_TABLES) { + List rows = new ArrayList<>(); + for (var row : + dsl.fetch( + "SELECT to_jsonb(retained_row)::text AS row_json FROM " + + table + + " retained_row ORDER BY to_jsonb(retained_row)::text")) { + rows.add(row.get("row_json", String.class)); + } + snapshots.put(table, List.copyOf(rows)); + } + return Map.copyOf(snapshots); + } + + private static List historySnapshot(DSLContext dsl) { + return dsl.fetch( + "SELECT to_jsonb(history_row)::text AS row_json FROM flyway_schema_history history_row " + + "ORDER BY installed_rank") + .getValues("row_json", String.class); + } + + private static Map constraintSnapshot(DSLContext dsl) { + Map constraints = new LinkedHashMap<>(); + for (var row : + dsl.fetch( + "SELECT relation.relname AS relation_name, constraint_row.conname AS constraint_name, " + + "constraint_row.contype::text AS constraint_type, constraint_row.convalidated, " + + "pg_get_constraintdef(constraint_row.oid, true) AS definition " + + "FROM pg_constraint constraint_row " + + "JOIN pg_class relation ON relation.oid = constraint_row.conrelid " + + "WHERE constraint_row.connamespace = current_schema()::regnamespace " + + "AND constraint_row.conname NOT IN (" + + sqlNames(RECREATED_UUID_DEPENDENT_CONSTRAINTS) + + "," + + sqlNames(ACCOUNT_ISSUER_CONSTRAINTS) + + ") ORDER BY relation.relname, constraint_row.conname")) { + String key = + row.get("relation_name", String.class) + "." + row.get("constraint_name", String.class); + String value = + row.get("constraint_type", String.class) + + "|" + + row.get("convalidated", Boolean.class) + + "|" + + row.get("definition", String.class); + constraints.put(key, value); + } + return Map.copyOf(constraints); + } + + private static Map indexSnapshot(DSLContext dsl) { + Map indexes = new LinkedHashMap<>(); + for (var row : + dsl.fetch( + "SELECT tablename, indexname, indexdef FROM pg_indexes " + + "WHERE schemaname = current_schema() ORDER BY tablename, indexname")) { + indexes.put( + row.get("tablename", String.class) + "." + row.get("indexname", String.class), + row.get("indexdef", String.class)); + } + return Map.copyOf(indexes); + } + + private static IssuerField field(String table, String column, String where, Object... keys) { + return new IssuerField(table, column, where, List.copyOf(Arrays.asList(keys))); + } + + private static String sqlNames(List names) { + return names.stream().map(name -> "'" + name + "'").collect(Collectors.joining(", ")); + } + + private static Flyway flyway( + DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (target != null) { + configuration.target(target); + } + return configuration.load(); + } + + 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 (Connection 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 issuer migration schema", failure); + } + } + + private record IssuerField(String table, String column, String where, List keys) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java new file mode 100644 index 0000000000..15c90f3a9a --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -0,0 +1,588 @@ +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.ByteBuffer; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +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; +import tools.jackson.databind.json.JsonMapper; + +/** + * Uses actual SQL intent/target reads with a controlled local signer. + * + *

The controlled key/channel proves only the verifier's local current-observation algorithm. It + * is not operational attestor custody or evidence that a real deployment has this incarnation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String KEY_ID = "controlled-attestor-1"; + private static final String ATTESTOR_BINDING = "controlled-local-attestor-binding"; + private static final String ACCEPTED_ATTESTATION_DIGEST = "sha256:" + "a".repeat(64); + private static final String ACL_DIGEST = "sha256:" + "b".repeat(64); + private static final String CONFIG_DIGEST = "sha256:" + "c".repeat(64); + private static final Instant NOW = Instant.parse("2026-10-26T00:00:00Z"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void verifiesOnlySignedExactCurrentTargetAndRejectsReplayAndMismatches() throws Exception { + try (Fixture fixture = Fixture.open()) { + ControlledSigner channel = new ControlledSigner(fixture.keyPair()); + var receiver = fixture.receiver(channel); + + var verified = receiver.observeForFenceTarget(fixture.intent().operationId(), 0L); + + assertThat(verified.operationId()).isEqualTo(fixture.intent().operationId()); + assertThat(verified.accountId()).isEqualTo(fixture.intent().accountId()); + assertThat(verified.tenantId()).isEqualTo(fixture.targetTenantId()); + assertThat(verified.playableStateNamespaceId()).isEqualTo(fixture.targetNamespaceId()); + assertThat(verified.plannedAccountAdmissionFence()) + .isEqualTo(fixture.intent().plannedAccountAdmissionFence()); + assertThat(verified.operationFence()).isEqualTo(fixture.intent().operationFence().toString()); + assertThat(verified.cohortDigest()).isEqualTo(fixture.intent().cohortDigest()); + assertThat(verified.barrierTargetDigest()).isEqualTo(fixture.intent().barrierTargetDigest()); + assertThat(verified.acceptedAttestationDigest()).isEqualTo(ACCEPTED_ATTESTATION_DIGEST); + assertThat(verified.evidence()).isEqualTo(fixture.expectedEvidence()); + assertThat(verified.expiresAtEpochMillis()).isEqualTo(NOW.toEpochMilli() + 30_000L); + assertThat(verified.payloadDigest()).startsWith("sha256:"); + assertThat(verified.incarnationDigest()).startsWith("sha256:"); + + var repeated = receiver.observeForFenceTarget(fixture.intent().operationId(), 0L); + assertThat(repeated.observationNonce()).isNotEqualTo(verified.observationNonce()); + assertThat(repeated.payloadDigest()).isNotEqualTo(verified.payloadDigest()); + assertThat(repeated.incarnationDigest()).isEqualTo(verified.incarnationDigest()); + + assertThat( + java.lang.reflect.Modifier.isPrivate( + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation.class + .getDeclaredConstructors()[0].getModifiers())) + .isTrue(); + + var restartedReceiver = fixture.receiver(request -> channel.lastSigned()); + assertThatThrownBy( + () -> restartedReceiver.observeForFenceTarget(fixture.intent().operationId(), 0L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + + for (Mutation mutation : + List.of( + Mutation.WRONG_NONCE, + Mutation.WRONG_OPERATION_ID, + Mutation.WRONG_OPERATION_FENCE, + Mutation.WRONG_STORAGE_GENERATION, + Mutation.FOREIGN_ACCOUNT, + Mutation.FOREIGN_TENANT, + Mutation.FOREIGN_NAMESPACE, + Mutation.EXPIRED_REQUEST_WINDOW, + Mutation.FUTURE_OBSERVATION_TIME, + Mutation.UNKNOWN_FIELD, + Mutation.TOO_MANY_NODES, + Mutation.TRAILING_TOKEN, + Mutation.NON_CANONICAL_BYTES, + Mutation.OVERSIZED, + Mutation.WRONG_KEY_ID, + Mutation.BAD_SIGNATURE)) { + ControlledSigner invalid = new ControlledSigner(fixture.keyPair(), mutation, null); + assertThatThrownBy( + () -> + fixture + .receiver(invalid) + .observeForFenceTarget(fixture.intent().operationId(), 0L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + } + + assertThatThrownBy( + () -> + fixture.receiver(null).observeForFenceTarget(fixture.intent().operationId(), 0L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + + var missingPinnedKeys = fixture.configuration(Map.of(), fixture.expectedEvidence()); + assertThatThrownBy( + () -> + fixture + .receiver(channel, missingPinnedKeys) + .observeForFenceTarget(fixture.intent().operationId(), 0L)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + + assertThatThrownBy( + () -> + fixture.configuration( + Map.of( + KEY_ID, + (java.security.interfaces.RSAPublicKey) fixture.keyPair().getPublic()), + null)) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); + } + } + + @Test + void changedTrustedStorageGenerationChangesIncarnationDigestInControlledFixture() + throws Exception { + try (Fixture fixture = Fixture.open()) { + // Both signed observations use this same SQL fixture. The local controlled signer does not + // establish custody of the actual target storage generation. + var trustedKeys = + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) fixture.keyPair().getPublic()); + var original = fixture.expectedEvidence(); + var changedEvidence = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + original.deploymentIdentity(), + original.deploymentGeneration(), + original.canonicalNodeSet(), + original.redisBuildIdentity(), + original.luaScriptRegistryVersion(), + original.luaScriptRegistryDigest(), + original.startupState(), + original.bootGeneration(), + original.startupGeneration(), + "storage-controlled-fixture-8", + original.aofGeneration()); + + var originalVerified = + fixture + .receiver(new ControlledSigner(fixture.keyPair())) + .observeForFenceTarget(fixture.intent().operationId(), 0L); + var changedVerified = + fixture + .receiver( + new ControlledSigner(fixture.keyPair()), + fixture.configuration(trustedKeys, changedEvidence)) + .observeForFenceTarget(fixture.intent().operationId(), 0L); + + assertThat(changedVerified.evidence()).isEqualTo(changedEvidence); + assertThat(changedVerified.operationFence()).isEqualTo(originalVerified.operationFence()); + assertThat(changedVerified.barrierTargetDigest()) + .isEqualTo(originalVerified.barrierTargetDigest()); + assertThat(changedVerified.incarnationDigest()) + .isNotEqualTo(originalVerified.incarnationDigest()); + } + } + + @Test + void changedCurrentSqlContextAfterSourceCallCannotProduceVerifiedEvidence() throws Exception { + try (Fixture fixture = Fixture.open()) { + ControlledSigner channel = + new ControlledSigner(fixture.keyPair(), Mutation.NONE, fixture.dsl()); + assertThatThrownBy( + () -> + fixture + .receiver(channel) + .observeForFenceTarget(fixture.intent().operationId(), 0L)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat(channel.lastSigned()).isNotNull(); + } + } + + private enum Mutation { + NONE, + WRONG_NONCE, + WRONG_OPERATION_ID, + WRONG_OPERATION_FENCE, + WRONG_STORAGE_GENERATION, + FOREIGN_ACCOUNT, + FOREIGN_TENANT, + FOREIGN_NAMESPACE, + EXPIRED_REQUEST_WINDOW, + FUTURE_OBSERVATION_TIME, + UNKNOWN_FIELD, + TOO_MANY_NODES, + TRAILING_TOKEN, + NON_CANONICAL_BYTES, + OVERSIZED, + WRONG_KEY_ID, + BAD_SIGNATURE + } + + private static final class ControlledSigner + implements CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel { + private final KeyPair keyPair; + private final Mutation mutation; + private final DSLContext contextMutationDsl; + private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation lastSigned; + + private ControlledSigner(KeyPair keyPair) { + this(keyPair, Mutation.NONE, null); + } + + private ControlledSigner(KeyPair keyPair, Mutation mutation, DSLContext contextMutationDsl) { + this.keyPair = keyPair; + this.mutation = mutation; + this.contextMutationDsl = contextMutationDsl; + } + + @Override + public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + if (contextMutationDsl != null) { + contextMutationDsl.execute( + "UPDATE game_session_canonical_account_admission_fence_intent" + + " SET cohort_digest = ? WHERE operation_id = ?", + "sha256:" + "f".repeat(64), + request.context().operationId()); + } + Map root = payload(request); + switch (mutation) { + case WRONG_NONCE -> root.put("observationNonce", "A".repeat(43)); + case WRONG_OPERATION_ID -> + asMap(root.get("owner")).put("operationId", UUID.randomUUID().toString()); + case WRONG_OPERATION_FENCE -> asMap(root.get("owner")).put("operationFence", "999999"); + case WRONG_STORAGE_GENERATION -> + asMap(root.get("targetDeploymentEvidence")) + .put("storageGeneration", "storage-untrusted-response"); + case FOREIGN_ACCOUNT -> + asMap(root.get("owner")).put("accountId", UUID.randomUUID().toString()); + case FOREIGN_TENANT -> + asMap(root.get("target")).put("tenantId", UUID.randomUUID().toString()); + case FOREIGN_NAMESPACE -> + asMap(root.get("target")).put("playableStateNamespaceId", UUID.randomUUID().toString()); + case EXPIRED_REQUEST_WINDOW -> + root.put("observationExpiresAtEpochMillis", request.issuedAtEpochMillis()); + case FUTURE_OBSERVATION_TIME -> + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis() + 1_000L); + case UNKNOWN_FIELD -> root.put("unexpected", "field"); + case TOO_MANY_NODES -> + asMap(root.get("targetDeploymentEvidence")) + .put("canonicalNodeSet", List.of("node-a", "node-b", "node-c")); + default -> { + // The other mutations are applied to the bytes or detached signature below. + } + } + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + byte[] payload; + if (mutation == Mutation.NON_CANONICAL_BYTES) { + payload = + ByteBuffer.allocate(canonical.length + 1).put(canonical).put((byte) ' ').array(); + } else if (mutation == Mutation.TRAILING_TOKEN) { + byte[] suffix = " {}".getBytes(java.nio.charset.StandardCharsets.UTF_8); + payload = + ByteBuffer.allocate(canonical.length + suffix.length) + .put(canonical) + .put(suffix) + .array(); + } else if (mutation == Mutation.OVERSIZED) { + asMap(root.get("owner")).put("padding", "x".repeat(17_000)); + byte[] oversized = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + payload = oversized; + } else { + payload = canonical; + } + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keyPair.getPrivate()); + signer.update(canonical); + byte[] signature = signer.sign(); + if (mutation == Mutation.BAD_SIGNATURE) { + signature[signature.length - 1] ^= 1; + } + String responseKeyId = + mutation == Mutation.WRONG_KEY_ID ? "unconfigured-attestor-key" : KEY_ID; + lastSigned = + new CanonicalGameplayProtectedIncarnationReceiver.SignedObservation( + responseKeyId, payload, signature); + return lastSigned; + } catch (Exception failure) { + throw new IllegalStateException("Controlled test signer failed", failure); + } + } + + private CanonicalGameplayProtectedIncarnationReceiver.SignedObservation lastSigned() { + return lastSigned; + } + } + + private static Map payload( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { + var context = request.context(); + var evidence = request.expectedEvidence(); + Map owner = new LinkedHashMap<>(); + owner.put("operationId", context.operationId().toString()); + owner.put("requestId", context.requestId().toString()); + owner.put("accountId", context.accountId().toString()); + owner.put("operationFence", context.operationFence()); + owner.put("plannedAccountAdmissionFence", context.plannedAccountAdmissionFence().toString()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("cohortDigest", context.cohortDigest()); + owner.put("barrierTargetDigest", context.barrierTargetDigest()); + + Map target = new LinkedHashMap<>(); + target.put("targetOrdinal", context.targetOrdinal()); + target.put("tenantId", context.tenantId().toString()); + target.put("playableStateNamespaceId", context.playableStateNamespaceId().toString()); + target.put("tenantGameplayTag", context.tenantGameplayTag()); + target.put("workloadNamespace", context.workloadNamespace()); + target.put("allocationVersion", context.allocationVersion()); + + Map targetEvidence = new LinkedHashMap<>(); + targetEvidence.put("deploymentIdentity", evidence.deploymentIdentity()); + targetEvidence.put("deploymentGeneration", evidence.deploymentGeneration()); + targetEvidence.put("canonicalNodeSet", evidence.canonicalNodeSet()); + targetEvidence.put("redisBuildIdentity", evidence.redisBuildIdentity()); + targetEvidence.put("luaScriptRegistryVersion", evidence.luaScriptRegistryVersion()); + targetEvidence.put("luaScriptRegistryDigest", evidence.luaScriptRegistryDigest()); + targetEvidence.put("startupState", evidence.startupState()); + targetEvidence.put("bootGeneration", evidence.bootGeneration()); + targetEvidence.put("startupGeneration", evidence.startupGeneration()); + targetEvidence.put("storageGeneration", evidence.storageGeneration()); + targetEvidence.put("aofGeneration", evidence.aofGeneration()); + + Map root = new LinkedHashMap<>(); + root.put("schema", "firemud.gs.protected-incarnation-read/v1"); + root.put("attestorBinding", request.attestorBinding()); + root.put("attestorKeyId", KEY_ID); + root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); + root.put("observationNonce", request.nonce()); + root.put("observationIssuedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationObservedAtEpochMillis", request.issuedAtEpochMillis()); + root.put("observationExpiresAtEpochMillis", request.expiresAtEpochMillis()); + root.put("owner", owner); + root.put("target", target); + root.put("targetDeploymentEvidence", targetEvidence); + root.put("coordOpsRoAclDigest", request.coordOpsRoAclDigest()); + root.put("coordRedisConfigObservedDigest", request.coordRedisConfigObservedDigest()); + return root; + } + + @SuppressWarnings("unchecked") + private static Map asMap(Object value) { + return (Map) value; + } + + private static final class Fixture implements AutoCloseable { + private final String schema; + private final DSLContext dsl; + private final CanonicalGameplayAccountAdmissionFenceIntent intent; + private final UUID targetTenantId; + private final UUID targetNamespaceId; + private final String targetWorkloadNamespace; + private final KeyPair keyPair; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence; + + private Fixture( + String schema, + DSLContext dsl, + CanonicalGameplayAccountAdmissionFenceIntent intent, + UUID targetTenantId, + UUID targetNamespaceId, + String targetWorkloadNamespace, + KeyPair keyPair, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence) { + this.schema = schema; + this.dsl = dsl; + this.intent = intent; + this.targetTenantId = targetTenantId; + this.targetNamespaceId = targetNamespaceId; + this.targetWorkloadNamespace = targetWorkloadNamespace; + this.keyPair = keyPair; + this.expectedEvidence = expectedEvidence; + } + + private static Fixture open() throws Exception { + String schema = "gs_incarnation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + UUID tenantId = UUID.randomUUID(); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest + .seedSyntheticVerifiedLegacyDisposition(dsl); + + UUID accountId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + String sessionId = UUID.randomUUID().toString(); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + characterId, + "SHARED", + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + sessionId, + UUID.randomUUID(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + CanonicalIssuerReservationFenceEvidence reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); + inventory.prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, reservation, null, null)); + CanonicalGameplayAccountAdmissionFenceIntent intent = + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(accountId, UUID.randomUUID()); + + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + var expectedEvidence = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-target-deployment", + "generation-7", + List.of("redis-node-a"), + "redis-test-build", + "registry-test-v1", + "sha256:" + "d".repeat(64), + "READY", + "boot-7", + "startup-7", + "storage-7", + "aof-7"); + return new Fixture( + schema, + dsl, + intent, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + runtime.targetNamespace(), + keyPair, + expectedEvidence); + } + + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel) { + return receiver( + channel, + configuration( + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), + expectedEvidence)); + } + + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel, + CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration configuration) { + return new CanonicalGameplayProtectedIncarnationReceiver( + new CanonicalGameplayAccountAdmissionBarrierRepository(dsl), + new CanonicalGameplayTenantGameplayTagRepository(dsl, targetWorkloadNamespace, 1), + channel, + configuration, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration configuration( + Map keys, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence evidence) { + return new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + ATTESTOR_BINDING, + ACCEPTED_ATTESTATION_DIGEST, + keys, + evidence, + ACL_DIGEST, + CONFIG_DIGEST, + 16 * 1024, + 1, + Duration.ofSeconds(30)); + } + + private CanonicalGameplayAccountAdmissionFenceIntent intent() { + return intent; + } + + private UUID targetTenantId() { + return targetTenantId; + } + + private UUID targetNamespaceId() { + return targetNamespaceId; + } + + private KeyPair keyPair() { + return keyPair; + } + + private DSLContext dsl() { + return dsl; + } + + private CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence() { + return expectedEvidence; + } + + @Override + public void close() { + dropSchema(schema); + } + + 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( + "Could not dispose protected incarnation test schema", failure); + } + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index 2d0ea4fe65..08e7c5296e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -100,12 +100,18 @@ void upgradeActualCanonicalHistory() { .containsExactlyElementsOf(beforeScheduling); assertThat(history().getLast()) .contains("1021", "V1021__canonical_roster_recovery_attempt_scheduling.sql"); + var beforeBinarySafeGuard = history(); + migrate("1022"); + assertThat(history().subList(0, beforeBinarySafeGuard.size())) + .containsExactlyElementsOf(beforeBinarySafeGuard); + assertThat(history()).hasSize(beforeBinarySafeGuard.size() + 1); + assertThat(history().getLast()) + .contains("1022", "V1022__canonical_roster_binary_safe_recovery_guard.sql"); var beforeLatest = history(); - migrate("latest"); + var latest = migrate(dataSource, schema, "latest"); + latest.validate(); + assertThat(latest.info().pending()).isEmpty(); assertThat(history().subList(0, beforeLatest.size())).containsExactlyElementsOf(beforeLatest); - assertThat(history()).hasSize(beforeLatest.size() + 1); - assertThat(history().get(history().size() - 1)) - .contains("1022", "V1022__canonical_roster_binary_safe_recovery_guard.sql"); transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); repository = new CanonicalGameplayRosterReferenceRepository( @@ -267,15 +273,25 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() "SELECT row_to_json(s)::text || ':' || s.xmin::text FROM game_session_canonical_roster_selection s ORDER BY operation_uuid"; var rowsBeforeBinaryGuard = upgradeDsl.fetch(retainedRowsSql).getValues(0, String.class); var historyBeforeBinaryGuard = history(upgradeDsl); - migrate(upgradeDataSource, upgradeSchema, "latest"); - assertThat(history(upgradeDsl).subList(0, historyBeforeBinaryGuard.size())) + migrate(upgradeDataSource, upgradeSchema, "1022"); + var historyAtBinaryGuard = history(upgradeDsl); + assertThat(historyAtBinaryGuard.subList(0, historyBeforeBinaryGuard.size())) .containsExactlyElementsOf(historyBeforeBinaryGuard); + assertThat(historyAtBinaryGuard).hasSize(historyBeforeBinaryGuard.size() + 1); + assertThat(historyAtBinaryGuard.getLast()) + .contains("1022", "V1022__canonical_roster_binary_safe_recovery_guard.sql"); + assertThat(upgradeDsl.fetch(retainedRowsSql).getValues(0, String.class)) + .containsExactlyElementsOf(rowsBeforeBinaryGuard); + var latest = migrate(upgradeDataSource, upgradeSchema, "latest"); + latest.validate(); + assertThat(latest.info().pending()).isEmpty(); + var historyAtLatest = history(upgradeDsl); + assertThat(historyAtLatest.subList(0, historyAtBinaryGuard.size())) + .containsExactlyElementsOf(historyAtBinaryGuard); assertThat(upgradeDsl.fetch(retainedRowsSql).getValues(0, String.class)) .containsExactlyElementsOf(rowsBeforeBinaryGuard); - assertThat(history(upgradeDsl).subList(0, historyBeforeScheduling.size())) + assertThat(historyAtLatest.subList(0, historyBeforeScheduling.size())) .containsExactlyElementsOf(historyBeforeScheduling); - assertThat(history(upgradeDsl).get(history(upgradeDsl).size() - 1)) - .contains("1022", "V1022__canonical_roster_binary_safe_recovery_guard.sql"); assertThat(upgradeRow(upgradeDsl, ordinaryTerminal)).isEqualTo(retainedOrdinaryTerminal); assertThat(upgradeRow(upgradeDsl, recoveredTerminal)).isEqualTo(retainedRecoveredTerminal); assertThat(upgradeRow(upgradeDsl, pendingRecovery)).isEqualTo(retainedPendingRecovery); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..fed8dcb237 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java @@ -0,0 +1,492 @@ +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.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.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +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.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +class CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final String DIGEST = "sha256:" + "0".repeat(64); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @org.junit.jupiter.api.Test + void serializesFirstAllocationPreservesRestartMappingAndRejectsGlobalCrossVersionCollision() + throws Exception { + String schema = "gs_tenant_tag_" + 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); + + UUID tenantA = UUID.randomUUID(); + UUID tenantB = UUID.randomUUID(); + var targetA = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantA); + var targetB = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantB); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest + .seedSyntheticVerifiedLegacyDisposition(dsl); + PreparedCandidate candidateA = prepareCandidate(dsl, targetA); + PreparedCandidate candidateB = prepareCandidate(dsl, targetB); + + CanonicalGameplayTenantGameplayTagRepository versionOne = + new CanonicalGameplayTenantGameplayTagRepository(dsl, targetA.targetNamespace(), 1); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + CanonicalGameplayTenantGameplayTagRepository.Assignment first; + CanonicalGameplayTenantGameplayTagRepository.Assignment second; + try { + Future firstFuture = + executor.submit( + () -> { + ready.countDown(); + await(start); + return versionOne.assignmentForTransition(candidateA.transitionId()); + }); + Future secondFuture = + executor.submit( + () -> { + ready.countDown(); + await(start); + return versionOne.assignmentForTransition(candidateA.transitionId()); + }); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + first = firstFuture.get(30, TimeUnit.SECONDS); + second = secondFuture.get(30, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + + assertThat(first.tenantGameplayTag()).isEqualTo(second.tenantGameplayTag()); + assertThat(first.allocationVersion()).isEqualTo(1); + assertThat(first.bindingRef()).isEqualTo(candidateA.bindingRef()); + assertThat(first.tenantId()).isEqualTo(tenantA); + + // A changed configured allocation version only applies to future mappings. + var restartedVersionTwo = + new CanonicalGameplayTenantGameplayTagRepository(dsl, targetA.targetNamespace(), 2) + .assignmentForTransition(candidateA.transitionId()); + assertThat(restartedVersionTwo.tenantGameplayTag()).isEqualTo(first.tenantGameplayTag()); + assertThat(restartedVersionTwo.allocationVersion()).isEqualTo(1); + + String expectedSessionKey = + "session:game:{" + + first.tenantGameplayTag() + + "}:" + + targetA.gameInstanceUuid() + + ":" + + candidateA.sessionId(); + assertThat(CanonicalGameplaySessionRedisKeys.session(first, candidateA.bindingRef())) + .isEqualTo(expectedSessionKey); + assertThat(CanonicalGameplaySessionRedisKeys.characterIndex(first, candidateA.bindingRef())) + .isEqualTo( + "session:game:index:character:{" + + first.tenantGameplayTag() + + "}:" + + targetA.playableStateNamespaceId() + + ":" + + candidateA.characterId()); + assertThat( + CanonicalGameplaySessionRedisKeys.accountTenantIndex(first, candidateA.bindingRef())) + .isEqualTo( + "session:game:index:account-tenant:{" + + first.tenantGameplayTag() + + "}:" + + candidateA.accountId()); + assertThat(CanonicalGameplaySessionRedisKeys.tenantIndex(first, candidateA.bindingRef())) + .isEqualTo("session:game:index:tenant:{" + first.tenantGameplayTag() + "}"); + + CanonicalGameplayBindingRef foreignBindingRef = + CanonicalGameplayBindingRef.of( + tenantB, targetB.gameInstanceUuid(), candidateB.sessionId()); + assertThatThrownBy(() -> CanonicalGameplaySessionRedisKeys.session(first, foreignBindingRef)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("persisted tenant assignment"); + assertThatThrownBy( + () -> + new CanonicalGameplayTenantGameplayTagRepository( + dsl, targetB.targetNamespace(), 2) + .assignmentForTransition(candidateA.transitionId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("configured Game Session workload"); + + // Simulate a future-version candidate colliding with the immutable version-one owner. + assertThatThrownBy( + () -> + new CanonicalGameplayTenantGameplayTagRepository( + dsl, targetB.targetNamespace(), 2) + .assignmentForTransitionWithCandidate( + candidateB.transitionId(), 2, first.tenantGameplayTag())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("already owned by a different tenant"); + assertThat( + dsl.fetchOne( + "SELECT tenant_id FROM game_session_canonical_tenant_gameplay_tag " + + "WHERE tenant_id = ?", + tenantB)) + .isNull(); + var assignmentB = + new CanonicalGameplayTenantGameplayTagRepository(dsl, targetB.targetNamespace(), 2) + .assignmentForTransition(candidateB.transitionId()); + assertThat(assignmentB.tenantGameplayTag()).isNotEqualTo(first.tenantGameplayTag()); + assertThat(assignmentB.allocationVersion()).isEqualTo(2); + assertThat( + dsl.fetchSingle( + "SELECT count(*) AS row_count FROM " + + "game_session_canonical_tenant_gameplay_tag") + .get("row_count", Long.class)) + .isEqualTo(2L); + assertThat( + dsl.fetchSingle( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + "game_session_canonical_tenant_gameplay_tag WHERE tenant_id = ?", + tenantA) + .get("tenant_gameplay_tag", String.class)) + .isEqualTo(first.tenantGameplayTag()); + + // The V1027 row identifies a required target only. Its returned key is not an installation + // receipt or admission decision. + UUID intentOperationId = UUID.randomUUID(); + seedCurrentBarrierTarget( + dsl, + candidateA.accountId(), + tenantA, + targetA.playableStateNamespaceId(), + intentOperationId); + var barrierTarget = versionOne.assignmentForBarrierTarget(intentOperationId, 0L); + assertThat(CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(barrierTarget)) + .isEqualTo( + "session:game:account-admission:{" + + first.tenantGameplayTag() + + "}:" + + candidateA.accountId() + + ":" + + targetA.playableStateNamespaceId()); + assertThat(barrierTarget.admissionFenceIntentOperationId()).isEqualTo(intentOperationId); + } finally { + dropSchema(schema); + } + } + + @org.junit.jupiter.api.Test + void barrierTargetAssignmentLocksControlBeforeIntentAndTarget() throws Exception { + String schema = "gs_tenant_tag_lock_order_" + 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); + + UUID tenantId = UUID.randomUUID(); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest + .seedSyntheticVerifiedLegacyDisposition(dsl); + PreparedCandidate candidate = prepareCandidate(dsl, runtime); + var expected = + new CanonicalGameplayTenantGameplayTagRepository(dsl, runtime.targetNamespace(), 1) + .assignmentForTransition(candidate.transitionId()); + + UUID operationId = UUID.randomUUID(); + seedCurrentBarrierTarget( + dsl, candidate.accountId(), tenantId, runtime.playableStateNamespaceId(), operationId); + + String holderApplicationName = + "gs_tenant_tag_holder_" + UUID.randomUUID().toString().replace("-", ""); + String assignmentApplicationName = + "gs_tenant_tag_assignment_" + UUID.randomUUID().toString().replace("-", ""); + DSLContext holderDsl = dslForSchema(dataSource(schema, holderApplicationName), schema); + DSLContext assignmentDsl = + dslForSchema(dataSource(schema, assignmentApplicationName), schema); + + CountDownLatch controlRowLocked = new CountDownLatch(1); + CountDownLatch allowIntentAndTargetLocks = new CountDownLatch(1); + CountDownLatch intentAndTargetLocked = new CountDownLatch(1); + CountDownLatch releaseControl = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future controlOwner = + executor.submit( + () -> + holderDsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + if (transaction.fetchOne( + "SELECT account_id FROM" + + " game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + candidate.accountId()) + == null) { + throw new IllegalStateException( + "Current account control row is missing"); + } + controlRowLocked.countDown(); + await(allowIntentAndTargetLocks); + if (transaction.fetchOne( + "SELECT operation_id FROM" + + " game_session_canonical_account_admission_fence_intent" + + " WHERE operation_id = ? AND intent_state =" + + " 'ACQUISITION_INTENT' FOR UPDATE NOWAIT", + operationId) + == null) { + throw new IllegalStateException( + "Current acquisition intent is missing"); + } + if (transaction.fetchOne( + "SELECT operation_id FROM" + + " game_session_canonical_account_admission_fence_intent_barrier_target" + + " WHERE operation_id = ? AND target_ordinal = 0" + + " AND target_state = 'REQUIRED' FOR UPDATE NOWAIT", + operationId) + == null) { + throw new IllegalStateException("Current barrier target is missing"); + } + intentAndTargetLocked.countDown(); + await(releaseControl); + return Boolean.TRUE; + })); + try { + assertThat(controlRowLocked.await(10, TimeUnit.SECONDS)).isTrue(); + Future assignment = + executor.submit( + () -> + new CanonicalGameplayTenantGameplayTagRepository( + assignmentDsl, runtime.targetNamespace(), 1) + .assignmentForBarrierTarget(operationId, 0L)); + awaitControlLockWait(dsl, assignmentApplicationName); + + // The reader is queued only on control: the control owner can still lock both later rows + // without waiting or receiving a lock-not-available error. + allowIntentAndTargetLocks.countDown(); + assertThat(intentAndTargetLocked.await(10, TimeUnit.SECONDS)).isTrue(); + releaseControl.countDown(); + controlOwner.get(10, TimeUnit.SECONDS); + + var actual = assignment.get(10, TimeUnit.SECONDS); + assertThat(actual.accountId()).isEqualTo(candidate.accountId()); + assertThat(actual.tenantId()).isEqualTo(tenantId); + assertThat(actual.playableStateNamespaceId()) + .isEqualTo(runtime.playableStateNamespaceId()); + assertThat(actual.tenantGameplayTag()).isEqualTo(expected.tenantGameplayTag()); + assertThat(actual.allocationVersion()).isEqualTo(expected.allocationVersion()); + assertThat(actual.workloadNamespace()).isEqualTo(expected.workloadNamespace()); + assertThat(actual.admissionFenceIntentOperationId()).isEqualTo(operationId); + assertThat(actual.barrierTargetOrdinal()).isEqualTo(0L); + } finally { + allowIntentAndTargetLocks.countDown(); + releaseControl.countDown(); + controlOwner.get(10, TimeUnit.SECONDS); + } + } finally { + executor.shutdownNow(); + } + } finally { + dropSchema(schema); + } + } + + private static PreparedCandidate prepareCandidate( + DSLContext dsl, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target) { + UUID transitionId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + String sessionId = UUID.randomUUID().toString(); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + target.canonicalTenantId(), + target.playableStateNamespaceId(), + characterId, + "SHARED", + target.gameInstanceUuid(), + target.gameInstanceId(), + sessionId, + UUID.randomUUID(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + CanonicalIssuerReservationFenceEvidence reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + CanonicalGameplayBindingTransitionRequest request = + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, reservation, null, null); + new CanonicalGameplayBindingInventoryRepository(dsl).prepare(request); + return new PreparedCandidate( + transitionId, accountId, characterId, sessionId, identity.bindingRef()); + } + + private static void seedCurrentBarrierTarget( + DSLContext dsl, UUID accountId, UUID tenantId, UUID namespaceId, UUID operationId) { + var clock = + dsl.fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock " + + "WHERE singleton_id = 1"); + BigInteger snapshotRevision = + clock.get("inventory_revision", java.math.BigDecimal.class).toBigIntegerExact(); + UUID requestId = UUID.randomUUID(); + UUID plannedFence = UUID.randomUUID(); + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent (" + + "operation_id, request_id, account_id, operation_fence, planned_account_admission_fence, " + + "inventory_snapshot_revision, legacy_cohort_id, legacy_owner_operation_id, " + + "legacy_writer_fence, legacy_source_snapshot_revision, " + + "legacy_canonical_inventory_revision, legacy_namespace_index_readback_revision, " + + "legacy_evidence_digest, intent_state, cohort_row_count, cohort_digest, " + + "barrier_target_count, barrier_target_digest) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, 1, 1, 1, ?, 'ACQUISITION_INTENT', 0, ?, 1, ?)", + operationId, + requestId, + accountId, + plannedFence, + snapshotRevision, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + DIGEST, + DIGEST, + DIGEST); + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent_barrier_target " + + "(operation_id, account_id, target_ordinal, tenant_id, " + + "playable_state_namespace_id, target_state) VALUES (?, ?, 0, ?, ?, 'REQUIRED')", + operationId, + accountId, + tenantId, + namespaceId); + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control SET state = 'ACQUISITION_INTENT', " + + "last_operation_fence = 1, current_operation_id = NULL, current_fence_intent_id = ?, " + + "current_operation_fence = 1, account_admission_fence = ?, " + + "historical_account_admission_fence = NULL, coverage_fence = NULL, " + + "inventory_snapshot_revision = ?, coverage_generation = NULL " + + "WHERE account_id = ? AND state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'", + operationId, + plannedFence, + snapshotRevision, + accountId); + } + + private static void await(CountDownLatch latch) throws InterruptedException { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent tag allocation fixture did not start"); + } + } + + private static void awaitControlLockWait(DSLContext observer, String applicationName) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Boolean waiting = + Objects.requireNonNull( + observer.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity" + + " WHERE pid <> pg_backend_pid() AND application_name = ?" + + " AND state = 'active' AND wait_event_type = 'Lock'" + + " AND query ILIKE '%game_session_canonical_account_coverage_control%')", + applicationName), + "account control lock wait query") + .get(0, Boolean.class); + if (Boolean.TRUE.equals(waiting)) { + return; + } + Thread.sleep(10); + } + throw new AssertionError("Barrier target assignment did not wait on the account control row"); + } + + 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"); + 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); + assertThat( + dsl.fetchSingle("SELECT current_schema() AS actual_schema") + .get("actual_schema", String.class)) + .isEqualTo(schema); + 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 tenant tag test schema", failure); + } + } + + private record PreparedCandidate( + UUID transitionId, + UUID accountId, + UUID characterId, + String sessionId, + CanonicalGameplayBindingRef bindingRef) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperationTest.java new file mode 100644 index 0000000000..bc7311e218 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperationTest.java @@ -0,0 +1,186 @@ +package net.firedevops.firemud.gamesession.binding; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigInteger; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayAccountMemberRepairOperationTest { + private static final UUID TRANSITION_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID OPERATION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COVERAGE_FENCE = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID ACCOUNT_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TENANT_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID ACCOUNT_INDEX_FENCE = + UUID.fromString("66666666-6666-4666-8666-666666666666"); + + @Test + void retainsExactTenantQualifiedMemberAndBindingLocalAckScope() { + CanonicalGameplayAccountMemberRepairOperation operation = operation(TENANT_ID); + + assertThat(operation.bindingRef().tenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(operation.member()) + .isEqualTo( + new CanonicalGameplayAccountIndexMember( + operation.bindingRef(), operation.bindingGeneration(), ACCOUNT_INDEX_FENCE) + .value()); + + var acknowledgement = + new CanonicalGameplayAccountMemberAcknowledgement( + operation, BigInteger.valueOf(12), operation.member()); + assertThat(acknowledgement.schemaVersion()).isEqualTo(2); + assertThat(acknowledgement.accountCoverageState()) + .isEqualTo( + CanonicalGameplayAccountMemberAcknowledgement.AccountCoverageState + .NO_ACTIVE_ACCOUNT_WIDE_FLOW); + assertThat(acknowledgement.accountCoverageOperationId()) + .isEqualTo(CanonicalGameplayAccountMemberAcknowledgement.NotApplicable.NOT_APPLICABLE); + assertThat(acknowledgement.accountCoverageLifecycle()) + .isEqualTo(CanonicalGameplayAccountMemberAcknowledgement.NotApplicable.NOT_APPLICABLE); + assertThat(acknowledgement.accountCoverageOperationFence()) + .isEqualTo(CanonicalGameplayAccountMemberAcknowledgement.NotApplicable.NOT_APPLICABLE); + assertThat(acknowledgement.accountAdmissionFence()) + .isEqualTo(CanonicalGameplayAccountMemberAcknowledgement.NotApplicable.NOT_APPLICABLE); + assertThat(acknowledgement.historicalAccountAdmissionFence()) + .isEqualTo(CanonicalGameplayAccountMemberAcknowledgement.NotApplicable.NOT_APPLICABLE); + assertThat(acknowledgement.resolvedScope()) + .isEqualTo(CanonicalGameplayAccountMemberAcknowledgement.NotApplicable.NOT_APPLICABLE); + assertThat(acknowledgement.coverageGeneration()).isGreaterThan(BigInteger.valueOf(11)); + assertThat(acknowledgement.readback().state()) + .isEqualTo(CanonicalGameplayAccountMemberAcknowledgement.ReadbackState.PRESENT); + } + + @Test + void rejectsCrossTenantBindingReferenceAndMemberThatDoesNotMatchFrozenTuple() { + CanonicalGameplayBindingRef reference = reference(TENANT_ID); + var obligation = obligation(reference, TENANT_ID); + String exactMember = + new CanonicalGameplayAccountIndexMember(reference, BigInteger.TEN, ACCOUNT_INDEX_FENCE) + .value(); + + assertThatThrownBy( + () -> + new CanonicalGameplayAccountMemberRepairOperation( + TRANSITION_ID, + OPERATION_ID, + BigInteger.ONE, + COVERAGE_FENCE, + BigInteger.valueOf(11), + reference, + ACCOUNT_ID, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + BigInteger.TEN, + ACCOUNT_INDEX_FENCE, + obligation, + exactMember, + BigInteger.ZERO)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bindingRef tenant segment"); + + assertThatThrownBy( + () -> + new CanonicalGameplayAccountMemberRepairOperation( + TRANSITION_ID, + OPERATION_ID, + BigInteger.ONE, + COVERAGE_FENCE, + BigInteger.valueOf(11), + reference, + ACCOUNT_ID, + TENANT_ID, + BigInteger.TEN, + ACCOUNT_INDEX_FENCE, + obligation, + exactMember + "-foreign", + BigInteger.ZERO)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("member differs"); + } + + @Test + void requiresLaterEvidenceGenerationAndOriginalNewObligation() { + CanonicalGameplayAccountMemberRepairOperation operation = operation(TENANT_ID); + assertThatThrownBy( + () -> + new CanonicalGameplayAccountMemberAcknowledgement( + operation, operation.inventorySnapshotRevision(), operation.member())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("newer than"); + + CanonicalGameplayBindingRef reference = reference(TENANT_ID); + assertThatThrownBy( + () -> + new CanonicalGameplayAccountMemberRepairOperation( + TRANSITION_ID, + OPERATION_ID, + BigInteger.ONE, + COVERAGE_FENCE, + BigInteger.valueOf(11), + reference, + ACCOUNT_ID, + TENANT_ID, + BigInteger.TEN, + ACCOUNT_INDEX_FENCE, + obligation(reference, TENANT_ID, BigInteger.ONE), + new CanonicalGameplayAccountIndexMember( + reference, BigInteger.TEN, ACCOUNT_INDEX_FENCE) + .value(), + BigInteger.ZERO)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact outstanding NEW"); + } + + private static CanonicalGameplayAccountMemberRepairOperation operation(UUID tenantId) { + CanonicalGameplayBindingRef reference = reference(tenantId); + return new CanonicalGameplayAccountMemberRepairOperation( + TRANSITION_ID, + OPERATION_ID, + BigInteger.ONE, + COVERAGE_FENCE, + BigInteger.valueOf(11), + reference, + ACCOUNT_ID, + tenantId, + BigInteger.TEN, + ACCOUNT_INDEX_FENCE, + obligation(reference, tenantId), + new CanonicalGameplayAccountIndexMember(reference, BigInteger.TEN, ACCOUNT_INDEX_FENCE) + .value(), + BigInteger.ZERO); + } + + private static CanonicalGameplayBindingRef reference(UUID tenantId) { + return CanonicalGameplayBindingRef.of( + tenantId, + UUID.fromString("88888888-8888-4888-8888-888888888888"), + "99999999-9999-4999-8999-999999999999"); + } + + private static CanonicalGameplayBindingAccountIndexObligation obligation( + CanonicalGameplayBindingRef reference, UUID tenantId) { + return obligation(reference, tenantId, null); + } + + private static CanonicalGameplayBindingAccountIndexObligation obligation( + CanonicalGameplayBindingRef reference, UUID tenantId, BigInteger expectedPriorGeneration) { + return new CanonicalGameplayBindingAccountIndexObligation( + TRANSITION_ID, + 0, + reference, + ACCOUNT_ID, + tenantId, + CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN, + BigInteger.TEN, + expectedPriorGeneration, + ACCOUNT_INDEX_FENCE, + CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS, + CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED, + BigInteger.TEN, + CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED, + null, + null); + } +} 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 index ccfd820329..669a1d3b41 100644 --- 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 @@ -5,6 +5,7 @@ import java.math.BigInteger; import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import org.junit.jupiter.api.Test; @@ -16,7 +17,8 @@ class CanonicalGameplayBindingIdentityTest { 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"); + private static final String ISSUER_ID = GameSessionAccountDelegationProfile.ISSUER; + private static final String ISSUER_ID_UUID = "77777777-7777-4777-8777-777777777777"; @Test void acceptsCanonicalNonNilSessionUuid() { @@ -31,7 +33,19 @@ void rejectsNilSessionUuidConsistentWithV29StorageConstraint() { .hasMessageContaining("sessionId must use canonical UUID text"); } + @Test + void rejectsLegacyUuidIssuerWithoutMappingEvenWhenGenerationIsUnchanged() { + assertThatThrownBy(() -> identity("88888888-8888-4888-8888-888888888888", ISSUER_ID_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported issuer identity") + .hasMessageContaining("legacy UUID issuer identities require explicit recovery"); + } + private static CanonicalGameplayBindingIdentity identity(String sessionId) { + return identity(sessionId, ISSUER_ID); + } + + private static CanonicalGameplayBindingIdentity identity(String sessionId, String issuerId) { return new CanonicalGameplayBindingIdentity( ACCOUNT_ID, TENANT_ID, @@ -43,7 +57,7 @@ private static CanonicalGameplayBindingIdentity identity(String sessionId) { sessionId, REGION_ID, BigInteger.ONE, - ISSUER_ID, + issuerId, BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingProvisionalCasEvidenceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingProvisionalCasEvidenceTest.java new file mode 100644 index 0000000000..1af29771bf --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayBindingProvisionalCasEvidenceTest.java @@ -0,0 +1,123 @@ +package 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.common.security.GameSessionAccountDelegationProfile; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayBindingProvisionalCasEvidenceTest { + @Test + void permitsUnrepairedTransferButRefusesNewOnlyAcknowledgedRepairForTransfer() { + assertThatCode( + () -> transfer(CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED)) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> transfer(CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("candidate is not an exact non-admissible transition row"); + } + + private static CanonicalGameplayBindingProvisionalCasEvidence transfer( + CanonicalGameplayBindingInventoryEntry.IndexState candidateAccountState) { + var prior = + entry( + identity(10), + BigInteger.ONE, + CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE, + CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED, + CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); + var candidate = + entry( + identity(11), + BigInteger.TWO, + CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL, + candidateAccountState, + CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED); + var reservation = + reservation(candidate, CanonicalIssuerPartitionReservation.Lifecycle.RESERVED); + var transition = + new CanonicalGameplayBindingTransitionSnapshot( + candidate.transitionId(), + candidate.identity(), + candidate.bindingGeneration(), + candidate.bindingRef(), + candidate.inventoryRevision(), + candidate.issuerReservationId(), + reservation.reservationFence(), + candidate.accountIndexFence(), + prior.bindingRef(), + prior.bindingGeneration(), + CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL, + CanonicalGameplayAccountCoverageEvidence.noActiveFlow()); + return new CanonicalGameplayBindingProvisionalCasEvidence( + transition, + candidate, + reservation, + prior, + reservation(prior, CanonicalIssuerPartitionReservation.Lifecycle.BOUND), + null); + } + + private static CanonicalGameplayBindingInventoryEntry entry( + CanonicalGameplayBindingIdentity identity, + BigInteger generation, + CanonicalGameplayBindingInventoryEntry.Lifecycle lifecycle, + CanonicalGameplayBindingInventoryEntry.IndexState accountState, + CanonicalGameplayBindingInventoryEntry.IndexState issuerState) { + return new CanonicalGameplayBindingInventoryEntry( + identity, + identity.bindingRef(), + generation, + id(20), + id(30 + generation.longValue()), + id(40 + generation.longValue()), + lifecycle, + accountState, + issuerState, + generation); + } + + private static CanonicalIssuerPartitionReservation reservation( + CanonicalGameplayBindingInventoryEntry entry, + CanonicalIssuerPartitionReservation.Lifecycle lifecycle) { + return new CanonicalIssuerPartitionReservation( + entry.issuerReservationId(), + entry.identity(), + entry.bindingGeneration(), + entry.transitionId(), + BigInteger.ZERO, + lifecycle, + id(50), + id(60), + BigInteger.ONE, + BigInteger.TWO, + BigInteger.ONE, + entry.inventoryRevision()); + } + + private static CanonicalGameplayBindingIdentity identity(long session) { + return new CanonicalGameplayBindingIdentity( + id(1), + id(2), + id(3), + id(4), + "SHARED", + id(5), + 1L, + id(session).toString(), + id(6), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.TEN); + } + + private static UUID id(long value) { + return new UUID(0L, value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java new file mode 100644 index 0000000000..8168fe8b97 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java @@ -0,0 +1,742 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.TlsServerCredentials; +import io.grpc.stub.StreamObserver; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AbortGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseResponse; +import net.firedevops.firemud.account.v1.AccountGameplayAdmissionLeaseServiceGrpc; +import net.firedevops.firemud.account.v1.AcquireGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.FinalizeGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.account.v1.ReadGameplayAdmissionLeaseRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.AcquireRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.OriginalLeaseRequest; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseGrpcCodec.State; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OriginKind; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled Account peer transport proof; the returned lease is codec evidence only. */ +@Timeout(60) +class AccountGameplayAdmissionLeaseClientTest { + private static final String NAMESPACE = "game-session-admission-test"; + private static final String GAME_SESSION_PEER = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String JWT = "header.transient-test-payload.signature"; + private static final UUID REQUEST_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + 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 OTHER_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION_ID = UUID.fromString("99999999-9999-4999-8999-999999999999"); + private static final UUID HOLD_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_FENCE = UUID.fromString("66666666-6666-4666-8666-666666666666"); + private static final UUID DECISION_ID = UUID.fromString("77777777-7777-4777-8777-777777777777"); + private static final String HIGH = "9007199254740993"; + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Gameplay admission lease test CA", + new LoopbackMtlsTestPki.IdentitySpec("client", GAME_SESSION_PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "account-server", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role", + "spiffe://firemud/ns/" + NAMESPACE + "/sa/world-management-service", + true), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-namespace", "spiffe://firemud/ns/other/sa/account-service", true)); + } + + @Test + void allFourOperationsUsePinnedMtlsPeerAndPreserveOriginalLeaseBytes() throws Exception { + var observed = new CopyOnWriteArrayList(); + var acquireRequests = new CopyOnWriteArrayList(); + var finalizeRequests = new CopyOnWriteArrayList(); + var readRequests = new CopyOnWriteArrayList(); + var abortRequests = new CopyOnWriteArrayList(); + var deadlines = new CopyOnWriteArrayList(); + Server server = + server( + "account-server", + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() { + @Override + public void acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + capture(observed, deadlines); + acquireRequests.add(request); + try { + AcquireRequest parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(request); + observer.onNext( + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireResponse( + parsed, lease(), State.PENDING, null, null, null)); + observer.onCompleted(); + } catch (RuntimeException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("controlled fixture rejected") + .asRuntimeException()); + } + } + + @Override + public void finalizeGameplayAdmissionLease( + FinalizeGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + capture(observed, deadlines); + finalizeRequests.add(request); + OriginalLeaseRequest parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(request); + observer.onNext( + AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeResponse( + parsed, parsed.originalLeaseEvidence(), State.PENDING, null, null, null)); + observer.onCompleted(); + } + + @Override + public void readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + capture(observed, deadlines); + readRequests.add(request); + OriginalLeaseRequest parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(request); + observer.onNext( + AccountGameplayAdmissionLeaseGrpcCodec.toReadResponse( + parsed, parsed.originalLeaseEvidence(), State.PENDING, null, null, null)); + observer.onCompleted(); + } + + @Override + public void abortGameplayAdmissionLease( + AbortGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + capture(observed, deadlines); + abortRequests.add(request); + OriginalLeaseRequest parsed = + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest(request); + observer.onNext( + AccountGameplayAdmissionLeaseGrpcCodec.toAbortResponse( + parsed, parsed.originalLeaseEvidence(), State.PENDING, null, null, null)); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + client.init(); + var acquired = client.acquire(REQUEST_ID, JWT, candidate(), target(), new BigInteger(HIGH)); + byte[] originalBytes = + acquired.originalLeaseEvidence().canonicalJson().getBytes(StandardCharsets.UTF_8); + client.finalizeLease(JWT, originalBytes, DECISION_ID); + client.read(JWT, originalBytes); + client.abort(JWT, originalBytes, null); + + assertThat(observed) + .containsExactly( + GAME_SESSION_PEER, GAME_SESSION_PEER, GAME_SESSION_PEER, GAME_SESSION_PEER); + assertThat(acquireRequests).hasSize(1); + assertThat(acquireRequests.getFirst().getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); + assertThat(finalizeRequests) + .singleElement() + .satisfies( + request -> { + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes); + assertThat(request.getBindingDecisionUuid(0)).isEqualTo(DECISION_ID.toString()); + }); + assertThat(readRequests) + .singleElement() + .satisfies( + request -> + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes)); + assertThat(abortRequests) + .singleElement() + .satisfies( + request -> { + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes); + assertThat(request.getBindingDecisionUuidCount()).isZero(); + }); + assertThat(deadlines) + .hasSize(4) + .allSatisfy( + deadline -> { + long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); + assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); + }); + assertThat(acquired.toString()).doesNotContain(JWT); + } finally { + stop(server); + } + } + + @Test + void wrongAccountRoleAndNamespaceAreRejectedBeforeServerHandlerReceivesJwt() throws Exception { + for (String identity : List.of("wrong-role", "foreign-namespace")) { + var calls = new AtomicInteger(); + Server server = + server( + identity, + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() { + @Override + public void acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.acquire(REQUEST_ID, JWT, candidate(), target(), new BigInteger(HIGH))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay admission lease acquisition failed") + .hasMessageNotContaining(JWT); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + } + + @Test + void foreignNamespaceLeaseWithMatchingCallerIsRejectedBeforeOriginalLeaseRpc() throws Exception { + var calls = new AtomicInteger(); + Server server = + server( + "account-server", + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() { + @Override + public void finalizeGameplayAdmissionLease( + FinalizeGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + + @Override + public void readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + + @Override + public void abortGameplayAdmissionLease( + AbortGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + Map foreignCarrier = new LinkedHashMap<>(lease().carrier()); + foreignCarrier.put("targetNamespace", "other"); + foreignCarrier.put("callerWorkload", "spiffe://firemud/ns/other/sa/game-session-service"); + byte[] foreignLeaseBytes = + AccountGameplayAdmissionLeaseEvidence.fromCarrier(foreignCarrier) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8); + + assertThatThrownBy(() -> client.finalizeLease(JWT, foreignLeaseBytes, DECISION_ID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not correlate"); + assertThatThrownBy(() -> client.read(JWT, foreignLeaseBytes)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not correlate"); + assertThatThrownBy(() -> client.abort(JWT, foreignLeaseBytes, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not correlate"); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + + @Test + void responseWireLimitRejectsOversizedAccountReplyWithRedactedError() throws Exception { + var calls = new AtomicInteger(); + Server server = + server( + "account-server", + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() { + @Override + public void acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onNext( + AccountGameplayAdmissionLeaseResponse.newBuilder() + .addSchemaVersion(1) + .addOriginalLeaseEvidenceUtf8( + ByteString.copyFrom( + new byte + [AccountGameplayAdmissionLeaseGrpcCodec.MAX_RESPONSE_WIRE_BYTES + + 1])) + .build()); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.acquire(REQUEST_ID, JWT, candidate(), target(), new BigInteger(HIGH))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account gameplay admission lease acquisition failed") + .hasMessageNotContaining(JWT); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + @Test + void allFourOperationsPreserveOnlySanitizedRemoteStatusAndRedactJwt() throws Exception { + Server server = + server( + "account-server", + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() { + @Override + public void acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + failWithSecret(observer, Status.Code.DEADLINE_EXCEEDED); + } + + @Override + public void finalizeGameplayAdmissionLease( + FinalizeGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + failWithSecret(observer, Status.Code.UNAVAILABLE); + } + + @Override + public void readGameplayAdmissionLease( + ReadGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + failWithSecret(observer, Status.Code.PERMISSION_DENIED); + } + + @Override + public void abortGameplayAdmissionLease( + AbortGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + failWithSecret(observer, Status.Code.FAILED_PRECONDITION); + } + }); + try (var client = client(server)) { + client.init(); + byte[] originalBytes = lease().canonicalJson().getBytes(StandardCharsets.UTF_8); + + assertSanitizedStatusFailure( + () -> client.acquire(REQUEST_ID, JWT, candidate(), target(), new BigInteger(HIGH)), + Status.Code.DEADLINE_EXCEEDED, + "Account gameplay admission lease acquisition failed"); + assertSanitizedStatusFailure( + () -> client.finalizeLease(JWT, originalBytes, DECISION_ID), + Status.Code.UNAVAILABLE, + "Account gameplay admission lease finalization failed"); + assertSanitizedStatusFailure( + () -> client.read(JWT, originalBytes), + Status.Code.PERMISSION_DENIED, + "Account gameplay admission lease read failed"); + assertSanitizedStatusFailure( + () -> client.abort(JWT, originalBytes, null), + Status.Code.FAILED_PRECONDITION, + "Account gameplay admission lease abort failed"); + } finally { + stop(server); + } + } + + @Test + void malformedResponseRetainsOnlyTheCodecSafeDiagnostic() throws Exception { + Server server = + server( + "account-server", + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() { + @Override + public void acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest request, + StreamObserver observer) { + observer.onNext( + AccountGameplayAdmissionLeaseResponse.newBuilder() + .addSchemaVersion(2) + .addOriginalLeaseEvidenceUtf8(ByteString.copyFromUtf8(JWT)) + .build()); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.acquire(REQUEST_ID, JWT, candidate(), target(), new BigInteger(HIGH))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account returned invalid gameplay admission lease evidence") + .hasCauseInstanceOf(IllegalArgumentException.class) + .satisfies( + failure -> { + assertThat(failure.getCause()) + .hasMessage("Unsupported Account admission lease schema") + .hasNoCause(); + assertThat(throwableText(failure)).doesNotContain(JWT); + }); + } finally { + stop(server); + } + } + + @Test + void rejectsPlaintextNamespaceAndAmbientSqlOrSynchronizationBeforeRpc() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires workload mTLS"); + assertThatThrownBy( + () -> + new AccountGameplayAdmissionLeaseClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + "bad namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + + Server server = + server( + "account-server", + new AccountGameplayAdmissionLeaseServiceGrpc + .AccountGameplayAdmissionLeaseServiceImplBase() {}); + try (var client = client(server)) { + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(client::init) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("initialization requires no ambient SQL"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + client.init(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.acquire(null, null, null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("acquisition requires no ambient SQL"); + assertThatThrownBy(() -> client.finalizeLease(null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("finalization requires no ambient SQL"); + assertThatThrownBy(() -> client.read(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read requires no ambient SQL"); + assertThatThrownBy(() -> client.abort(null, null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("abort requires no ambient SQL"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } finally { + stop(server); + } + } + + private static AccountGameplayAdmissionLeaseClient client(Server server) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new AccountGameplayAdmissionLeaseClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static Server server( + String identity, + AccountGameplayAdmissionLeaseServiceGrpc.AccountGameplayAdmissionLeaseServiceImplBase service) + throws Exception { + var serverIdentity = pki.identity(identity); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(serverIdentity), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + GrpcRequestBytePolicy.ordinary(), + GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + factory.addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + return factory.createServer().start(); + } + + private static void capture(List peers, List deadlines) { + var peer = GrpcPeerIdentity.current(); + peers.add(peer == null ? null : peer.uri()); + deadlines.add(Context.current().getDeadline()); + } + + private static void failWithSecret( + StreamObserver observer, Status.Code code) { + Metadata trailers = new Metadata(); + Metadata.Key secret = + Metadata.Key.of("x-controlled-secret", Metadata.ASCII_STRING_MARSHALLER); + trailers.put(secret, JWT); + observer.onError( + Status.fromCode(code) + .withDescription("controlled failure " + JWT) + .asRuntimeException(trailers)); + } + + private static void assertSanitizedStatusFailure( + Runnable operation, Status.Code expectedCode, String expectedMessage) { + assertThatThrownBy(operation::run) + .isInstanceOf(IllegalStateException.class) + .hasMessage(expectedMessage) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expectedCode); + assertThat(failure.getCause()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure.getCause()).getCode()) + .isEqualTo(expectedCode); + assertThat(throwableText(failure)).doesNotContain(JWT); + }); + } + + private static String throwableText(Throwable failure) { + StringWriter text = new StringWriter(); + failure.printStackTrace(new PrintWriter(text)); + return text.toString(); + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static Candidate candidate() { + return new Candidate( + ACCOUNT_ID, + TENANT_ID, + OTHER_ID, + OTHER_ID, + "SHARED", + OTHER_ID, + 71, + OTHER_ID, + OTHER_ID, + new BigInteger(HIGH), + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + new BigInteger(HIGH), + new BigInteger(HIGH), + new BigInteger(HIGH)); + } + + private static Target target() { + var ownerRequest = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT_ID, + "world", + OTHER_ID, + OTHER_ID, + "SHARED", + OTHER_ID, + VERSION_ID, + new BigInteger(HIGH).longValueExact(), + REQUEST_ID.toString(), + "c".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + new BigInteger(HIGH).longValueExact(), + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity(ownerRequest, HOLD_ID, HOLD_FENCE); + return new Target( + NAMESPACE, + "tenant", + TENANT_ID, + "world", + "World", + OTHER_ID, + "realm", + "Realm", + 11, + 71, + OTHER_ID, + "SHARED", + OTHER_ID, + VERSION_ID, + 99, + new BigInteger(HIGH).longValueExact(), + new BigInteger(HIGH).longValueExact(), + "d".repeat(64), + new BigInteger(HIGH).longValueExact(), + REQUEST_ID.toString(), + "c".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + HOLD_ID, + HOLD_FENCE, + hold.holdBindingDigest(), + 101, + "sha256:" + "a".repeat(64), + OwnerProofOutcome.COMMITTED, + false, + Instant.parse("2026-10-25T00:00:00Z"), + "PRESEEDED_ONLY"); + } + + private static AccountGameplayAdmissionLeaseEvidence lease() { + Map value = new LinkedHashMap<>(); + value.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + value.put("schemaVersion", "1"); + value.put("mode", "PUBLIC_PRODUCTION"); + value.put("targetNamespace", NAMESPACE); + value.put("callerWorkload", GAME_SESSION_PEER); + value.put("requestId", REQUEST_ID.toString()); + value.put("leaseId", TENANT_ID.toString()); + value.put("leaseFence", HIGH); + value.put("leaseKind", "NEW_BINDING"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", ACCOUNT_ID.toString()); + scope.put("tenantId", TENANT_ID.toString()); + scope.put("realmId", OTHER_ID.toString()); + scope.put("worldSlug", "world"); + scope.put("realmSlug", "realm"); + scope.put("playableStateNamespaceId", OTHER_ID.toString()); + scope.put("playableStateScope", "SHARED"); + scope.put("gameInstanceId", OTHER_ID.toString()); + scope.put("characterId", OTHER_ID.toString()); + scope.put("sessionId", OTHER_ID.toString()); + scope.put("bindingGeneration", HIGH); + scope.put("catalogRevision", HIGH); + scope.put("pointerVersion", HIGH); + scope.put("regionId", OTHER_ID.toString()); + scope.put("regionEpoch", HIGH); + value.put("bindingScope", scope); + value.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), HIGH), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), HIGH), + "privateRealmGrantVersions", List.of())); + value.put("issuanceFence", HIGH); + value.put( + "membershipBaseline", + Map.of( + "membershipLifecycleState", + "ACTIVE", + "membershipVersion", + Map.of(TENANT_ID.toString(), HIGH), + "membershipAuthorityGeneration", + HIGH)); + List> checkpoints = new ArrayList<>(); + for (String suffix : + List.of( + "account/" + ACCOUNT_ID, + "issuer/firemud-account-service", + "membership/" + ACCOUNT_ID + "/" + TENANT_ID, + "tenant/" + TENANT_ID)) { + checkpoints.add( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : HIGH)); + } + value.put("outboxCheckpoints", checkpoints); + value.put( + "tokenIdentityEvidence", + Map.ofEntries( + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("operationId", OTHER_ID.toString()), + Map.entry("issuanceRequestId", OTHER_ID.toString()), + Map.entry("tokenJti", OTHER_ID.toString()), + Map.entry("tokenSHA256", jwtSha256(JWT)), + Map.entry("tokenGeneration", HIGH), + Map.entry("issuanceFence", HIGH), + Map.entry("tokenIdentityFence", HIGH), + Map.entry("tokenProfile", "game-session-account-delegation"), + Map.entry("issuedAt", "999"), + Map.entry("notBefore", "999"), + Map.entry("expiresAt", "1300"))); + value.put("evaluatedAt", "1000000"); + value.put("expiresAt", "1015000"); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(value); + } + + private static String jwtSha256(String jwt) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(jwt.getBytes(StandardCharsets.UTF_8))); + } catch (Exception unavailable) { + throw new IllegalStateException("SHA-256 unavailable"); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntentTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntentTest.java new file mode 100644 index 0000000000..355c5982b4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntentTest.java @@ -0,0 +1,67 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayLegacyMigrationDisposition; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayAccountAdmissionFenceIntentTest { + @Test + void modelCopiesRowsAndNamesThePlannedFenceAsUninstalledIntent() { + UUID accountId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID plannedFence = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var cohort = + new ArrayList<>( + List.of( + CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( + 0, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.BINDING, + "binding-reference", + tenantId, + namespaceId, + "{\"lifecycle\":\"CANDIDATE_PREPARED\"}"))); + var targets = + new ArrayList<>( + List.of( + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + 0, tenantId, namespaceId))); + var intent = + new CanonicalGameplayAccountAdmissionFenceIntent( + operationId, + requestId, + accountId, + BigInteger.ONE, + plannedFence, + BigInteger.TEN, + new CanonicalGameplayLegacyMigrationDisposition( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE, + "sha256:" + "a".repeat(64)), + CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT, + cohort, + targets, + "sha256:" + "b".repeat(64), + "sha256:" + "c".repeat(64)); + + cohort.clear(); + targets.clear(); + + assertThat(intent.state()) + .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.State.ACQUISITION_INTENT); + assertThat(intent.plannedAccountAdmissionFence()).isEqualTo(plannedFence); + assertThat(intent.cohortRows()).hasSize(1); + assertThat(intent.barrierTargets()).hasSize(1); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairOwnerTest.java new file mode 100644 index 0000000000..e30cf4e1e4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairOwnerTest.java @@ -0,0 +1,41 @@ +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.verifyNoInteractions; + +import io.lettuce.core.RedisClient; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameplayAccountMemberRepairOwnerTest { + @Test + void refusesSynchronizationOnlyContextBeforeSqlOrRedisWork() { + DSLContext dsl = mock(DSLContext.class); + RedisClient redisClient = mock(RedisClient.class); + var owner = + new CanonicalGameplayAccountMemberRepairOwner( + dsl, redisClient, RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + + try { + TransactionSynchronizationManager.initSynchronization(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + + assertThatThrownBy(() -> owner.repair(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Binding-local account member repair phases cannot share an ambient transaction"); + + verifyNoInteractions(dsl, redisClient); + } finally { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerTest.java new file mode 100644 index 0000000000..3e537bf58b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerTest.java @@ -0,0 +1,155 @@ +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.verifyNoInteractions; + +import io.lettuce.core.RedisClient; +import java.lang.reflect.Modifier; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountIndexMember; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountMemberRepairOperation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountMemberRepairRedisScriptContribution; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameplayAccountMemberRepairRedisOwnerTest { + @Test + void installedDescriptorDeclaresOnlyTheGlobalAccountSetAndBoundLocalAction() { + var descriptor = + RedisScriptCatalog.loadInstalled(getClass().getClassLoader()) + .require(CanonicalGameplayAccountMemberRepairRedisScriptContribution.SCRIPT_ID); + + assertThat(descriptor.owner()).isEqualTo("game-session-service"); + assertThat(descriptor.principal()).isEqualTo("gamesession_coord_app"); + assertThat(descriptor.role()).isEqualTo(RedisScriptDescriptor.RedisRole.COORDINATION); + assertThat(descriptor.keys()) + .containsExactly( + new RedisScriptDescriptor.KeySpec( + "accountIndex", + "session:game:index:account:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)); + assertThat(descriptor.category()) + .isEqualTo(RedisScriptDescriptor.ScriptCategory.SESSION_ACCOUNT_INDEX); + assertThat(descriptor.arguments()).hasSize(12); + assertThat(descriptor.resetSensitivity()) + .isEqualTo(RedisScriptDescriptor.ResetSensitivity.CLUSTER); + assertThat(descriptor.outcomes()) + .extracting(RedisScriptDescriptor.OutcomeSpec::code) + .containsExactly( + "MEMBER_ADDED", + "MEMBER_ALREADY_PRESENT", + "WRONG_KEY_TYPE_OR_EXPIRY", + "INVALID_ARGUMENTS"); + } + + @Test + void readbackHasNoCallerAccessibleConstructorOrFactory() { + assertThat( + Arrays.stream( + CanonicalGameplayAccountMemberRepairRedisOwner.Readback.class + .getDeclaredConstructors())) + .allSatisfy( + constructor -> assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue()); + assertThat( + Arrays.stream( + CanonicalGameplayAccountMemberRepairRedisOwner.Readback.class.getDeclaredMethods())) + .noneMatch( + method -> + Modifier.isStatic(method.getModifiers()) + && !Modifier.isPrivate(method.getModifiers())); + } + + @Test + void refusesToOpenRedisWhileAnAmbientSqlTransactionIsActive() { + RedisClient client = mock(RedisClient.class); + var owner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + client, RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> owner.projectAndRead(operation())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("projection is unavailable"); + verifyNoInteractions(client); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void refusesToOpenRedisWhileAmbientSynchronizationIsActiveWithoutSqlTransaction() { + RedisClient client = mock(RedisClient.class); + var owner = + new CanonicalGameplayAccountMemberRepairRedisOwner( + client, RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); + try { + TransactionSynchronizationManager.initSynchronization(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + + assertThatThrownBy(() -> owner.projectAndRead(operation())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("projection is unavailable"); + verifyNoInteractions(client); + } finally { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + } + + static CanonicalGameplayAccountMemberRepairOperation operation() { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + CanonicalGameplayBindingRef bindingRef = + CanonicalGameplayBindingRef.of(tenantId, UUID.randomUUID(), UUID.randomUUID().toString()); + UUID accountIndexFence = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + UUID coverageFence = UUID.randomUUID(); + BigInteger bindingGeneration = BigInteger.valueOf(7); + BigInteger snapshotRevision = BigInteger.valueOf(11); + String member = + new CanonicalGameplayAccountIndexMember(bindingRef, bindingGeneration, accountIndexFence) + .value(); + var obligation = + new CanonicalGameplayBindingAccountIndexObligation( + transitionId, + 0, + bindingRef, + accountId, + tenantId, + CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN, + bindingGeneration, + null, + accountIndexFence, + CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS, + CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED, + BigInteger.valueOf(10), + CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED, + null, + null); + return new CanonicalGameplayAccountMemberRepairOperation( + transitionId, + operationId, + BigInteger.valueOf(2), + coverageFence, + snapshotRevision, + bindingRef, + accountId, + tenantId, + bindingGeneration, + accountIndexFence, + obligation, + member, + BigInteger.valueOf(3)); + } +} 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 index 98a3a354a7..459b536515 100644 --- 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 @@ -3,6 +3,7 @@ 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @@ -18,8 +19,10 @@ import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingRef; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; @@ -36,6 +39,27 @@ class CanonicalGameplayBindingInventorySqlTest { private static final long RUNTIME_GAME_INSTANCE_ID = 918273645L; private static final BigInteger REGION_EPOCH = new BigInteger("76543210987654321"); + @Test + void malformedStoredRepairOperationIsTranslatedAtTheDecoderBoundary() throws Exception { + Record row = mock(Record.class); + UUID tenantId = UUID.randomUUID(); + CanonicalGameplayBindingRef bindingRef = + CanonicalGameplayBindingRef.of(tenantId, UUID.randomUUID(), "session"); + Mockito.when(row.get("desired_action", String.class)).thenReturn("ADD_OR_RETAIN"); + Mockito.when(row.get("account_control_state", String.class)) + .thenReturn("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + Mockito.when(row.get("binding_ref", byte[].class)).thenReturn(bindingRef.bytes()); + Mockito.when(row.get("account_id", UUID.class)).thenReturn(UUID.randomUUID()); + Mockito.when(row.get("tenant_id", UUID.class)).thenReturn(tenantId); + Mockito.when(row.get("transition_id", UUID.class)).thenReturn(UUID.randomUUID()); + Mockito.when(row.get("obligation_ordinal", Integer.class)).thenReturn(0); + Mockito.when(row.get("original_action", String.class)).thenReturn("MALFORMED_ACTION"); + + assertThrows( + CanonicalGameplayBindingInventoryConflictException.class, + () -> invoke("toMemberRepairOperation", row)); + } + @Test void everyInventoryInsertHelperKeepsColumnsValuesAndBindingsAligned() throws Exception { DSLContext dsl = mock(DSLContext.class); @@ -44,6 +68,8 @@ void everyInventoryInsertHelperKeepsColumnsValuesAndBindingsAligned() throws Exc Record coverageControl = mock(Record.class); Mockito.when(coverageControl.get("state", String.class)) .thenReturn("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + Mockito.when(coverageControl.get("last_operation_fence", BigDecimal.class)) + .thenReturn(BigDecimal.ZERO); Mockito.doReturn(coverageControl) .when(dsl) .fetchOne(Mockito.anyString(), Mockito.any(Object[].class)); @@ -136,12 +162,14 @@ void everyInventoryInsertHelperKeepsColumnsValuesAndBindingsAligned() throws Exc 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(GameSessionAccountDelegationProfile.ISSUER, candidate.value("issuer_id")); 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(GameSessionAccountDelegationProfile.ISSUER, reservation.value("issuer_id")); assertEquals("RESERVED", reservation.literal("lifecycle")); BoundInsert regionObligation = @@ -272,7 +300,7 @@ private static Fixture fixture() { "f0f46b01-57f6-47e8-a714-9fbcefe49b56", UUID.fromString("e375e81b-9c7a-40e5-b361-0f39bd06f4c1"), REGION_EPOCH, - UUID.fromString("b8c9ff0c-48a3-4388-ae0a-03f4f5a3e721"), + GameSessionAccountDelegationProfile.ISSUER, BigInteger.valueOf(43), BigInteger.valueOf(47), BigInteger.valueOf(53), 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 index d9e47a8860..ddbe01aad9 100644 --- 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 @@ -20,6 +20,7 @@ import java.util.Properties; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAccountCoverageEvidence; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingAccountIndexObligation; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; @@ -113,8 +114,9 @@ void retainedTargetOrUnknownNamespaceKeyRemainsUnchangedAndBlocksReconciliation( } @Test - void onlyCanonicalNonNilIssuerProjectionIsExcludedAndPreservedWithoutReadingValue() { - String issuerProjection = "session:game:auth:issuer-generation:v1:" + UUID.randomUUID(); + void onlyExactAccountIssuerProjectionIsExcludedAndPreservedWithoutReadingValue() { + String issuerProjection = + "session:game:auth:issuer-generation:v1:" + GameSessionAccountDelegationProfile.ISSUER; RedisFixture fixture = redisFixtureWithScans( scans( @@ -140,8 +142,12 @@ void onlyCanonicalNonNilIssuerProjectionIsExcludedAndPreservedWithoutReadingValu } @Test - void malformedIssuerProjectionKeyIsDeniedWithoutMutation() { - for (String issuerId : List.of("not-a-uuid", "00000000-0000-0000-0000-000000000000")) { + void unsupportedIssuerProjectionIdentityIsDeniedWithoutMutation() { + for (String issuerId : + List.of( + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "77777777-7777-4777-8777-777777777777")) { String malformed = "session:game:auth:issuer-generation:v1:" + issuerId; StringRedisTemplate redis = redisWithScans(scans(List.of(), List.of(), List.of(malformed))); @@ -150,7 +156,8 @@ void malformedIssuerProjectionKeyIsDeniedWithoutMutation() { reconciler(redis) .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(2))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .hasMessageContaining("malformed issuer projection key"); + .hasMessageContaining("unsupported issuer identity") + .hasMessageContaining("preserve legacy UUID issuer keys"); verify(redis, times(4)).execute(any(RedisCallback.class)); verifyNoRedisMutationOrValueRead(redis); @@ -159,7 +166,8 @@ void malformedIssuerProjectionKeyIsDeniedWithoutMutation() { @Test void repeatedCanonicalIssuerVisitsAreDeduplicatedButRemainVisitBounded() { - String issuerProjection = "session:game:auth:issuer-generation:v1:" + UUID.randomUUID(); + String issuerProjection = + "session:game:auth:issuer-generation:v1:" + GameSessionAccountDelegationProfile.ISSUER; StringRedisTemplate redis = redisWithScans( scans( @@ -585,7 +593,6 @@ private static CanonicalRows canonicalRows() { 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(); @@ -605,7 +612,7 @@ private static CanonicalRows canonicalRows() { UUID.randomUUID().toString(), regionId, BigInteger.ONE, - issuerId, + GameSessionAccountDelegationProfile.ISSUER, BigInteger.ONE, BigInteger.ONE, BigInteger.valueOf(8), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryTest.java new file mode 100644 index 0000000000..7b175ce658 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryTest.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class CanonicalGameplayTenantGameplayTagRepositoryTest { + @Test + void acceptsOnlyBoundedOpaqueTagsWithoutRedisDelimitersOrHashTags() { + assertThatCode( + () -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g2147483647-0123456789abcdef0123456789abcdef")) + .doesNotThrowAnyException(); + + assertThatThrownBy( + () -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g1-{0123456789abcdef0123456789abcdef")) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g1-0123456789abcdef0123456789abcdef:other")) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g0-0123456789abcdef0123456789abcdef")) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThatThrownBy( + () -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g1-0123456789ABCDEF0123456789abcdef")) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + } +}