diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index bb46173ece..bd0c08132c 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -32,13 +32,11 @@ Game Design issues each new game row an opaque canonical tenant UUID and keeps e ## Isolated Run-Owned Authored-World Fixture Receipt -The claimed local Compose fixture may register an authored-world source through Game Design's existing owner-local transaction primitive, using the persisted game's actual canonical tenant identity and one stable registration request. The resulting `AuthoredWorldSourceEvidence` is fixture input: `ResolveLaunchDescriptor` must still validate the exact committed source and current binding over the authenticated Game Session connection. Existing proto fields carry that source tuple; numeric tenant/template identifiers alone do not authorize launch. This path introduces no production source issuer, creation RPC, or Account admission authority. +The claimed fixed local Compose producer uses the existing fresh creation owner before ordinary game-row save, then the source registration, Version/bundle, launch descriptor and realm-policy owners. It refuses unowned existing game rows. The source registration request deliberately equals the fixture operation UUID; creation request and owner operation identities remain separately retained actual values, with no inferred creation-request equality. Numeric source keys alone do not authorize launch. This path introduces no production source issuer, creation RPC or Account admission authority. -Only the Game Design owner writes the run/project-bound receipt. The capability pins the actual Game Session and World Management recipient leaf certificates, each checked against the same actual CA and exact development workload URI, while retaining the existing operation-ID derivation. Registration and seed state must commit before Game Design independently reads the source and its three owner snapshots; only an exact match permits descriptor resolution. The real default-template/no-overrides descriptor is then resolved and committed through the proxied owner service, independently read with its actual request/result digests, and compared with a second source and owner-snapshot read before atomic receipt publication. Rollback, absent, partial, changed, or ambiguous evidence publishes nothing. The existing `NEW_GAME_ROW` outbox side effect remains intact; receipt publication neither delivers that outbox nor establishes World intake or activation. +Game Design alone receives writable receipt-directory access. The immutable receipt carries actual fresh creation/source evidence, all four launch snapshots and the existing owner policy seal, mounted read-only by Game Session and World. `RunOwnedFixtureLaunchReadback` independently verifies committed creation/source/snapshot/descriptor values; the existing policy owner retains complete original request bytes and the seal with committed readback before atomic publication. Ordinary demo seeding cannot register source or publish receipts, and restart cannot amend original evidence to newer state. The existing `NEW_GAME_ROW` outbox side effect remains intact; receipt publication neither delivers it nor proves World intake or activation. The normative grammar, seal commitment and ordering are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). -The receipt belongs to the existing claimed run/project lifecycle, carries the actual persisted launch descriptor protobuf alongside the three existing owner snapshots, and is mounted read-only by Game Session and World Management. Game Design alone receives the receipt directory writable access. Ordinary Compose demo seeding does not authorize source registration or receipt publication. A restart reuses the original immutable source operation and receipt; wrong-run, malformed, conflicting, stale, or missing evidence fails closed before launch mutation. The normative immutable receipt grammar and consumer boundary are in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); current producer construction and proof status belong to the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). - -For launch preflight, the owner receipt also carries actual committed release, artifact-state, and version-state read projections through the same atomic file handoff. Game Design captures and independently verifies those projections outside the writer transaction; the fixture does not invoke the three production read RPCs. Their exact-peer authentication followed by default denial remains the production contract until operation-specific authority exists. The canonical bounded evidence and proof contract is in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). +The realm-policy owner uses explicit Human and fixed-fixture variants. Fixture policy never supplies or acquires Human PublishedSet, terminal, capture or protection children, and Human guards remain exact. Fixture launch projections are owner-local committed reads, not permission to invoke the three production release/version/artifact RPCs: those authenticate the exact candidate peer and deny before owner reads pending operation-specific authority. Producer construction and candidate-specific proof remain recorded by the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair); this contract does not claim actual producer-to-Game-Session-to-World runtime or genuine handoff completion. The separate `GetCompleteLaunchBinding` production RPC retains its exact candidate peer check and then defaults to `PERMISSION_DENIED` before owner reads pending operation-specific tenant/scope authority. The owner-local complete-binding service still returns the descriptor with its release attestation for fixture proof; it does not replace or derive the run-owned receipt's independently captured release, artifact-state, and version-state projections. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 7552344320..a68182fbdd 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,7 +8,11 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The run-owned Compose repair now carries Game Design's committed launch-read projections and actual resolved launch-descriptor protobuf with the source receipt. Game Session accepts them only through the typed evidence carrier created by its existing trusted data-package parser/coordinator after fixed capability checks; the generic `StartSession` API cannot construct or select that carrier. Fixture preflight compares the descriptor against authenticated `ResolveLaunchDescriptor` and checks the actual release reference, template/source binding, artifact state, and version state without calling Game Design's three production release/version/artifact read RPCs. The capability retains both actual recipient pins and the shared CA pin; this local path does not authorize public admission or change production RPC permissions. The canonical evidence shape and ordering are in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); receipt ownership and producer consequences remain in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). Implementation and proof status are recorded in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff). +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. + +`GameSessionControlPlaneService.GetRunOwnedFixtureLaunchAssociation` is a fixed, default-off source read of that exact `STARTING` allocation. It authenticates the same-namespace World workload and retained recipient certificate before decoding caller selectors, then requires the original operation and policy-seal digest. It returns the exact owner-allocated identities and retained policy request/seal, not World lifecycle, first `OPEN`, Account membership or player authority. The transport bypasses bearer validation only for this method; its exact workload checks remain mandatory. The canonical evidence shape is owned by [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence), with producer consequences in [Game Design API contracts](../game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) and candidate proof in the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#canonical-fixture-launch-owner-stage). + +World materialization, activation and the later canonical first-`OPEN` phase remain unavailable in this stage. The explicit canonical launch-preparation method has no scheduled caller. The retained bootstrap has separate legacy admission outcomes described below; they do not establish completion of the canonical phase. Generic `StartSession` cannot construct the verified fixture carrier, and this stage grants no Human activation or production Game Design release-read permission. The original-claim preparation remains inactive and default-denied: the exact owner repositories, authenticated Account-projection read/pin clients, and descriptor evidence are not registered for runtime admission. It does not establish production composition, World-backed playable admission, continuous owner authority through commit, or historical-owner reconciliation. Current implementation and proof status are recorded in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). @@ -64,7 +68,9 @@ The first admission-pointer bind for a realm is a separate owner transaction fro An exact retry or post-restart recovery reuses the same attempt and hold identities and reconciles the durable attempt, pointer, and audit. Game Session may record `ABORTED` only as a durable terminal outcome that prevents any later commit for that same attempt. World may accept that exact, authenticated owner-readback outcome bound to the same hold and tuple as abort proof; pointer absence, `NOT_FOUND`, `PENDING`, unavailable reads, mismatched tuple/audit, or contradictory evidence is not proof. World finalization requires an authenticated exact Game Session owner readback of the same hold and request identity/digest, tuple, committed pointer, matching audit, and `COMMITTED` outcome. Ambiguous results remain termination-fenced while automatic reconciliation retries; elapsed time does not release the World hold. See the World-owned [initial admission bind hold contract](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). -The local run-owned Compose fixture path now reaches this owner transaction through a scheduled Game Session coordinator, explicitly disabled by default. It accepts only a read-only capability file bound to the claimed run and Compose project, one stable operation ID, the fixed demo/production fixture, and the exact development Game Session and World Management recipient leaf/CA pins; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the persisted Game Design launch descriptor, durably reserves the matching launch identity, and drives World prepare/activate with exact epoch readback so a restart resumes the same launch. The coordinator persists the initial-bind intent before requesting the World hold, then uses the owner-local pointer/audit/outcome transaction and World’s authenticated owner-proof reconciliation; bounded retries reuse the same operation identity, and ambiguous evidence keeps the World termination fence closed. This path is a local Compose fixture bootstrap, not the accepted Account `JOIN` transaction or a production activation path; realm identity and admission-pointer authority remain defined by the [Multi-Tenancy contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract), and explicit join remains owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). See the [run-owned player-flow smoke boundary](../../system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) and [canonical launch-evidence contract](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). Cross-service database race/restart proof remains outstanding; implementation and proof state are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) and [validation workflow](../../../developer-workflows/validation-and-runtime-proof.md). The existing cutover transaction and [replacement hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract) remain distinct; the canonical initial-bind contract is owned by [World](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +When the existing default-off fixture mode is enabled, the retained `RunOwnedInitialAdmissionFixtureCoordinator` executes the legacy initial-admission flow: it starts a `RUNNING` launch, registers the public shared fixture catalog, begins the initial-admission intent, acquires the World hold, and can return `BootstrapResult.COMMITTED` or `BootstrapResult.ABORTED`. Canonical preparation is a separate explicit `RunOwnedCanonicalLaunchPreparationOwner` path with no scheduled caller; the retained legacy outcomes do not establish canonical World activation or canonical first-`OPEN`. The canonical target sequencing remains the [World initial admission bind contract](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract), with fixture evidence defined by [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). + +The fresh canonical Human admission path also refuses preparation, commit and abort before intent reservation, World hold acquisition, pointer or audit effects while authenticated Account protection acquisition and terminal settlement are unavailable. Retained predecessor terminal records remain readable with their original bytes; storage retention does not qualify current Human execution. Existing legacy initial-bind and player flows keep their distinct boundaries. This containment supplies no strict Account `JOIN`, production activation or fixture first-`OPEN` authority; the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#canonical-fixture-launch-owner-stage) records current proof and remaining composition. ### Canonical gameplay roster owner reads diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 4e8be0f5dd..2a1d03f7ea 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -2,9 +2,11 @@ ## Implementation Status +The source-first stage retains the published World fixture verifier, demo seeder and prepare/activate dispatch until the canonical runtime swap. The strengthened fixed capability and Game Design receipt remain required; the active verifier does not adopt the new canonical Game Session allocation read. This retention supplies no new canonical activation, admission, Entity placement or operational-region authority. The canonical run-owned ordering remains defined in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary) records candidate proof and remaining handoffs. + This API contract is target-state canonical; implementation coverage is partial and must not be inferred from target examples alone. -- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The source-retention cut itself does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. A separate component-owner candidate includes graph capture and the ordinary schema-3 digest writer; focused component proof is recorded in the tracker, while its exact checkpoint producer and positive frozen capture remain unqualified. It does not expose a new public publication/activation surface. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). +- The authored-world source-retention cut adds the publication-attempt owner association to source intake and immutable receipt storage, canonical tenant-key protection, UUID-backed version identity, complete launch binding, and publication-fence binding. Focused physical PostgreSQL and mTLS proof is recorded for the tracked World boundary; the exact source revision, check scope, and limitations are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The source-retention cut itself does not implement graph snapshot capture, frozen topology, canonical preparation/execution artifacts (including V62/V63), runtime activation, or gameplay admission, and does not claim external database application. A separate published component-owner candidate includes graph capture and the ordinary schema-3 digest writer; focused component proof is recorded in the tracker, while its exact checkpoint producer and positive frozen capture and packaged runtime remain unqualified. It does not expose a new public publication/activation surface. The canonical persistence boundary is recorded in [Runtime and Data](./runtime-and-data.md#authored-world-source-retention). - The current World Management gameplay bridge serializes runtime room ids as `R-` and rejects scoped decimal `roomInstanceId` values such as `1021`. That storage-derived encoding is not the canonical target identity defined by the [Identifier Glossary](../../system-architecture-identifier-glossary.md). - The bridge, cross-service callers, examples, and focused proof have not migrated together to the scoped decimal `roomInstanceId` contract. The checked-in proof still exercises the legacy encoding. - The typed `ApplyRoomAmbientStatePatch` contract below is target-state: the current service has no complete handler or durable operation/digest-bound guard, so player-significant ambient mutations remain on the fenced Game Session admission/reconciliation path and are not direct table writes. @@ -273,7 +275,7 @@ Game Session owns the initial-bind attempt outcome and the admission pointer. It World finalizes only after an authenticated exact Game Session owner readback proves the same hold and request identity/digest, complete realm-target tuple, no-prior-pointer transition, committed pointer, matching audit event, and durable `COMMITTED` outcome. Definitive abort requires an authenticated exact readback of the durable `ABORTED` outcome bound to that same hold and tuple, with storage semantics that prevent any later commit for that attempt; World may then safely abort the hold. Pointer absence, a snapshot, `NOT_FOUND`, `PENDING`, an unavailable read, a tuple or audit mismatch, or contradictory evidence is not abort proof and never releases the hold. Any ambiguous or mismatched result leaves termination fenced and is reconciled automatically from the durable World hold and Game Session attempt record after retries, response loss, or process restart. Timeouts are repair triggers only; no hold is auto-released by elapsed time. -Current implementation includes the typed `AcquireInitialAdmissionBindHold` RPC restricted to the authenticated Game Session workload, the separate durable World hold record, lifecycle-row serialization that blocks termination while the hold is unresolved, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The run-owned local Compose fixture coordinator now reaches this hold after Game Session records its durable initial-bind intent; the World-owned reconciler resolves it only from authenticated exact owner proof. This remains an opt-in fixture path, not a change to the hold contract or a production activation path. PostgreSQL race/restart proof remains outstanding, and unavailable or mismatched owner evidence continues to fence termination. See the [Game Session initial-admission implementation status](../game-session-service/api-contracts.md#initial-admission-bind), [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) for implementation anchors and current proof state, and the [validation and runtime proof workflow](../../../developer-workflows/validation-and-runtime-proof.md) for check selection. The replacement hold contract above remains separate. +The retained legacy implementation includes the typed `AcquireInitialAdmissionBindHold` RPC, separate durable hold record, lifecycle-row serialization, scheduled fail-closed reconciliation and method-specific Game Session owner-read adapter. When enabled, the published `RunOwnedInitialAdmissionFixtureCoordinator` follows that legacy path through Game Session launch, World hold acquisition, and initial-admission owner commit/readback. Canonical fresh-association and `STARTING` creation with independent readback belong to the explicit `RunOwnedCanonicalLaunchPreparationOwner` call, which has no scheduler; the fixed canonical allocation read is described in the [Game Session API](../game-session-service/api-contracts.md#implementation-status). This legacy path does not establish canonical World materialization/activation or first `OPEN`. Current implementation and proof limits belong to the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary) and [Game Session initial-admission status](../game-session-service/api-contracts.md#initial-admission-bind). The replacement hold contract remains separate. Overdue hold diagnostics are observational. World Management emits `world_initial_admission_bind_overdue_observations_total`, a counter whose unit is one nonterminal hold observation in a bounded reconciliation scan at or after its authoritative `diagnosticExpiresAt`; a repeated scan of the same hold increments it again, so it is not a unique-hold count. Its only label is `error_code`, limited to `none`, `GS_OWNER_READ_UNAVAILABLE`, `GS_OWNER_READ_FAILED`, `GS_OWNER_PROOF_MISSING`, `GS_OWNER_NOT_FOUND`, `GS_OWNER_PENDING`, `GS_OWNER_UNAVAILABLE`, `GS_OWNER_ERROR`, `GS_OWNER_PROOF_MISMATCH`, `GS_OWNER_TERMINAL_PROOF_INCOMPLETE`, `WORLD_LIFECYCLE_PROOF_MISMATCH`, or `other`. Unknown persisted codes map to `other`. The counter never carries tenant, hold, realm, or runtime identifiers; scoped structured reconciliation logs retain the exact `holdId`, `tenantId`, and `gameInstanceId` for diagnosis. The `InitialAdmissionBindHoldOverdueObservations` alert is a diagnostic signal only. Neither its firing nor its absence authorizes readiness, termination, or hold release. @@ -281,9 +283,9 @@ Operator procedure: use the scoped World reconciliation log fields to identify t ## Run-Owned World Launch Evidence -The opt-in run-owned World launch path is disabled by default. Its fixed-server provider independently reads the run capability and source receipt for each prepare, activate, and exact retry, verifies the authenticated same-namespace Game Session TLS peer and World Management's own leaf/CA pins, and performs the existing same-namespace `GetLaunchDescriptor` read with the receipt's actual request and result digests before mutation. It compares the owner response and serving Game Design identity with the actual descriptor and owner snapshots in the receipt; requests cannot select file paths, certificate identities, or evidence. This fixture path does not grant the three default-denied Game Design bundle/version/artifact read RPCs or add a new World read permission. The immutable wire shape and full comparison boundary are owned by [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). +The opt-in run-owned fixture is disabled by default. Target integration requires a fixed-server provider to independently read the immutable capability and source receipt, verify the authenticated same-namespace Game Session peer and World leaf/CA pins, and compare the exact Game Design descriptor and Game Session allocation before any World effect. Requests cannot select file paths, certificate identities or evidence. This boundary grants neither default-denied Game Design bundle/version/artifact RPC authority nor player admission. The complete wire and comparison contract belongs to [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence). -World's local storage consequence is limited to a SHA-256 binding digest and original positive preparing epoch on the existing `world_instance` row, with a partial unique tenant/fixture-operation identity. Every prepare, activation, replay, and restart must revalidate the same complete receipt and stored binding before mutation. An `ACTIVE` lost-response replay may use the retained original `PREPARING` epoch when the complete receipt, authenticated request, and stored binding match; this exception performs no mutation or epoch transition. Ordinary exact current-epoch behavior and storage compare-and-set rules remain unchanged; other stale epochs and non-`ACTIVE` original-epoch replays fail closed. If Temporal orchestration is configured for this isolated fixture, the fixture lifecycle fails closed rather than forwarding without authenticated peer context; the ordinary Temporal path is unchanged. Implementation and proof status, including historical and candidate-specific evidence, are recorded in the [Game Design authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). +The retained published demo seeder and fixture `PREPARING`/`ACTIVE` dispatch remain available for the predecessor bootstrap. Canonical World materialization and activation are not composed with the explicit canonical Game Session launch/read owner or the canonical initial-admission hold and first-`OPEN` path. The active `RunOwnedWorldLaunchEvidenceProvider` verifies the fixed capability and source receipt, authenticates the Game Session peer, and compares the Game Design launch descriptor; it does not read the canonical Game Session allocation. The separate canonical producer and fixed allocation read are described in the [Game Session API](../game-session-service/api-contracts.md#implementation-status). Retained fixture binding-digest and original preparing-epoch columns describe predecessor storage and do not authorize a new lifecycle transition or replay. Current capability and revision-specific proof are recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). ## Instance Termination Contract diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 46db62ee0b..67b9ec31a9 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -2,7 +2,7 @@ ## Implementation Status -- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its source-retention migrations are `V23.1` and `V24`–`V27.2`; the guarded component-owner stage adds `V1003`–`V1007.1`. These forward-only migrations preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The guarded component-owner candidate includes graph capture and the ordinary schema-3 digest writer; focused component proof is recorded in the tracker, while its exact checkpoint producer and positive frozen capture remain unqualified. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). +- The authored-world source-retention cut adds source intake and immutable receipts, protection for canonical UUID-to-legacy World tenant-key associations, UUID-backed Game Design version identity, complete launch binding, publication-fence linkage, and the publication-owner association specified below. Its source-retention migrations are `V23.1` and `V24`–`V27.2`; the guarded component-owner stage adds `V1003`–`V1007.1`. These forward-only migrations preserve existing `V1`–`V23` history and do not establish that any external database has applied them. Focused physical PostgreSQL and mTLS proof for the tracked World boundary, including its exact revision and scope, is recorded in the [World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#authored-world-source-retention-status). The published guarded component-owner candidate includes graph capture and the ordinary schema-3 digest writer; focused component proof is recorded in the tracker, while its exact checkpoint producer and positive frozen capture and packaged runtime remain unqualified. No frozen topology, canonical preparation/execution artifact (including V62/V63), activation, gameplay-admission readiness, or external database application is claimed. See [World API Contracts](./api-contracts.md#grpc-apis). - The current room-cache implementation remains an unversioned TTL-only payload and must use authoritative reads until the target opaque component-version and invalidation proof exists. - World V22 directly renames `room_instance` and `room_instance_exit` columns and renames `idx_room_instance_exit_from` to `idx_room_instance_exit_from_record`; older-binary compatibility and retained-data rollout proof remain open in [Shared Runtime Contracts and Persistence](../../../project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md#unit-5b-persistence-review-consequences). - Historical migration status is incomplete: `V16__runtime_world_event_scope.sql` dropped and recreated `world_event` while changing its legacy template-region reference to a runtime-instance reference, without recorded retained-row mapping or backfill evidence. The current repository cannot reconstruct rows already dropped. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit owner disposition/mapping, with exact readback and lifecycle/admission-isolation evidence; future remediation must add migration and focused proof before contraction is claimed. @@ -16,7 +16,7 @@ - The current Weather path fails closed while its aggregate selector and typed effect fence remain unresolved: `WorldEventServiceImpl.scheduleEvent` rejects `WEATHER_CHANGE` before persistence, and the due-event sweep leaves retained Weather rows unprocessed without changing `region_instance.weather`. Region-bearing non-Weather scheduling also rejects a region outside the event's exact tenant/game-instance scope. This is containment, not Weather implementation or a disposition for retained Weather events; the owner still needs the accepted selector, effect identity/fence, safe reconciliation, and production-shaped proof before admitting Weather. - The non-Weather due-event query now requires a referenced `region_instance` to match the event's tenant/game-instance scope, and the processor defensively leaves a returned mismatch unprocessed. Focused service tests cover wrong-scope and valid rows, and Docker-backed PostgreSQL integration proof covers Weather exclusion, exact tenant/game-instance scope, and single-claim `SKIP LOCKED` behavior; local execution requires Docker/Testcontainers. `V16` still has only a scalar region FK, so retained-data/composite-ownership migration and readback remain separate open work. - For an in-progress termination, the Temporal orchestrator waits for a World lifecycle snapshot with status `TERMINATED` and the exact `(tenantId, gameInstanceId)`; it does not derive a terminal-epoch threshold from the retry argument. Focused proof is in [TemporalWorldLifecycleOrchestratorTest](../../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleOrchestratorTest.java). Temporal lifecycle activity retries do not yet preserve business idempotency after a local commit: activation/failure validate the supplied epoch before checking their terminal state, so a lost response retries stale, and StartSession compensation can fail to reconcile an already-`ACTIVE` world. The operation identity/result must be durable and retries must reconcile exact results; compensation must be ACTIVE-aware. After fail/terminate completes the long-lived workflow, the current orchestrator still signals that closed workflow on an exact terminal retry instead of reconciling the durable terminal row. These current gaps require focused lost-response, compensation, closed-workflow retry, and terminal-result proof. -- The opt-in run-owned launch fixture validates its complete immutable receipt before World prepare and activation. A fixed-server provider reads only the configured capability and receipt paths, checks the exact authenticated Game Session peer and World Management recipient/CA pins, and compares the real descriptor with the existing same-namespace Game Design `GetLaunchDescriptor` response before mutation. The existing `world_instance` row retains only the complete fixture binding digest and original positive preparing epoch; a partial unique tenant/operation index prevents a second instance for the same fixture operation. Retries and restart require identical evidence, and exact `ACTIVE` replay at the retained preparing epoch performs no new lifecycle mutation. Fixture use fails closed when Temporal orchestration would lose authenticated peer context. The canonical evidence contract is in [System Architecture: Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); implementation and proof status are recorded in the [Game Design authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). +- The source-first boundary retains the published fixture bootstrap while canonical source preparation and runtime adoption remain separate. Canonical World materialization, association, holds and first-`OPEN` remain unavailable; retained bootstrap execution does not establish that authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); current implementation and proof limits belong to [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). ## Template and Runtime Ownership diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 2c30986069..750a85e4f5 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -179,15 +179,27 @@ Unknown, partial, stale, contradictory, or unavailable reset, mutation, or clean #### Run-owned v1 launch read evidence -The isolated authored-world fixture carries committed Game Design launch-read snapshots and the actual persisted launch descriptor beside its immutable source receipt. The receipt has twelve envelope fields and thirteen `sourceEvidence` fields; `launchReadEvidence` has exactly six fields: `schema` (`firemud.run-owned-v1-launch-read-evidence.v1`), the actual positive integral `gameTemplateId`, and canonical standard Base64 encodings of the actual `PublishedReleaseBundle`, `VersionAssetArtifactState`, `VersionStateSnapshot`, and `LaunchDescriptor` protobuf messages. The descriptor includes its real authored-world request and result evidence digests. The bounded parser rejects unknown or duplicate JSON fields, malformed UTF-8 or JSON including trailing values, noncanonical Base64, recursively unknown protobuf fields, and payloads exceeding the existing 16 KiB receipt limit. These are actual owner values, not synthesized identities or success defaults. The receipt also binds the actual Game Session and World Management recipient URI/DER leaf pins to the same CA pin; no new schema family or permission is introduced. +The source-first Game Session code isolates canonical `STARTING` preparation in `RunOwnedCanonicalLaunchPreparationOwner`: its fixed-evidence preparation method is explicit and has no scheduler, while `GetRunOwnedFixtureLaunchAssociation` reads only the actual canonical owner allocation. The published `RunOwnedInitialAdmissionFixtureCoordinator` scheduled bootstrap and `GameInstanceServiceImpl` behavior remain in place pending coherent canonical adoption; the explicit preparation path is not wired into that bootstrap. This separation does not establish scheduled canonical allocation, canonical World fixture materialization or activation, or canonical first-`OPEN`; the retained bootstrap is a separate staged implementation. The World preparation and first-`OPEN` paragraphs below define the complete target ordering, not proof that the current owner stage implements them. Owning service trackers retain candidate-specific physical and packaged proof limits. -Game Design commits the seed and source registration transaction first. Before resolving a descriptor, it independently reads the committed source and three current owner snapshots and requires exact equality with captured values. It then resolves the canonical default-template/no-overrides descriptor using the fixture operation ID and actual source tuple through the proxied owner service; that resolution transaction commits. Game Design independently reads the exact descriptor using its actual request and result digests and compares the returned DTO, then rereads the source and three current owner snapshots and refuses publication if any changed. Only after the descriptor and second snapshot match does Game Design atomically publish the complete run/project-bound receipt once; replay must be byte-identical, and the receipt is never amended to match newer owner state. The protobuf value is mapped from the actual descriptor binding by the existing Game Design/Common codec. +The isolated authored-world fixture is an explicit `RUN_OWNED_FIXTURE` authority variant in the existing Game Design policy, Game Session catalog/launch and initial-admission owners, and World source/Version/association/preparation owners. It is available only to the fixed, independently verified run-owned Compose capability under default-off server configuration. The claim commitment, existing UUIDv5 derivation, run/project/operation, claim lock, both recipient URI/DER leaf pins and shared CA pin remain bound throughout. Parsed common capability, receipt, protobuf or policy records are wire data; their shape, digest or successful decoding alone grants no authority. Generic `StartSession` and player ingress cannot select or construct the trusted fixture carrier. -Game Session's trusted data-package parser/coordinator validates the fixed fixture capability and creates the only typed carrier accepted by its fixture consumer. The generic `StartSession` API cannot construct or select that carrier. Game Session preflight uses the verified projections and authenticated `ResolveLaunchDescriptor` result; it does not call the production `GetPublishedReleaseBundle`, `GetVersionState`, or `GetVersionAssetArtifactState` RPCs. World Management independently rereads the immutable capability and receipt under fixed server configuration for every prepare, activate, and exact retry, authenticates the exact Game Session TLS peer, validates its own recipient/CA pins and the serving Game Design owner evidence, and uses the existing same-namespace `GetLaunchDescriptor` read with the receipt's actual request/result digests before mutation. It compares the complete source, descriptor, template, version, bundle, and artifact tuple before accepting fixture evidence. +The immutable source receipt has exactly fourteen envelope fields, including `creationEvidence`, `sourceEvidence`, `launchReadEvidence` and `fixturePolicySeal`. Fresh creation evidence retains its ten fields `{schemaVersion, targetNamespace, creationRequestId, operationId, requestDigest, canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind, evidenceDigest}`. The thirteen-field source evidence retains its actual registration request, owner operation, digest, canonical tenant, source row/key and provenance independently. The fixture operation UUID deliberately equals the source **registration request** UUID, as issued by the producer and checked by the codec. Creation request, creation owner operation, source owner operation and descriptor identities keep their own semantic roles; creation-request equality is not inferred, and no universal pairwise inequality rule replaces actual owner evidence. The current production fixture producer explicitly uses the fixture operation UUID as its creation request ID, so its creation request and source registration request IDs are equal. This is producer behavior; the codec permits distinct creation and registration request IDs and retains their independent semantic roles. -World persists only a SHA-256 binding digest and the original positive preparing epoch on the existing `world_instance` row. The digest binds the complete immutable receipt and capability, both recipient and CA pins, run/project/fixture operation, source evidence, descriptor digests, real instance, and original epoch; a partial tuple is invalid and one fixture operation cannot bind a second instance. Retries and restart must reproduce the same binding before writes. An `ACTIVE` lost-response replay may use the retained original preparing epoch when the complete receipt, authenticated request, and stored binding match; this exception performs no mutation or epoch transition. Ordinary exact current-epoch behavior and storage compare-and-set rules remain unchanged; other stale epochs and non-`ACTIVE` original-epoch replays fail closed. If the isolated fixture is run with Temporal orchestration configured, it fails closed rather than dropping authenticated peer context; ordinary Temporal lifecycle behavior is unchanged. +`launchReadEvidence` has exactly six fields: `schema` (`firemud.run-owned-v1-launch-read-evidence.v1`), the actual positive integral `gameTemplateId`, and canonical standard Base64 encodings of the actual `PublishedReleaseBundle`, `VersionAssetArtifactState`, `VersionStateSnapshot` and `LaunchDescriptor` protobuf messages. The descriptor retains its real authored-world request and result digests. `fixturePolicySeal` has exactly `{schema, ownerService, operationId, requestDigest, evidenceDigest}`, with schema `firemud.run-owned-fixture-policy-seal.v1` and the actual Game Design owner. Its request commitment is the existing closed ordered length-framed encoding of capability, fresh creation, source and all four launch snapshots; its evidence digest binds schema, fixture operation and request digest. The seal's evidence digest is the fixture provenance commitment used by downstream owners, not a substitute Account receipt. The bounded parser rejects unknown or duplicate JSON fields, malformed UTF-8/JSON and trailing values, noncanonical Base64, recursively unknown protobuf fields and payloads exceeding the existing 16 KiB limit. -These local projections do not grant production RPC read permission. Production calls to the three Game Design bundle/version/artifact RPCs authenticate their exact candidate peer first and then deny by default before owner reads until genuine operation-specific authority exists. Candidate peers are Game Session and World Management for version and artifact state, and Game Session, World Management, and Automation & Scripting for release bundles. There is no admin, generic internal-service, or bearer fallback. The producer and consumer implementation/proof status is recorded by the [Game Design authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair), [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#run-owned-canonical-source-handoff), and [World runtime tracker](../project-management/implementation-tracking/world-runtime-and-movement.md#capability-status). Local and physical proof status is not implied by this contract. +Game Design must establish authentic fresh creation from inception through its existing creation owner before ordinary game-row save; an unowned existing row cannot be adopted. It commits creation, source registration, Version/bundle and the exact fixed fixture policy in their existing owners. Before descriptor resolution, it independently reads committed creation, source and the three current launch snapshots and exact-compares the captured results. It resolves the default-template/no-overrides descriptor through the proxied owner service, commits that transaction, independently reads the exact descriptor by its actual request/result digests, and rereads the committed creation/source/snapshots. The existing policy owner retains the complete request bytes and seal with independent committed readback. Only matching owner results permit atomic one-time publication of the complete run/project-bound receipt; restart and replay retain original bytes rather than amending them to newer state. + +Game Session's `RunOwnedCanonicalLaunchPreparationOwner` validates this complete fixed capability and receipt before creating the typed fixture carrier when its explicit preparation method is invoked. The existing canonical catalog and launch owners consume the verified fixed policy and allocate the actual catalog, realm, namespace and private tenant/instance identities, atomically retaining `STARTING` and its launch association. Their fixture variant retains complete original policy-request bytes, seal, source/creation/snapshots and exact catalog/current-row fences with independent committed readback. It contains no invented Human original Account tuple, PublishedSet, terminal, capture, lock or protection. The Human variant continues to require its exact original authority and pin-before-STARTING/lease guards; missing authority metadata on retained rows is unqualified and is never backfilled to grant new authority. + +World independently rereads the immutable capability and receipt for every prepare, activate and exact retry under fixed server configuration. It authenticates the exact same-namespace Game Session TLS peer, verifies its own recipient/CA pins and serving Game Design owner identity, and reads `GetLaunchDescriptor` with the actual receipt request/result digests. It also obtains the exact authenticated `GetRunOwnedFixtureLaunchAssociation` result, including retained original request bytes and policy seal. Each owner read uses a fresh correlation identity, distinct from the fixture operation, with exact request/response echo and closed URI/actual-leaf pins before accepting response evidence. These independent remote owner reads run outside an ambient writer transaction. World compares the complete creation/source/Version/descriptor/bundle/artifact/policy and actual catalog/STARTING association. Game Design source keys, Game Session private tenant/instance keys and World private tenant/Version/instance keys belong to separate services; only actual owner-backed associations relate them. Numeric equality or substitution is not association proof. + +World's existing source intake and Version owners allocate and retain fresh World-local keys. Under their writable `OPEN` guard, the fixed-preset seeder and existing preparation owner materialize `firemud-demo-topology-v1` at those exact keys: one Demo Region, one Demo Zone, Candle-lit Antechamber and Smith's Annex, and the reciprocal NORTH/SOUTH exits. These are six stable template identities with six actual template/runtime mappings, not six-family Human capture evidence. Before any resource write, an immutable expected-content/connectivity seal binds the authentic claim and recipients, complete Game Design source/descriptor/bundle/policy seal, authenticated Game Session association and exact World source/Version allocations. It is distinct from the lifecycle binding. Template INSERT and runtime preparation use the existing exact one-use row manifests together, retain the result atomically, and independently read back the complete template/runtime content and all six mappings outside the writer transaction. Missing, extra, changed or partial topology, unowned existing resources and changed original-binding retries fail closed. Legacy tenant/version `1` rows are never copied or adopted. Demo-region templates confer no operational region or lease authority. + +The existing `world_instance` row retains its original SHA-256 fixture binding and positive preparing epoch, while the existing association and preparation owners retain the owner identities, original evidence bytes, immutable preset seal/content/mappings and preparation result. One fixture operation cannot bind a second instance. Every mutation and restart revalidates these complete original bindings under the existing one-use manifests and lifecycle CAS. An `ACTIVE` lost-response replay may use the retained original `PREPARING` epoch only when the complete authenticated request, capability/receipt, association, preset and stored binding match; it returns immutable original evidence without mutation or epoch transition. Other stale epochs and non-`ACTIVE` original-epoch replays fail closed. Temporal-configured isolated fixture execution fails closed rather than dropping authenticated peer context. + +First `OPEN` bind consumes the allocated canonical catalog/namespace/launch through the existing Game Session initial-admission intent and attempt owners, pointer/event transaction and World hold reconciliation. The intent precedes the hold request; exact fixture provenance survives commit, abort and independent readback. World releases the hold only on authenticated exact `COMMITTED` pointer plus matching audit/terminal proof, or definitive `ABORTED` proof that prevents later commit for the same attempt. Missing, `PENDING`, mismatched or ambiguous evidence keeps termination fenced. Explicit fixture request/proof/lifecycle frames retain the authority kind and exact policy-seal evidence digest; they do not fabricate Account/Human capture, selected-room, graph, protected activation or operational-region proof. The Human frames and complete Human guards remain exact. This local bind is neither Account `JOIN` nor player admission. + +These local owner variants grant no production activation, registration or read permission. The three Game Design bundle/version/artifact RPCs authenticate their exact candidate peer first and deny before owner reads pending genuine operation-specific authority; candidate peers remain Game Session and World for version/artifact state and Game Session, World and Automation & Scripting for bundles, with no admin, generic internal-service or bearer fallback. Fixture association and initial-admission reads remain fixed, authenticated and default-off. The [Game Design authoring tracker](../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair), [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#canonical-fixture-launch-owner-stage) and [World runtime tracker](../project-management/implementation-tracking/world-runtime-and-movement.md#capability-status) own implementation/proof status. This contract does not qualify a receiving candidate or a full runtime: controlled upstream peer data is controlled proof, and actual Game Design-producer-to-Game-Session-to-World execution, all four genuine owner handoffs, Entity and operational-region authority require their own evidence. ### Redis in Tests diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 805c149bba..744a47af31 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -265,6 +265,12 @@ Entry format: - Expected pattern: bound optional external uploads within the containing job's budget and preserve time for required proof artifacts. `continue-on-error` alone cannot protect against whole-job cancellation. Keep cancelled aggregate proof separate from successful individual checks. - Current status: the Codecov step is bounded to two minutes with its existing failure tolerance retained. New-head cloud validation remains required to verify the workflow outcome. +- `2026-10-14`: Wait for the database-owned expiry condition in lock-race proof + - Context: a canonical Game Session pin test established its real PostgreSQL INSERT lock wait, then expected a finite owner lease to have expired after a fixed host sleep. + - Observation: the database still reported the lease live after the sleep, so the intended post-expiry race was not established. + - Expected pattern: retain the original finite lease and exact blocker, poll the same PostgreSQL expiry predicate used by the owner within a bounded deadline, then release the lock and assert refusal without mutation. Do not change the lease, renew authority, weaken the refusal assertion or infer clock skew from the failed sleep assumption. + - Current status: the test now waits for the database-owned expiry condition; current physical qualification remains required. + - `2026-10-14`: Review-period bookkeeping must not contend for provider execution locks - Context: the Overseer reported that Gameplay's three concurrent metadata reset batches encountered active-provider errors during the native rollout, with no actual provider active. - Observation: reset-versus-reset global lock contention was reported as provider activity, and network/full-stack refresh made local counter bookkeeping slow and coupled to unrelated source readiness. @@ -290,6 +296,17 @@ Entry format: - Expected pattern: inspect the exact requested row or declaration before recording an accepted-fix resolution; verify its named anchors instead of relying on a nearby paragraph or a broad substring replacement. - Current status: the exact row is corrected and verified. An immutable audited resolution correction points to the published repair while retaining the original wrong attribution; the User and Overseer were informed. +- `2026-10-14`: Follow typed construction before accepting a missing validation finding. + - Context: A CLI finding claimed World accepted non-STARTING fixture allocations. + - Observation: Main initially accepted it after reading the codec and client but missed the shared result constructor's existing STARTING requirement; the attempted negative fixture failed before reaching World. + - Recovery: The redundant production guard was removed, the decision was corrected in the immutable controller audit, and the public checkpoint correction preserves the original review credit. Focused wire-response rejection proof verifies the actual transitive boundary. + - Expected pattern: Follow the complete typed construction path before adjudicating an absent check. A local consumer need not repeat an invariant already enforced by every constructible input; retained findings and changed code alone are not fix proof. + +- `2026-10-14`: Selected-PR status can exhaust its deadline while reading historical targets + - Observation: Gameplay's full `reviews status --pr 3206` failed at its 120-second deadline in `target_history_pr_3162_cli`, after 99 prior phases, so it produced no completed readiness result. The existing `--summary --json` projection subsequently succeeded; no safety guard was bypassed. + - Consequence and unknowns: the timeout delayed current-front adjudication. The diagnostic identifies historical evidence work, but does not establish which lookup caused the overall latency or that the summary avoids that work. + - Current status: the exact diagnostic was reported to Overseer for the controller owner's existing performance work. Prefer the documented summary projection for routine status and retain an explicit unavailable result when a required inspection times out; reconsider at the owner's next measured performance checkpoint. + - `2026-10-15`: Keep Gradle metadata refresh behind a confirmed resolution failure - Context: Validation's module matrix globally refreshed all dependency metadata to recover a cached negative Spring Boot 4.1.1 result. Later warm-cache builds still made remote Maven requests; retained CI logs show both a Maven Central rate limit and a separate Netty POM connection reset before tests. - Observation: a full metadata refresh on every affected module repeats repository checks and disables configuration-cache reuse even when the restored dependency cache is warm. A dependency-resolution cause can be separated from compiler or test failures when the nested repository error and execution stage are retained. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index b908b5fceb..8ea3a2d3b9 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -12,6 +12,14 @@ The ordinary World producer emits digest schema 3 for its tagged Entity-referenc The coherent receiving successor for [PR #3196](https://github.com/benhook1013/FireMUD/pull/3196) is prepared on the latest qualified parent `d7f78ebbb5e2d13bfd73885202c0742c41e3f94b` from [PR #3189](https://github.com/benhook1013/FireMUD/pull/3189). Its coherent boundary includes Game Design/shared-contract/caller/proof paths, preserved Logging receiving paths, and bounded CI/process repairs. The PR’s generated scope section records its current path count. The ten earlier Account/process prerequisite paths are inherited from the preparation parent rather than duplicated. The current local composition gate and source proofs have the exact attribution below. The published CLI2 source `371f0dcedc75690aadb7cb267b4a19ddbc8c16ff` passed its exact-head Validation, CodeQL, License and Security gates. Current review fixes require new published-source CI; Hosted/CLI review and rebuilt packaged receiver proof remain separate gates. Earlier results retain their original source attribution. +### Closed fixture policy producer + +The successor to the guarded World owner stage uses Game Design's existing fresh creation, source registration, Version/bundle, descriptor and realm-policy owners to publish the fixed run-owned receipt only after independent committed readback. Forward [V1031](../../../services/game-design-service/src/main/resources/db/migration/V1031__run_owned_fixture_policy_owner_seal.sql) keeps Human and fixture policy headers mutually exclusive: fixture policy supplies no Human capture, terminal or Account-protection children, and the existing Human capture foreign key remains mandatory for Human rows. The original migration artifacts and predecessor Human owner bytes remain unchanged. + +The current selected stage on parent `3533ec932ff76d8f7ada3947dfff419b6004b152` passed the whole Game Design `check -PfullCheck` with formatting, generated metadata, static checks, 504 freshly executed unit cases and 139 freshly executed PostgreSQL cases, all with zero failures, errors or skips. The physical cases cover actual creation/source/release/descriptor/policy sealing, closed variants, exact replay/refusal and retained predecessor rows including original bytes and `xmin`. This qualifies the owner-local fixture producer; consumer Game Session/World and packaged runtime qualification remain separate. It supplies no genuine Account publication authorization or closure of the four Gameplay handoffs. The receipt contract remains in [Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), with local API consequences in [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt). + +The subsequent #3206 consumer configuration correction rejects blank World workload namespaces before fixture-client construction, makes legacy DSL-only Game Session fixture calls fail explicitly before storage, and binds the fresh-tenant Game Design client to the exact same-namespace server peer before RPC dispatch. Initialization and closure are explicit; client shutdown releases its monitor before draining certificate-watcher callbacks. The inspected local postimages pass 27 fresh unit cases, two controlled physical mTLS cases and 39 fresh cross-service cases, with affected static and formatting checks, in 4m15s. The TLS cases prove a valid peer read and zero RPC dispatch to wrong-workload and wrong-namespace peers sharing the test CA. These controlled transport results do not establish genuine owner production, packaged receiver qualification or activation; published-head CI and current review obligations remain separate. + ### Coherent owner receiving prerequisite The receiver implements mandatory fresh-v2 operation values, actual ordinary asset ownership and synchronized export projection, and asset-bound reviewed-base v2 evidence. It preserves the 21 byte-identical Game Design migration artifacts at V1003–V1023 and adds V1024 for fresh asset-bound reviews. Forward [V1025](../../../services/game-design-service/src/main/resources/db/migration/V1025__template_config_transaction_witness_projection.sql) corrects the existing template-insert witness to compare PostgreSQL's typed 32-bit transaction ID rather than parsing the epoch-bearing transaction ID as 32-bit text; V1008 remains unchanged. Forward [V1026](../../../services/game-design-service/src/main/resources/db/migration/V1026__template_config_verifier_diagnostics.sql) changes only five template-config verifier diagnostic prefixes; its predecessor function and migration bytes remain unchanged. All 59 predecessor Game Design migrations, 109 predecessor Account migrations and applied Saga artifacts remain unchanged. The latest parent corrects the unmerged Account V1003 tail; whole Account-input byte identity is not carried forward from the earlier preparation parent. Default Flyway ordering and exact installed-parent manifests remain authoritative; no retained operation, review or source history is backfilled. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 2ba7c21cb0..96d18ab48c 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -6,11 +6,21 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +### Canonical fixture launch owner stage + +Source-first canonical preparation is isolated in `RunOwnedCanonicalLaunchPreparationOwner`. It validates the fixed capability and closed Game Design receipt, and its explicit `prepareFixedVerifiedFixtureLaunch()` call creates and independently reads the canonical fresh association, catalog, and `STARTING` launch. It has no scheduler. The fixed authenticated `GetRunOwnedFixtureLaunchAssociation` RPC reads only that canonical owner allocation and returns its retained source/policy evidence. The published `RunOwnedInitialAdmissionFixtureCoordinator` scheduled bootstrap and `GameInstanceServiceImpl` behavior remain unchanged pending coherent canonical adoption; the explicit source owner is not wired into that bootstrap. Focused source and retained-bootstrap checks are qualified below; they do not establish scheduled canonical allocation, canonical World/first-`OPEN`, or genuine player admission. + +The source-first reconstruction on the `29ba9330f80dd3f2682ab8574c7806be505ba4bb` working base passed 98 focused Game Session unit cases (eight explicit preparation-owner, thirteen retained coordinator, 68 GameInstance service, seven fixture association-read and two protected-interceptor cases). Its native receiving gate passed 32 fresh cases: four canonical launch and nine catalog PostgreSQL cases, two World TLS and three World PostgreSQL cases, and fourteen Game Design producer cases, all without failures, errors or skips. The TLS test uses controlled creation/source evidence with a real authenticated descriptor read; the World PostgreSQL test uses controlled upstream evidence and actual owner/CAS storage. The unchanged World unit scope contributes 33 passing cases from the preceding execution. Affected static checks pass, including the final TLS builder correction. Fresh source-built baseline and same-version restart both passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK`, followed by successful original-capability teardown of the claimed Compose project. Because the packaged scripts force fixture mode off, the fresh source-built and same-version restart WebSocket/Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK` results establish only ordinary default-off baseline behavior, not the enabled fixture coordinator or canonical admission; canonical player-flow closure remains open. Earlier failed receipt-constructor, operation-ID and test-format gates remain recorded separately. + +The published scheduled bootstrap and its existing fixture lifecycle behavior are retained until a coherent canonical adoption; the explicit source owner does not replace or activate them. Canonical World materialization/activation, first `OPEN`, and all four genuine handoffs remain open. The historical validation results below predate the source-first owner split and do not qualify this candidate. Exact published head `e9f026aa49bb49c7635abd0055febf520aa18321` passed [source Validation run 38496689054](https://github.com/benhook1013/FireMUD/actions/runs/38496689054), with 2,202 fresh unit, 39 cross-service and 267 integration cases, zero failures, errors or skips. The earlier local 260-integration attempt with nine failures predates that passing candidate and retains only its original unpublished-input attribution; it is not the current whole-service result. Exact `eef2c317cac61211a5619badc70e3380f5696995` subsequently passed its Game Session matrix job in [run 38505527497](https://github.com/benhook1013/FireMUD/actions/runs/38505527497), with 2,505 fresh cases and zero failures, errors or skips; the separate Dev Tool Contract Checks job failed on the World tracker verification-state cell. The snapshot guard matches V34.3’s 128-character column, and focused physical proof covers 121/128-character reservations and rejection above 128. The seven Human containment/retention cases include pre-1006 COMMITTED/ABORTED history upgraded without changing original fields, bytes or `xmin`. Rebuilt packaged proof on exact `eef2` reached healthy services and passed WebSocket `WORLDS` and `LOGIN`, then failed `PLAY` with `PLAY_SELECTION_REQUIRED`; Telnet was unrun and default authenticated cleanup removed the project resources. Its browse result contained no selectable world, consistent with the missing materialization/first-OPEN boundary. The operational dependency-readiness correction is published separately in #3210; its 70 focused cases and fresh packaged Game Session/Game Logic readiness plus WebSocket LOGIN proof do not establish an admitted `LOOK`. The canonical receipt and phase ordering remain in [Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence). + +The migration-preservation correction restores the exact original V1005/V1006 Git blobs and applies their stricter guards through forward V1011, above the complete Game Session/shared-Saga frontier of 1010. Forward [V1011.1](../../../services/game-session-service/src/main/resources/db/migration/V1011.1__canonical_human_launch_policy_provenance.sql) additionally requires complete non-empty policy evidence for new Human launches and rejects fixture provenance. It does not adopt historical all-NULL catalogs or change existing launch/catalog rows or their `xmin`; the focused PostgreSQL guard proof preserves those retained rows. Retained-target application status remains unknown; the source does not classify those originals as never applied. Owning jOOQ generation and 15 focused native PostgreSQL cases passed across qualified runs: ten initial-admission cases, one run-owned launch case and four launch-preparation cases. The admission suite checks original SQL bytes, original applied-history checksums and validation, staged original-1010 and direct pre1006 upgrades, unchanged historical row bytes/`xmin`/source/pointer/audit, preserved trigger/function identity, strict fresh-write rejection and transactional rollback for malformed retained protection. Four historical scenarios are one JUnit case. Selected style/static checks and pinned-parent Flyway version validation passed. These are original-history compatibility fixtures, not actual retained deployment-cohort qualification; a discovered mixed original/edited history remains a separate deployment hold requiring owner adjudication. No history repair, adoption, checksum rewrite or genuine Account terminal authority is established. + ### Run-owned canonical source handoff -The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the repaired candidate. The repaired local fixture consumes Game Design's atomic run/project receipt containing actual committed release-bundle, artifact-state, version-state, and persisted launch-descriptor evidence, pins the exact evidence across retries, and binds its internal launch to the registered source. Game Session obtains its verified typed carrier only through the existing trusted data-package parser/coordinator; generic `StartSession` cannot construct or select that path. It compares the actual descriptor to authenticated resolution and preflights against the owner projections without invoking the three production Game Design release/version/artifact read RPCs. The receipt also carries the exact Game Session and World Management recipient pins; it does not grant production RPC authority. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. +The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the current source-first candidate. The source-first owner consumes the closed run/project-bound Game Design receipt with actual fresh creation and source evidence, all four immutable launch snapshots (release bundle, artifact state, version state, and persisted launch descriptor), and the fixture policy seal. It pins the exact receipt across reads and binds canonical preparation to the registered source. Game Session obtains its typed fixture carrier only through the trusted data-package parser; `RunOwnedCanonicalLaunchPreparationOwner` exposes `createVerifiedFixtureStartingLaunch` plus independent `readVerifiedFixtureLaunch` only through explicit preparation, with no scheduler. The new `GetRunOwnedFixtureLaunchAssociation` RPC is read-only and reads the canonical repository. The explicit owner is not wired into the retained published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap or existing `GameInstanceServiceImpl` behavior. This path has no descriptor-resolution or preflight phase and invokes none of the three production Game Design release/version/artifact read RPCs. Generic `StartSession` cannot construct or select the fixture carrier. The receipt also carries the exact Game Session and World Management recipient pins; it does not grant production RPC authority. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. -Focused unit tests cover immutable replay, descriptor comparison, certificate-pin mismatch, malformed/unknown evidence, and bundle/template/source, artifact state/epoch, and version state/epoch mismatches. All fourteen [fixture capability cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java) passed in the 2026-10-12 canonical Game Session full check; the whole unit task ran 2,080 cases with seventeen environment-dependent skips and no failures. This is local unit proof. The prior `aaecdcc92e5de67047a7af80649b30ed773c91c1` revision rebuilt and booted the run-owned Compose images and passed WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` in [runtime run 38190595607](https://github.com/benhook1013/FireMUD/actions/runs/38190595607); that result belongs to that revision. Current-candidate physical PostgreSQL and fresh packaged runtime proof remain pending; local database-dependent tests skipped without Docker. Source-only containment does not implement production producer handoffs or Account admission; both routed findings remain open and capability ratings are unchanged. +Historical focused unit tests cover immutable replay, descriptor comparison, certificate-pin mismatch, malformed/unknown evidence, and bundle/template/source, artifact state/epoch, and version state/epoch mismatches; those results do not qualify the current source-first split. The new `RunOwnedCanonicalLaunchPreparationOwnerTest` and fixture association-read tests passed eight and seven cases respectively in the current focused gate described above. All fourteen [fixture capability cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java) passed in the 2026-10-12 canonical Game Session full check; the whole unit task ran 2,080 cases with seventeen environment-dependent skips and no failures. This remains historical local unit proof. The prior `aaecdcc92e5de67047a7af80649b30ed773c91c1` revision rebuilt and booted the run-owned Compose images and passed WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` in [runtime run 38190595607](https://github.com/benhook1013/FireMUD/actions/runs/38190595607); that result belongs to that revision. Bounded source proof on `4896eaa8939cd4783106c9dbe0ef8e88515dd6ed` covers 2,207 unit and 39 cross-service cases. Current native PostgreSQL proof comprises 278 unique cases across the 277-case previous pass and the final 10-owner pass, with nine overlapping cases. The raw full integration attempt failed; only the qualified focused owner proof is established. The source-first reconstruction’s fresh and restart packaged `PLAY`/`LOOK` proof is qualified above; these historical native counts retain their original attribution. Source-only containment does not implement production producer handoffs or Account admission; both routed findings remain open and capability ratings are unchanged. This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. @@ -28,7 +38,7 @@ Retained bootstrap correction: V8 recognizes only the unchanged, provenance-back Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. -Initial-admission owner boundary: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +Initial-admission owner boundary: Retained intent, pointer, audit and terminal storage remain separate from current execution. Fresh canonical Human prepare, commit and abort now refuse before intent, World hold, pointer and audit effects because authenticated Account protection acquisition/currentness and terminal settlement are unavailable. Canonical Game Session `STARTING` allocation and independent readback belong to the explicit `RunOwnedCanonicalLaunchPreparationOwner` call, which has no scheduler. The retained `RunOwnedInitialAdmissionFixtureCoordinator` remains the legacy scheduled bootstrap and uses the legacy World hold/admission path. Canonical World materialization/activation, hold and first `OPEN` remain open. Earlier whole-stack and terminal tests belong to their recorded revisions and do not qualify this current boundary. Current scoped proof is recorded above; no strict Account `JOIN`, production activation or generalized runtime-ID convergence is claimed. The authenticated internal `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiving APIs currently fail closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command, coordinator, follow-up, or queue mutation. Ordinary gameplay APIs are unchanged. [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) covers the receiving-boundary gate; lower-level admission tests do not prove durable receiver-epoch projection or the cross-service pause-versus-handoff race. The gate and remaining successor proof are recorded in the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). @@ -61,7 +71,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and opt-in fixture coordination are wired locally. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandlerIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java). The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java). The historical original-owner producer and caller guard are exercised by [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) and [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java). Durable owner behavior is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java) and [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java). Exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service cases; all 2,327 passed with zero skips, failures, or errors. Cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | +| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog, retained intent storage, and retained pointer/audit components plus typed owner-proof reads are wired locally; retained intent storage does not establish current fresh reservation wiring. The source-first canonical owner exposes an explicit canonical `STARTING` create/readback path; its focused owner and association-read tests have the earlier qualified results recorded below, but it is not wired into the retained scheduled bootstrap. The published fixture bootstrap remains in place. Fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, while canonical World materialization/activation and first `OPEN` remain unproved. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandlerIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java). The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java). The historical original-owner producer and caller guard are exercised by [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) and [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java). The current Human bind and abort refusal boundary is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java): both refuse before intent, World hold, pointer, or audit effects; this unit proof does not establish a current Human commit or durable terminal settlement. Incomplete Human preparation denial before intent reservation or World acquisition is separately covered by [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java), `incompleteHumanPreparationDeniesBeforeIntentReservationOrWorldAcquire`. Retained attempt, pointer, audit, and history preservation/readback are covered separately by [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); that retained-storage proof does not establish a successful current Human commit or abort. The source-first explicit canonical preparation and read path has focused test sources in [RunOwnedCanonicalLaunchPreparationOwnerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java) and [GameSessionFixtureLaunchAssociationReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java); their eight and seven cases passed on the source-first reconstruction based on `29ba9330f80dd3f2682ab8574c7806be505ba4bb`, as attributed above; they were not rerun on this documentation head and do not establish scheduled canonical preparation, World materialization, or first-`OPEN`. Historical bootstrap tests remain in [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java), while earlier repository persistence proof is in [GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java). Historical exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service cases; those 2,327 passing cases predate the current Human refusal boundary. The current scoped [Validation run 38496689054](https://github.com/benhook1013/FireMUD/actions/runs/38496689054) is for exact revision `e9f026aa49bb49c7635abd0055febf520aa18321`, not the whole current HEAD; it passed 2,202 unit, 267 integration, and 39 cross-service cases. Cross-service PostgreSQL race/restart proof and live Compose execution remain unestablished. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedCanonicalLaunchPreparationOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwner.java); [published bootstrap coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | | `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | @@ -204,7 +214,7 @@ The recorded Markdown and contract checks for these slices include `./gradlew li ## Active Gaps -- Initial-admission pointer creation is durable only within Game Session’s local owner ledger. The run-owned local Compose path now supplies an opt-in coordinator and a launch identity that resumes across restart; this does not satisfy Account’s strict `JOIN` validation-through-commit gate, activate production, or complete generalized runtime-ID migration. The general `StartSession` retry path and cross-service PostgreSQL race/restart proof remain open; startup stays closed by default and ambiguity continues to fence World termination. See the canonical [World hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and [run-owned smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). +- Initial-admission pointer creation is durable only within Game Session’s local owner ledger. The explicit `RunOwnedCanonicalLaunchPreparationOwner` prepares the opt-in canonical `STARTING` allocation with exact replay/readback but has no scheduled caller; the retained scheduled Compose coordinator follows the legacy admission path. The canonical World and first-`OPEN` phases remain unqualified here, while fresh canonical Human preparation/terminal writes deny before effects pending Account protection; this does not satisfy Account’s strict `JOIN` validation-through-commit gate, activate production, or complete generalized runtime-ID migration. The general `StartSession` retry path and cross-service PostgreSQL race/restart proof remain open; startup stays closed by default and ambiguity continues to fence World termination. See the canonical [World hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and [run-owned smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). - TICK-03 is now the accepted command-level boundary: required versus optional effects, permitted terminal combinations, intentional `PARTIAL`, and stronger atomicity routing must be classified per command family. Current implementation and proof remain partial; no status promotion is implied. - TICK-04 remains partial and proof remains incomplete: operation/digest-bound participant guards and focused crash/retry/dead-letter coverage across World and Entity are still gaps under accepted contracts. Command-plan admission, `planOrdinal`, and root allocation are accepted under ADR 0183; implementation and proof remain incomplete. ADR 0069 owns effect identity, replay, and terminal-outcome rules; ADR 0071 owns durable tick commit before fenced coordination cleanup. - Replacement cutover remains partial at the Game Session boundary: the current wire/durable record/reconciler has no complete proof of exact cross-service cutover binding, post-swap readback, safe abort, or finalization, and must not infer success from a pointer write or an in-memory termination request. See the canonical [World Management replacement cutover hold contract](../../architecture/microservices/world-management-service/api-contracts.md#replacement-cutover-hold-contract) and [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 68e6241755..32689f5585 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +### Canonical fixture launch receiving boundary + +The source-first front retains the published World fixed-evidence verifier, scheduled demo topology and fixture preparation/activation dispatch while the canonical replacement is prepared separately. It consumes the strengthened closed capability and Game Design receipt without requiring the new canonical Game Session association from the running bootstrap. Mandatory canonical-association adoption, World materialization and first-`OPEN` move together to the later coherent runtime swap; this retained path does not establish canonical World/Entity/operational-region authority. The reconstructed boundary passed three World PostgreSQL and two real mTLS cases with controlled upstream evidence, alongside actual Game Design producer and Game Session source-storage cases. Its 33 unchanged World unit cases retain their preceding successful execution; affected static checks and the final two-case TLS rerun pass. Fresh source-built baseline and same-version restart both passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK`; fixture mode was disabled for these packaged runs, so they qualify only the ordinary default-off baseline, not the enabled retained fixture coordinator. Original-capability teardown removed the claimed project containers, network and volumes. Canonical owner-chain closure remains open. + +Historical canonical-adoption candidate `4cee3da213ad2b4d1ba27a4bbb7e418efee88a8a` after [PR #3203](https://github.com/benhook1013/FireMUD/pull/3203) passed the World whole-service/static/documentation gate in 2m43s: 292 fresh unit and 65 fresh integration cases (63 PostgreSQL, two controlled mTLS socket cases), zero failures/errors/skips. That candidate refused fixture writes and proved passive storage/retention; its results do not qualify the current retained-bootstrap reconstruction. The socket cases used controlled remote handlers, and all four genuine canonical owner handoffs remain open. + ### Guarded graph capture and frozen owner stage The World owner stage carries immutable donor migrations V1003–V1007 for guarded six-family topology, authored/canonical graph storage and schema-3 capture. The ordinary digest writer now emits schema 3 with tagged numeric-versus-canonical Entity references through its installed interface. The installed 31 World plus three Saga artifacts remain unchanged. New V1007.1 restores the installed V27.2 stable same-tenant legacy UPDATE fastpath after V1004; later donor guard replacements must preserve that same invariant through their own forward repairs. No shared/protobuf or Game Design/Game Session fixture contracts are introduced, and the existing private fixture bootstrap is unchanged. @@ -32,7 +38,7 @@ The later storage-classification and typed launch-scope correction `6d41311efe75 This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). -The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Its separate World launch-evidence provider rereads the immutable capability and receipt, verifies the caller and both recipient pins, and reads the real Game Design descriptor before World mutation. World persists a binding digest and original preparing epoch on `world_instance`; exact ACTIVE replay at that epoch with identical evidence does not cause another transition. Historical original-source compositional proof for the bounded fixture lifecycle was accepted at `f330c8721824d063a5eba09afd5388631ae184b9`: unchanged `d44429e683a80271d3a03e0e31e2f80fe5b33a4c` World socket (2), PostgreSQL (3), provider (5), and lifecycle unit (22) cases passed without skips, complemented by rebuilt positive Smoke run `38174536549` on merge `763d96cafe10037b9d2ebe3fb250e99261ca2f0e` (`ec16942` plus `f330`). The current private reconstruction has separate consolidated local checks: its two authenticated socket cases pass, while three World PostgreSQL cases skip without Docker and rebuilt packaged Smoke/restart remain unrun. Historical Smoke does not prove startup refusal (skipped), packaged process restart, per-RPC counters, later protected activation, or hold race/restart; exact provenance and complementary producer/denial proof are recorded in [the Game Design fixture status](game-authoring-publishing-and-activation.md#run-owned-authored-world-fixture-repair). Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract), [run-owned launch-evidence contract](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). +The retained initial-admission code includes the typed Game Session workload-only acquire RPC, durable World holds, lifecycle-row termination serialization and fail-closed reconciliation. The source-first reconstruction retains the published coordinator and World fixture PREPARING/ACTIVE dispatch for the existing bootstrap. Canonical Game Session STARTING preparation and authenticated association read are explicit source operations, separate from that running bootstrap. They do not establish canonical World materialization, lifecycle, hold or first-OPEN authority. General owner integration, strict Account JOIN and production activation remain open. Current proof is qualified in [Current Status](#current-status) and the canonical owner boundary remains in [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md). The subsequent World/Game Design review-fix gate verifies fixed immutable graph/result/evidence serialization across application-mapper changes and direct PostgreSQL frozen-capture rejection/immutability guards. All 295 World unit cases passed in the preceding combined gate and were reused by the final World gate; all 64 PostgreSQL integrations ran freshly in that final gate, with no failures, errors or skips, plus World and affected Game Design static/formatting checks and Markdown/link validation. The Game Design gate passed 507 fresh unit cases, including the controlled schema-3 wire/gate and schema-2/4 refusal cases. Its broader PostgreSQL run selected 136 cases: 120 passed and 16 failed before assertions because a fixture endpoint refused connections; the cause remains unknown, so the full Game Design physical gate is not established by this run. This component proof does not qualify the missing complete-commit producer, positive live frozen capture, packaged runtime or activation. @@ -52,7 +58,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; the guarded graph/capture stage adds `V1003`–`V1007.1`, without establishing that external databases applied them. This retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. The opt-in run-owned launch path validates its immutable capability and receipt, then stores their binding digest and original preparing epoch through [RunOwnedWorldLaunchEvidenceProvider](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java) and [V23.0.1](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql). Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. Focused provider, workload-mTLS, and fixture PostgreSQL test anchors are listed; candidate PostgreSQL/restart and production-activation proof remain unproved. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [V1003 authored graph snapshot](../../../services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql); [V1004 guarded region commits](../../../services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql); [V1005 guarded UUID topology commits](../../../services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql); [V1006 canonical frozen topology](../../../services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql); [V1007 digest schema 3 capture](../../../services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql); [V1007.1 legacy update fastpath](../../../services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql); [WorldDraftTopologyCommitRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java); [WorldAuthoredGraphSnapshotCapture.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java); [WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java); [WorldGuardedAuthoredTopologyPlanTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. Run-owned fixture evidence binding is implemented, but candidate PostgreSQL, packaged restart, and production activation remain unproved. Initial-bind PostgreSQL race/restart proof and live Compose execution also remain open. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: the authored-world source-retention boundary is implemented through `WorldAuthoredSourceIntakeRepository`, `WorldAuthoredVersionIdentityRepository`, `WorldCompleteLaunchBindingRepository`, and `WorldDesignPublicationFenceRepository`, with migrations `V23.1`–`V27.2`; the guarded graph/capture stage adds `V1003`–`V1007.1`, without establishing that external databases applied them. This retained evidence does not activate a runtime or establish gameplay admission. Its focused source, identity, launch-binding, and publication-fence proof is recorded above and linked below. Version-scoped topology and the owner-local Draft mutation algorithm exist, but registered `ApplyWorldDesignMutation` ingress fails closed before dispatch pending complete caller/tenant authorization and owner publication proof; instance lifecycle exists, while generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The retained initial-admission hold contributes to the `AR-3.1` lifecycle handoff through lifecycle serialization and exact owner-proof reconciliation; current fixture preparation does not acquire it. The published coordinator, seeder and fixture preparation/activation dispatch remain available for the retained bootstrap. Separate canonical STARTING preparation and association read are source operations; controlled source proof does not establish canonical materialization, lifecycle, hold or first-OPEN authority. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: World retains lifecycle and initial-admission hold storage and read boundaries. The retained bootstrap verifies the closed Game Design receipt using its published World fixed-evidence path; source-built baseline and same-version restart pass both transports with fixture mode disabled, qualifying only the ordinary default-off baseline; there is no current packaged proof of the enabled retained fixture coordinator. The separate canonical source preparation/read boundary does not qualify canonical materialization, lifecycle, hold or first-OPEN effects. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [V23.1 source intake](../../../services/world-management-service/src/main/resources/db/migration/V23.1__world_authored_source_intake.sql); [V24 tenant mutation guard](../../../services/world-management-service/src/main/resources/db/migration/V24__world_canonical_tenant_mutation_guard.sql); [V25 publication fence](../../../services/world-management-service/src/main/resources/db/migration/V25__world_design_publication_fence.sql); [V26 launch binding](../../../services/world-management-service/src/main/resources/db/migration/V26__world_complete_launch_binding.sql); [V27 version identity](../../../services/world-management-service/src/main/resources/db/migration/V27__world_authored_version_identity.sql); [V27.1 publication owner binding](../../../services/world-management-service/src/main/resources/db/migration/V27.1__world_publication_owner_binding.sql); [V27.2 legacy tenant claim concurrency](../../../services/world-management-service/src/main/resources/db/migration/V27.2__world_legacy_tenant_claim_concurrency.sql); [V1003 authored graph snapshot](../../../services/world-management-service/src/main/resources/db/migration/V1003__world_authored_graph_snapshot.sql); [V1004 guarded region commits](../../../services/world-management-service/src/main/resources/db/migration/V1004__world_guarded_region_draft_commits.sql); [V1005 guarded UUID topology commits](../../../services/world-management-service/src/main/resources/db/migration/V1005__world_guarded_uuid_topology_commits.sql); [V1006 canonical frozen topology](../../../services/world-management-service/src/main/resources/db/migration/V1006__world_canonical_frozen_topology.sql); [V1007 digest schema 3 capture](../../../services/world-management-service/src/main/resources/db/migration/V1007__world_digest_schema3_capture.sql); [V1007.1 legacy update fastpath](../../../services/world-management-service/src/main/resources/db/migration/V1007.1__world_restore_stable_legacy_update_fastpath.sql); [WorldDraftTopologyCommitRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java); [WorldAuthoredGraphSnapshotCapture.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotCapture.java); [RunOwnedWorldLaunchEvidenceProvider.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java); [RunOwnedWorldLaunchEvidence.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java); [V23.0.1 fixture binding](../../../services/world-management-service/src/main/resources/db/migration/V23.0.1__world_run_owned_fixture_launch_binding.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java); [RunOwnedWorldLaunchEvidenceProviderTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java); [RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java); [RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java); [WorldAuthoredSourceIntakeServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java); [WorldAuthoredVersionIdentityServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java); [WorldCompleteLaunchBindingServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java); [WorldDesignPublicationFenceCommittedReadTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceCommittedReadTest.java); [WorldAuthoredSourceIntakeIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java); [WorldAuthoredVersionIdentityIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java); [WorldCompleteLaunchBindingIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java); [WorldDesignPublicationFenceIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java); [WorldDesignPublicationFenceEvidenceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java); [WorldPublicationOwnerBindingMigrationIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPublicationOwnerBindingMigrationIntegrationTest.java); [WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java); [WorldGuardedAuthoredTopologyPlanTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredTopologyPlanTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Canonical fixture materialization, activation, continuous Account protection, hold acquisition and first OPEN remain unavailable; packaged runtime proof is limited to the ordinary default-off baseline with fixture mode disabled. Genuine owner handoffs, hold/termination race and restart recovery, strict Account JOIN and generalized runtime-ID migration remain open. Earlier tests retain their recorded revision attribution; source or fixture read evidence supplies no activation authority. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | @@ -143,7 +149,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - The current Weather path is fail-closed while its selector and typed effect fence remain unresolved: new `WEATHER_CHANGE` scheduling is rejected before persistence, retained Weather rows remain unprocessed and non-mutating, and region-bearing non-Weather events require exact tenant/game-instance scope matching. Focused service proof covers the containment and valid non-Weather path; PostgreSQL integration proof covers Weather exclusion, exact tenant/game-instance scope, and single-claim `SKIP LOCKED` behavior. Safe Weather admission and retained-row reconciliation remain open. - Temporal activation/failure retries still lack durable operation-result reconciliation after a lost response, and StartSession compensation does not reconcile an already-`ACTIVE` world. Exact retries after fail/terminate workflow completion can signal a closed workflow instead of returning the durable terminal result; focused retry, compensation, and closed-workflow proof remains absent. - Replacement cutover still lacks the World-owned one-shot hold record/readback contract: exact source/target `ACTIVE` epoch locking, the nonterminal-hold termination predicate, hold-bound Game Session pointer transaction, safe abort/finalize reconciliation, diagnostic-only expiry, and focused proof. This remains target implementation drift; it does not introduce a new world lifecycle state. -- The run-owned local Compose initial-admission coordinator is implemented, but the general `StartSession` retry path, strict Account `JOIN` validation-through-commit gate, production activation, and generalized runtime-ID migration remain outside this slice. PostgreSQL hold/termination race and restart recovery, plus live Compose proof, remain unproved; World expiry is diagnostic only and no ambiguous outcome releases the termination fence. See the canonical [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and its [focused integration test](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java). +- Canonical Game Session `STARTING` creation with independent readback belongs to the explicit `RunOwnedCanonicalLaunchPreparationOwner` call; its write has no scheduler, and its fixed allocation read is a separate authenticated source operation. Canonical World materialization/activation, the canonical initial-admission hold and first `OPEN` remain unqualified here. The retained published seeder and fixture `PREPARING`/`ACTIVE` dispatch remain available for the predecessor bootstrap; `RunOwnedInitialAdmissionFixtureCoordinator` follows the legacy World hold and admission-owner path. The packaged fresh/restart `PLAY`/`LOOK` verification ran with fixture mode disabled, so it proves the ordinary default-off baseline, not the enabled fixture coordinator. General `StartSession` retries, strict Account `JOIN` validation through commit, production activation, hold/termination race and restart recovery remain open; World expiry is diagnostic and ambiguous outcomes never release a termination fence. See the canonical [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract), [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), and [focused integration proof](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java). - Starter-region preparation still persists hard-coded `SimpleDungeonGenerator` metadata and does not consume the frozen published generation inputs and provenance required by the launch descriptor. - Initial world-event scheduling is absent from the current prepare path despite being canonical lifecycle step 2. - Omitted optional terrain/population stages have no durable `SKIPPED_NOT_REQUIRED` outcome or operator-facing projection, so current lifecycle status cannot distinguish intentional omission from not-started or failed work. diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index dd6b27a860..9746aa5718 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -372,6 +372,7 @@ PY _firemud_smoke_validate_initial_admission_capability() { local path="$1" operation_id="$2" game_session_leaf_sha256="$3" local world_management_leaf_sha256="$4" ca_sha256="$5" + local claim_digest="$FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST" local file_metadata if [[ -L "$path" || ! -f "$path" ]]; then _firemud_smoke_fail "initial-admission capability must be an existing regular non-symlink file." @@ -385,7 +386,8 @@ _firemud_smoke_validate_initial_admission_capability() { if ! python3 - "$path" "$FIREMUD_SMOKE_RUN_ID" \ "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" \ - "$game_session_leaf_sha256" "$world_management_leaf_sha256" "$ca_sha256" <<'PY' + "$game_session_leaf_sha256" "$world_management_leaf_sha256" "$ca_sha256" \ + "$claim_digest" <<'PY' import json import os import re @@ -393,14 +395,14 @@ import stat import sys import uuid -path, run_id, project_name, operation_id, game_session_leaf_sha256, world_management_leaf_sha256, ca_sha256 = sys.argv[1:] +path, run_id, project_name, operation_id, game_session_leaf_sha256, world_management_leaf_sha256, ca_sha256, claim_digest = sys.argv[1:] allowed = { "schema", "runId", "composeProjectName", "operationId", "tenantId", "gameTemplateId", "ownerAccountId", "worldSlug", "worldDisplayName", "realmSlug", "realmDisplayName", "visible", "publicProductionRealm", "requiresCharacterSelection", "stateScope", "characterCreationPolicy", "gameSessionLeafSha256", "gameSessionUriSan", "worldManagementLeafSha256", - "worldManagementUriSan", "caCertificateSha256", + "worldManagementUriSan", "caCertificateSha256", "claimDigest", } def unique_object(pairs): @@ -474,6 +476,7 @@ expected = { "worldManagementLeafSha256": world_management_leaf_sha256, "worldManagementUriSan": "spiffe://firemud/ns/dev/sa/world-management-service", "caCertificateSha256": ca_sha256, + "claimDigest": claim_digest, } safe_id = re.compile(r"[a-z0-9][a-z0-9-]{0,127}\Z") if not safe_id.fullmatch(run_id) or not safe_id.fullmatch(project_name): @@ -607,12 +610,13 @@ ensure_run_owned_initial_admission_capability() { } if ! python3 - "$temporary" "$FIREMUD_SMOKE_RUN_ID" \ "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" \ - "$leaf_sha256" "$world_management_leaf_sha256" "$ca_sha256" <<'PY' + "$leaf_sha256" "$world_management_leaf_sha256" "$ca_sha256" \ + "$FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST" <<'PY' import json import pathlib import sys -path, run_id, project_name, operation_id, game_session_leaf_sha256, world_management_leaf_sha256, ca_sha256 = sys.argv[1:] +path, run_id, project_name, operation_id, game_session_leaf_sha256, world_management_leaf_sha256, ca_sha256, claim_digest = sys.argv[1:] value = { "schema": "firemud.run-owned-initial-admission-fixture.v1", "runId": run_id, @@ -635,6 +639,7 @@ value = { "worldManagementLeafSha256": world_management_leaf_sha256, "worldManagementUriSan": "spiffe://firemud/ns/dev/sa/world-management-service", "caCertificateSha256": ca_sha256, + "claimDigest": claim_digest, } with pathlib.Path(path).open("w", encoding="utf-8") as target: json.dump(value, target, indent=2) diff --git a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh index fd74843df4..6433d785eb 100644 --- a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -37,21 +37,23 @@ expect_failure() { } load_operation_id() { - python3 - "$1" <<'PY' + python3 - "$1" "$FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST" <<'PY' import json import pathlib import sys value = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) +expected_claim_digest = sys.argv[2] expected_fields = { "schema", "runId", "composeProjectName", "operationId", "tenantId", "gameTemplateId", "ownerAccountId", "worldSlug", "worldDisplayName", "realmSlug", "realmDisplayName", "visible", "publicProductionRealm", "requiresCharacterSelection", "stateScope", "characterCreationPolicy", "gameSessionLeafSha256", "gameSessionUriSan", "worldManagementLeafSha256", - "worldManagementUriSan", "caCertificateSha256", + "worldManagementUriSan", "caCertificateSha256", "claimDigest", } assert set(value) == expected_fields, set(value) +assert value["claimDigest"] == expected_claim_digest assert value["schema"] == "firemud.run-owned-initial-admission-fixture.v1" assert value["tenantId"] == 1 assert value["gameTemplateId"] == 1 @@ -105,6 +107,37 @@ reject_replaced_capability() { ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify } +reject_claim_digest_variant() { + local variant="$1" + local backup="$TEST_ROOT/capability-before-claim-digest-$variant.json" + local status=0 + cp -p -- "$base_capability" "$backup" + python3 - "$TEST_ROOT/claim-digest-$variant.json" "$base_capability" "$variant" <<'PY' +import json +import pathlib +import sys + +target, source, variant = sys.argv[1:] +value = json.loads(pathlib.Path(source).read_text(encoding="utf-8")) +if variant == "missing": + del value["claimDigest"] +elif variant == "substituted": + value["claimDigest"] = "0" * 64 +else: + raise SystemExit("unknown claim digest test variant") +pathlib.Path(target).write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") +PY + chmod 444 "$TEST_ROOT/claim-digest-$variant.json" + mv -- "$TEST_ROOT/claim-digest-$variant.json" "$base_capability" + if ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify; then + status=0 + else + status=$? + fi + mv -- "$backup" "$base_capability" + return "$status" +} + reject_missing_restart_capability() { ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only } @@ -175,6 +208,8 @@ ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-onl [[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] expect_failure wrong_claim reject_wrong_claim +expect_failure missing_claim_digest reject_claim_digest_variant missing +expect_failure substituted_claim_digest reject_claim_digest_variant substituted expect_failure wrong_run reject_wrong_run expect_failure wrong_project reject_wrong_project expect_failure symlinked_capability reject_symlinked_capability diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 3f4a39b31d..7bc0c36677 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -48,6 +48,9 @@ service GameSessionControlPlaneService { rpc GetCanonicalGameInstanceLaunchAssociation( GetCanonicalGameInstanceLaunchAssociationRequest) returns (GetCanonicalGameInstanceLaunchAssociationResponse); + // Fixed default-off run-owned fixture allocation read; exact World workload only. + rpc GetRunOwnedFixtureLaunchAssociation(GetRunOwnedFixtureLaunchAssociationRequest) + returns (GetRunOwnedFixtureLaunchAssociationResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -646,6 +649,36 @@ message GetCanonicalGameInstanceLaunchAssociationResponse { int64 owner_fence = 20; } +message GetRunOwnedFixtureLaunchAssociationRequest { + string read_request_id = 1; + string target_namespace = 2; + string fixture_operation_id = 3; + string expected_fixture_policy_evidence_digest = 4; +} + +// Complete immutable fixture provenance plus independently read GS allocations; no Human tuple. +message GetRunOwnedFixtureLaunchAssociationResponse { + string read_request_id = 1; + string target_namespace = 2; + string fixture_operation_id = 3; + string expected_fixture_policy_evidence_digest = 4; + int64 game_session_tenant_id = 5; + int64 game_instance_id = 6; + string canonical_tenant_id = 7; + string game_instance_uuid = 8; + string canonical_version_id = 9; + string canonical_realm_id = 10; + string playable_state_namespace_id = 11; + entity_management.v1.PlayableStateScope playable_state_scope = 12; + int64 catalog_revision = 13; + string current_game_instance_status = 14; + int64 current_row_version = 15; + bytes fixture_policy_request_bytes = 16; + string fixture_policy_seal_operation_id = 17; + string fixture_policy_seal_request_digest = 18; + string fixture_policy_seal_evidence_digest = 19; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java new file mode 100644 index 0000000000..3c0f67ecbd --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java @@ -0,0 +1,320 @@ +package net.firedevops.firemud.common.gamedesign; + +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.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; + +/** Immutable internal evidence associating a frozen source set with its actual sealed release. */ +public final class RealmPolicyPublishedEvidence { + public static final String SET_DIGEST_SCHEMA = "game-design-published-realm-policy-set/v1"; + public static final String POLICY_DIGEST_SCHEMA = "game-design-published-realm-policy/v1"; + + private RealmPolicyPublishedEvidence() {} + + /** One Game Design allocated immutable identity for one effective authored policy. */ + public record Policy(UUID policyId, RealmPolicySource.Policy source, String policyDigest) { + public Policy { + nonNil(policyId, "policyId"); + Objects.requireNonNull(source, "source"); + if (policyDigest == null || !policyDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical policy digest required"); + } + } + } + + /** Complete immutable set and the original owner evidence that authorized its publication. */ + public record PublishedSet( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + int policyCount, + String policySetDigest, + List policies) { + public PublishedSet { + Objects.requireNonNull(target, "target"); + nonNil(sourceCommitId, "sourceCommitId"); + if (versionNumber <= 0 + || sourceEpoch == null + || !sourceEpoch.matches("0|[1-9][0-9]*") + || publishedReleaseBundleRef == null + || publishedReleaseBundleRef.isBlank() + || !digest(publishedReleaseBundleDigest) + || publishWorkflowId == null + || publishWorkflowId.isBlank() + || !digest(manifestHash) + || publicationVersionStateEpoch <= 0) { + throw new IllegalArgumentException("Complete publication-bound policy identity required"); + } + operationBytes = nonEmptyCopy(operationBytes, "operationBytes"); + captureBytes = nonEmptyCopy(captureBytes, "captureBytes"); + terminalEvidenceBytes = nonEmptyCopy(terminalEvidenceBytes, "terminalEvidenceBytes"); + policies = List.copyOf(Objects.requireNonNull(policies, "policies")); + if (policyCount < 1 + || policyCount > RealmPolicySource.MAX_POLICIES + || policyCount != policies.size() + || !digest(policySetDigest)) { + throw new IllegalArgumentException("Complete bounded policy-set evidence required"); + } + var sources = policies.stream().map(Policy::source).toList(); + if (!RealmPolicySource.ordered(sources).equals(sources)) { + throw new IllegalArgumentException("Canonical published policy source order required"); + } + var operation = GameDesignPublicationOperationBinding.fromStored(operationBytes); + if (!operation.account().input().selection().target().equals(target) + || !operation.world().request().publishWorkflowId().equals(publishWorkflowId)) { + throw new IllegalArgumentException("Publication evidence differs from exact TargetProof"); + } + var capture = new DraftAuthorizationFenceBinding.FrameReader(captureBytes); + capture.expect("game-design-realm-policy-source-capture/v1"); + byte[] capturedOperationBytes = capture.bytes(); + String snapshotJson = capture.text(); + capture.requireEnd(); + if (!Arrays.equals(capturedOperationBytes, operationBytes)) { + throw new IllegalArgumentException("Policy capture differs from exact operation bytes"); + } + var snapshot = RealmPolicySnapshot.fromStored(snapshotJson); + var selectedCommit = operation.account().input().selection().selectedCommit(); + if (!snapshot.binding().equals(selectedCommit) + || !snapshot.binding().target().equals(target) + || !snapshot.binding().commitId().equals(sourceCommitId) + || !snapshot.sourceEpoch().equals(sourceEpoch)) { + throw new IllegalArgumentException("Policy capture differs from complete published source"); + } + var terminal = GameDesignPublicationTerminalEvidence.fromStored(terminalEvidenceBytes); + if (terminal.outcome() != GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + || !Arrays.equals(terminal.operationBytes(), operationBytes)) { + throw new IllegalArgumentException("Terminal release evidence differs from policy set"); + } + var release = terminal.releaseContent(); + if (!release.canonicalTenantId().equals(target.canonicalTenantId()) + || !release.canonicalVersionId().equals(target.canonicalVersionId()) + || release.versionNumber() != versionNumber + || !release.publishedReleaseBundleRef().equals(publishedReleaseBundleRef) + || !release.contentDigest().equals(publishedReleaseBundleDigest) + || !release.publishWorkflowId().equals(publishWorkflowId) + || !release.manifestHash().equals(manifestHash) + || terminal.publicationVersionStateEpoch() != publicationVersionStateEpoch) { + throw new IllegalArgumentException("Terminal release evidence differs from policy set"); + } + for (Policy policy : policies) { + if (!policyDigest( + policy.policyId(), + target, + versionNumber, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + policy.source()) + .equals(policy.policyDigest())) { + throw new IllegalArgumentException("Published policy digest differs from full policy"); + } + } + if (!snapshot.policies().equals(sources)) { + throw new IllegalArgumentException("Policy capture differs from complete published source"); + } + if (!computePolicySetDigest( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policies) + .equals(policySetDigest)) { + throw new IllegalArgumentException("Published policy-set digest differs from evidence"); + } + } + + @Override + public byte[] operationBytes() { + return operationBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + + @Override + public byte[] terminalEvidenceBytes() { + return terminalEvidenceBytes.clone(); + } + + @Override + public List policies() { + return List.copyOf(policies); + } + } + + public static String targetProofJson(DraftCommitBinding.TargetProof target) { + Objects.requireNonNull(target, "target"); + return RealmPolicySource.canonical( + Map.of( + "canonicalTenantId", target.canonicalTenantId().toString(), + "canonicalVersionId", target.canonicalVersionId().toString(), + "gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", target.gameDesignVersionTenantKey(), + "sourceGameRowId", Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", target.sourceGameTenantKey(), + "sourceProvenanceKind", target.sourceProvenanceKind())); + } + + public static String policyDigest( + UUID policyId, + DraftCommitBinding.TargetProof target, + int versionNumber, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + RealmPolicySource.Policy source) { + nonNil(policyId, "policyId"); + Objects.requireNonNull(source, "source"); + String evidence = + RealmPolicySource.canonical( + map( + "schema", + POLICY_DIGEST_SCHEMA, + "policyId", + policyId.toString(), + "target", + RealmPolicySource.tree(targetProofJson(target)), + "versionNumber", + versionNumber, + "sourceCommitId", + source.commitId().toString(), + "sourceRevisionId", + source.revisionId().toString(), + "logicalRevisionId", + source.logicalRevisionId(), + "publishedReleaseBundleRef", + publishedReleaseBundleRef, + "publishedReleaseBundleDigest", + publishedReleaseBundleDigest, + "publishWorkflowId", + publishWorkflowId, + "manifestHash", + manifestHash, + "policy", + RealmPolicySource.tree(source.policy().canonicalJson()))); + return sha256(evidence.getBytes(StandardCharsets.UTF_8)); + } + + public static String computePolicySetDigest( + DraftCommitBinding.TargetProof target, + int versionNumber, + UUID sourceCommitId, + String sourceEpoch, + String publishedReleaseBundleRef, + String publishedReleaseBundleDigest, + String publishWorkflowId, + String manifestHash, + long publicationVersionStateEpoch, + byte[] operationBytes, + byte[] captureBytes, + byte[] terminalEvidenceBytes, + List policies) { + var ordered = RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); + if (ordered.size() != policies.size()) { + throw new IllegalArgumentException("Canonical policy order required"); + } + var bySource = + policies.stream().collect(java.util.stream.Collectors.toMap(Policy::source, p -> p)); + var orderedEvidence = + ordered.stream() + .map( + source -> { + Policy policy = bySource.get(source); + return Map.of( + "policyId", policy.policyId().toString(), + "sourceCommitId", source.commitId().toString(), + "sourceRevisionId", source.revisionId().toString(), + "logicalRevisionId", source.logicalRevisionId(), + "worldSlug", source.policy().worldSlug(), + "realmSlug", source.policy().realmSlug(), + "policyDigest", policy.policyDigest()); + }) + .toList(); + String evidence = + RealmPolicySource.canonical( + map( + "schema", SET_DIGEST_SCHEMA, + "target", RealmPolicySource.tree(targetProofJson(target)), + "versionNumber", versionNumber, + "sourceCommitId", sourceCommitId.toString(), + "sourceEpoch", sourceEpoch, + "publishedReleaseBundleRef", publishedReleaseBundleRef, + "publishedReleaseBundleDigest", publishedReleaseBundleDigest, + "publishWorkflowId", publishWorkflowId, + "manifestHash", manifestHash, + "publicationVersionStateEpoch", Long.toString(publicationVersionStateEpoch), + "operationDigest", sha256(operationBytes), + "captureDigest", sha256(captureBytes), + "terminalEvidenceDigest", sha256(terminalEvidenceBytes), + "policyCount", orderedEvidence.size(), + "policies", orderedEvidence)); + return sha256(evidence.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] nonEmptyCopy(byte[] bytes, String name) { + if (bytes == null || bytes.length == 0) { + throw new IllegalArgumentException("Nonempty " + name + " required"); + } + return bytes.clone(); + } + + private static Map map(Object... entries) { + if (entries.length % 2 != 0) { + throw new IllegalArgumentException("Even evidence key/value entries required"); + } + var result = new java.util.LinkedHashMap(); + for (int index = 0; index < entries.length; index += 2) { + result.put((String) entries[index], entries[index + 1]); + } + return result; + } + + private static boolean digest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void nonNil(UUID value, String name) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException("Non-nil " + name + " required"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java new file mode 100644 index 0000000000..8f739ea559 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java @@ -0,0 +1,334 @@ +package net.firedevops.firemud.common.gamedesign; + +import java.io.ByteArrayOutputStream; +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.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Closed canonical carrier for complete published realm-policy evidence. */ +public final class RealmPolicyPublishedEvidenceCodec { + public static final String SCHEMA = "game-design-published-realm-policy-carrier/v1"; + + /** + * Bounds this complete framed carrier. Existing constituents retain their own limits, including + * the 4 MiB publication operation and at most 128 policies of at most 4 KiB each; original + * capture and terminal bytes remain opaque and exact. Larger assembled envelopes fail closed. + */ + public static final int MAX_ENVELOPE_BYTES = 32 * 1024 * 1024; + + private static final ObjectMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder(); + private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder(); + + private RealmPolicyPublishedEvidenceCodec() {} + + /** Encodes every field in a closed versioned frame without changing retained evidence bytes. */ + public static byte[] encode(RealmPolicyPublishedEvidence.PublishedSet evidence) { + Objects.requireNonNull(evidence, "evidence"); + long binaryBytes = + (long) evidence.operationBytes().length + + evidence.captureBytes().length + + evidence.terminalEvidenceBytes().length; + if (binaryBytes > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException("Published realm-policy carrier exceeds 32 MiB"); + } + byte[] payload = canonicalPayload(evidence).getBytes(StandardCharsets.UTF_8); + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, SCHEMA); + DraftAuthorizationFenceBinding.frame(out, payload); + byte[] encoded = out.toByteArray(); + if (encoded.length > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException("Published realm-policy carrier exceeds 32 MiB"); + } + return encoded; + } + + /** Decodes only the complete canonical v1 carrier and revalidates the reconstructed record. */ + public static RealmPolicyPublishedEvidence.PublishedSet decode(byte[] encoded) { + if (encoded == null || encoded.length == 0 || encoded.length > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException( + "Complete bounded published realm-policy carrier required"); + } + try { + var reader = new DraftAuthorizationFenceBinding.FrameReader(encoded); + reader.expect(SCHEMA); + byte[] payload = reader.bytes(); + reader.requireEnd(); + String json = strictUtf8(payload); + if (!Arrays.equals(payload, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw new IllegalArgumentException("Noncanonical published realm-policy carrier JSON"); + } + JsonNode root = JSON.readTree(json); + RealmPolicySource.fields( + root, + "schema", + "target", + "versionNumber", + "sourceCommitId", + "sourceEpoch", + "publishedReleaseBundleRef", + "publishedReleaseBundleDigest", + "publishWorkflowId", + "manifestHash", + "publicationVersionStateEpoch", + "operationBytesBase64", + "captureBytesBase64", + "terminalEvidenceBytesBase64", + "policyCount", + "policySetDigest", + "policies"); + if (!SCHEMA.equals(RealmPolicySource.text(root, "schema"))) { + throw new IllegalArgumentException("Unsupported published realm-policy carrier schema"); + } + DraftCommitBinding.TargetProof target = target(root.get("target")); + int versionNumber = positiveInt(root, "versionNumber"); + UUID sourceCommitId = uuid(root, "sourceCommitId"); + String sourceEpoch = RealmPolicySource.text(root, "sourceEpoch"); + if (!sourceEpoch.matches("0|[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical source epoch required"); + } + String publishedReleaseBundleRef = RealmPolicySource.text(root, "publishedReleaseBundleRef"); + String publishedReleaseBundleDigest = + RealmPolicySource.text(root, "publishedReleaseBundleDigest"); + String publishWorkflowId = RealmPolicySource.text(root, "publishWorkflowId"); + String manifestHash = RealmPolicySource.text(root, "manifestHash"); + long publicationVersionStateEpoch = positiveLong(root, "publicationVersionStateEpoch"); + byte[] operationBytes = base64(root, "operationBytesBase64"); + byte[] captureBytes = base64(root, "captureBytesBase64"); + byte[] terminalEvidenceBytes = base64(root, "terminalEvidenceBytesBase64"); + int policyCount = positiveInt(root, "policyCount"); + if (policyCount > RealmPolicySource.MAX_POLICIES) { + throw new IllegalArgumentException("Published policy count exceeds the source limit"); + } + String policySetDigest = RealmPolicySource.text(root, "policySetDigest"); + List policies = policies(root.get("policies")); + var evidence = + new RealmPolicyPublishedEvidence.PublishedSet( + target, + versionNumber, + sourceCommitId, + sourceEpoch, + publishedReleaseBundleRef, + publishedReleaseBundleDigest, + publishWorkflowId, + manifestHash, + publicationVersionStateEpoch, + operationBytes, + captureBytes, + terminalEvidenceBytes, + policyCount, + policySetDigest, + policies); + if (!Arrays.equals(encoded, encode(evidence))) { + throw new IllegalArgumentException("Noncanonical published realm-policy carrier frame"); + } + return evidence; + } catch (IOException malformed) { + throw new IllegalArgumentException("Malformed published realm-policy carrier", malformed); + } catch (RuntimeException malformed) { + if (malformed instanceof IllegalArgumentException invalid) { + throw invalid; + } + throw new IllegalArgumentException("Malformed published realm-policy carrier", malformed); + } + } + + private static String canonicalPayload(RealmPolicyPublishedEvidence.PublishedSet evidence) { + var target = evidence.target(); + var targetJson = + map( + "canonicalTenantId", target.canonicalTenantId().toString(), + "canonicalVersionId", target.canonicalVersionId().toString(), + "gameDesignVersionRowId", Long.toString(target.gameDesignVersionRowId()), + "gameDesignVersionTenantKey", target.gameDesignVersionTenantKey(), + "sourceGameRowId", Long.toString(target.sourceGameRowId()), + "sourceGameTenantKey", target.sourceGameTenantKey(), + "sourceProvenanceKind", target.sourceProvenanceKind()); + var policies = + evidence.policies().stream() + .map( + policy -> + map( + "policyId", policy.policyId().toString(), + "source", + map( + "commitId", policy.source().commitId().toString(), + "revisionId", policy.source().revisionId().toString(), + "logicalRevisionId", policy.source().logicalRevisionId(), + "canonicalPolicyJson", policy.source().policy().canonicalJson()), + "policyDigest", policy.policyDigest())) + .toList(); + return RealmPolicySource.canonical( + map( + "schema", SCHEMA, + "target", targetJson, + "versionNumber", Integer.toString(evidence.versionNumber()), + "sourceCommitId", evidence.sourceCommitId().toString(), + "sourceEpoch", evidence.sourceEpoch(), + "publishedReleaseBundleRef", evidence.publishedReleaseBundleRef(), + "publishedReleaseBundleDigest", evidence.publishedReleaseBundleDigest(), + "publishWorkflowId", evidence.publishWorkflowId(), + "manifestHash", evidence.manifestHash(), + "publicationVersionStateEpoch", Long.toString(evidence.publicationVersionStateEpoch()), + "operationBytesBase64", BASE64_ENCODER.encodeToString(evidence.operationBytes()), + "captureBytesBase64", BASE64_ENCODER.encodeToString(evidence.captureBytes()), + "terminalEvidenceBytesBase64", + BASE64_ENCODER.encodeToString(evidence.terminalEvidenceBytes()), + "policyCount", Integer.toString(evidence.policyCount()), + "policySetDigest", evidence.policySetDigest(), + "policies", policies)); + } + + private static DraftCommitBinding.TargetProof target(JsonNode node) { + RealmPolicySource.fields( + node, + "canonicalTenantId", + "canonicalVersionId", + "gameDesignVersionRowId", + "gameDesignVersionTenantKey", + "sourceGameRowId", + "sourceGameTenantKey", + "sourceProvenanceKind"); + return new DraftCommitBinding.TargetProof( + uuid(node, "canonicalTenantId"), + uuid(node, "canonicalVersionId"), + positiveLong(node, "gameDesignVersionRowId"), + RealmPolicySource.text(node, "gameDesignVersionTenantKey"), + positiveLong(node, "sourceGameRowId"), + RealmPolicySource.text(node, "sourceGameTenantKey"), + RealmPolicySource.text(node, "sourceProvenanceKind")); + } + + private static List policies(JsonNode node) { + if (node == null + || !node.isArray() + || node.size() < 1 + || node.size() > RealmPolicySource.MAX_POLICIES) { + throw new IllegalArgumentException("Complete bounded published policy list required"); + } + var result = new ArrayList(node.size()); + for (JsonNode policyNode : node) { + RealmPolicySource.fields(policyNode, "policyId", "source", "policyDigest"); + JsonNode sourceNode = policyNode.get("source"); + RealmPolicySource.fields( + sourceNode, "commitId", "revisionId", "logicalRevisionId", "canonicalPolicyJson"); + RealmEntryPolicy policy = + RealmEntryPolicy.parseCanonical( + RealmPolicySource.text(sourceNode, "canonicalPolicyJson"), JSON); + result.add( + new RealmPolicyPublishedEvidence.Policy( + uuid(policyNode, "policyId"), + new RealmPolicySource.Policy( + uuid(sourceNode, "commitId"), + uuid(sourceNode, "revisionId"), + RealmPolicySource.text(sourceNode, "logicalRevisionId"), + policy), + RealmPolicySource.text(policyNode, "policyDigest"))); + } + return List.copyOf(result); + } + + private static byte[] base64(JsonNode object, String field) { + String encoded = RealmPolicySource.text(object, field); + final byte[] decoded; + try { + decoded = BASE64_DECODER.decode(encoded); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException("Canonical base64 required: " + field, malformed); + } + if (!BASE64_ENCODER.encodeToString(decoded).equals(encoded)) { + throw new IllegalArgumentException("Canonical base64 required: " + field); + } + return decoded; + } + + private static UUID uuid(JsonNode object, String field) { + String encoded = RealmPolicySource.text(object, field); + try { + UUID parsed = UUID.fromString(encoded); + if (!parsed.toString().equals(encoded) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil UUID required: " + field); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil UUID required: " + field, malformed); + } + } + + private static int positiveInt(JsonNode object, String field) { + String value = RealmPolicySource.text(object, field); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + try { + int parsed = Integer.parseInt(value); + if (parsed <= 0 || !Integer.toString(parsed).equals(value)) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + return parsed; + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Canonical positive counter required: " + field, malformed); + } + } + + private static long positiveLong(JsonNode object, String field) { + String value = RealmPolicySource.text(object, field); + if (!value.matches("[1-9][0-9]*")) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + try { + long parsed = Long.parseLong(value); + if (parsed <= 0 || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException("Canonical positive counter required: " + field); + } + return parsed; + } catch (NumberFormatException malformed) { + throw new IllegalArgumentException( + "Canonical positive counter required: " + field, malformed); + } + } + + private static String strictUtf8(byte[] bytes) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } + + private static Map map(Object... entries) { + if (entries.length % 2 != 0) { + throw new IllegalArgumentException("Even carrier key/value entries required"); + } + var result = new LinkedHashMap(); + for (int i = 0; i < entries.length; i += 2) { + result.put((String) entries[i], entries[i + 1]); + } + return result; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java index 0d20a38e20..ea14c4d6f6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClient.java @@ -78,6 +78,49 @@ public Result read(Request request) { } } + /** + * Exact fixed-capability allocation read; caller supplies the independently verified run leaf. + */ + public CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult readFixture( + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request, + String expectedLeafSha256) { + Objects.requireNonNull(request); + if (!workloadNamespace.equals(request.targetNamespace()) + || expectedLeafSha256 == null + || !expectedLeafSha256.matches("[0-9a-f]{64}")) + throw new IllegalArgumentException("Fixed fixture owner binding required"); + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) { + throw new IllegalStateException("Fixture owner reads require no ambient transaction"); + } + String peer = "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + var response = + requireStub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withCallCredentials( + new GrpcServerPeerIdentityCallCredentials(peer, expectedLeafSha256)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer, expectedLeafSha256)) + .getRunOwnedFixtureLaunchAssociation( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureRequest(request)); + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult result; + try { + result = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Session returned invalid run-owned fixture owner evidence", invalid); + } + if (!expectedLeafSha256.equals( + result.fixturePolicyRequest().capability().gameSessionLeafSha256())) { + throw new IllegalStateException( + "Fixture owner TLS leaf differs from its committed capability"); + } + return result; + } + @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { return endpoints.getGameSessionService(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java index d7476b32f2..7999c433e1 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadEvidence.java @@ -1,10 +1,13 @@ package net.firedevops.firemud.common.gamesession; +import java.util.Arrays; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; /** @@ -19,6 +22,142 @@ public final class CanonicalGameInstanceLaunchAssociationReadEvidence { private CanonicalGameInstanceLaunchAssociationReadEvidence() {} + /** Fixed fixture owner selector: wire construction grants no fixture authority. */ + public record FixtureRequest( + UUID readRequestId, + String targetNamespace, + UUID fixtureOperationId, + String expectedFixturePolicyEvidenceDigest) { + public FixtureRequest { + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(fixtureOperationId, "fixtureOperationId"); + if (readRequestId.equals(fixtureOperationId) + || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Independent fixture owner read identity required"); + } + requireDigest(expectedFixturePolicyEvidenceDigest, "expectedFixturePolicyEvidenceDigest"); + } + } + + /** Exact fixture allocation and immutable owner readback, never a Human release attestation. */ + public record FixtureResult( + FixtureRequest request, + long gameSessionTenantId, + long gameInstanceId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + UUID canonicalVersionId, + UUID canonicalRealmId, + UUID playableStateNamespaceId, + long catalogRevision, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion, + byte[] fixturePolicyRequestBytes, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixturePolicySeal) { + public FixtureResult { + Objects.requireNonNull(request); + Objects.requireNonNull(fixturePolicySeal); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(canonicalVersionId, "canonicalVersionId"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(currentGameInstanceStatus); + if (gameSessionTenantId <= 0 + || gameInstanceId <= 0 + || catalogRevision <= 0 + || currentRowVersion < 0) { + throw new IllegalArgumentException( + "Fixture allocation contains invalid private keys or fences"); + } + fixturePolicyRequestBytes = Objects.requireNonNull(fixturePolicyRequestBytes).clone(); + if (currentGameInstanceStatus != CurrentGameInstanceStatus.STARTING) { + throw new IllegalArgumentException( + "Fixture launch association read requires the current STARTING snapshot"); + } + var decoded = + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes( + fixturePolicyRequestBytes); + var cap = decoded.capability(); + if (!request.targetNamespace().equals(decoded.sourceEvidence().targetNamespace()) + || !request.fixtureOperationId().toString().equals(cap.operationId()) + || !request.fixtureOperationId().equals(fixturePolicySeal.operationId()) + || !request + .expectedFixturePolicyEvidenceDigest() + .equals(fixturePolicySeal.evidenceDigest()) + || !RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA.equals( + fixturePolicySeal.schema()) + || !RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE.equals( + fixturePolicySeal.ownerService()) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + cap, + decoded.creationEvidence(), + decoded.sourceEvidence(), + decoded.launchReadEvidence()) + .equals(fixturePolicySeal.requestDigest()) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + fixturePolicySeal.operationId(), fixturePolicySeal.requestDigest()) + .equals(fixturePolicySeal.evidenceDigest()) + || !canonicalTenantId.equals(decoded.sourceEvidence().canonicalTenantId()) + || !canonicalTenantId + .toString() + .equals(decoded.launchReadEvidence().publishedReleaseBundle().getCanonicalTenantId()) + || !canonicalVersionId + .toString() + .equals( + decoded.launchReadEvidence().publishedReleaseBundle().getCanonicalVersionId())) { + throw new IllegalArgumentException( + "Fixture allocation differs from complete immutable owner provenance"); + } + } + + @Override + public byte[] fixturePolicyRequestBytes() { + return fixturePolicyRequestBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof FixtureResult value)) return false; + return request.equals(value.request) + && gameSessionTenantId == value.gameSessionTenantId + && gameInstanceId == value.gameInstanceId + && canonicalTenantId.equals(value.canonicalTenantId) + && gameInstanceUuid.equals(value.gameInstanceUuid) + && canonicalVersionId.equals(value.canonicalVersionId) + && canonicalRealmId.equals(value.canonicalRealmId) + && playableStateNamespaceId.equals(value.playableStateNamespaceId) + && catalogRevision == value.catalogRevision + && currentGameInstanceStatus == value.currentGameInstanceStatus + && currentRowVersion == value.currentRowVersion + && fixturePolicySeal.equals(value.fixturePolicySeal) + && Arrays.equals(fixturePolicyRequestBytes, value.fixturePolicyRequestBytes); + } + + @Override + public int hashCode() { + return Objects.hash( + request, + gameSessionTenantId, + gameInstanceId, + canonicalTenantId, + gameInstanceUuid, + canonicalVersionId, + canonicalRealmId, + playableStateNamespaceId, + catalogRevision, + currentGameInstanceStatus, + currentRowVersion, + fixturePolicySeal, + Arrays.hashCode(fixturePolicyRequestBytes)); + } + + public RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest fixturePolicyRequest() { + return RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes( + fixturePolicyRequestBytes); + } + } + /** Separate transient read identity and the complete immutable association selector. */ public record Request( UUID readRequestId, diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java index 207371eb3d..0bac03bc3b 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodec.java @@ -17,12 +17,115 @@ import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameInstanceLaunchAssociationResponse; -/** Closed request mapping and strict exact-readback validation for the Game Session owner API. */ +/** + * Closed request/result mapping and strict exact-readback validation for the Game Session owner + * API. + */ public final class CanonicalGameInstanceLaunchAssociationReadGrpcCodec { private static final UUID NIL_UUID = new UUID(0L, 0L); private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} + public static net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest + toFixtureRequest(CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request) { + return net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest + .newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setFixtureOperationId(request.fixtureOperationId().toString()) + .setExpectedFixturePolicyEvidenceDigest(request.expectedFixturePolicyEvidenceDigest()) + .build(); + } + + public static CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest + fromFixtureRequest( + net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest + request) { + requireNoUnknownFields(request, "Fixture launch owner request"); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getFixtureOperationId(), "fixtureOperationId"), + request.getExpectedFixturePolicyEvidenceDigest()); + } + + public static net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse + toFixtureResponse(CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult result) { + var request = result.request(); + var seal = result.fixturePolicySeal(); + return net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse + .newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setFixtureOperationId(request.fixtureOperationId().toString()) + .setExpectedFixturePolicyEvidenceDigest(request.expectedFixturePolicyEvidenceDigest()) + .setGameSessionTenantId(result.gameSessionTenantId()) + .setGameInstanceId(result.gameInstanceId()) + .setCanonicalTenantId(result.canonicalTenantId().toString()) + .setGameInstanceUuid(result.gameInstanceUuid().toString()) + .setCanonicalVersionId(result.canonicalVersionId().toString()) + .setCanonicalRealmId(result.canonicalRealmId().toString()) + .setPlayableStateNamespaceId(result.playableStateNamespaceId().toString()) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setCatalogRevision(result.catalogRevision()) + .setCurrentGameInstanceStatus(result.currentGameInstanceStatus().name()) + .setCurrentRowVersion(result.currentRowVersion()) + .setFixturePolicyRequestBytes( + com.google.protobuf.ByteString.copyFrom(result.fixturePolicyRequestBytes())) + .setFixturePolicySealOperationId(seal.operationId().toString()) + .setFixturePolicySealRequestDigest(seal.requestDigest()) + .setFixturePolicySealEvidenceDigest(seal.evidenceDigest()) + .build(); + } + + public static CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult + fromFixtureResponse( + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest expected, + net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse + response) { + requireNoUnknownFields(response, "Fixture launch owner response"); + var actual = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + parseCanonicalNonNilUuid(response.getReadRequestId(), "readRequestId"), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getFixtureOperationId(), "fixtureOperationId"), + response.getExpectedFixturePolicyEvidenceDigest()); + if (!expected.equals(actual) + || response.getPlayableStateScope() + != net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) { + throw new IllegalArgumentException( + "Fixture launch owner changed the exact read identity or scope"); + } + var seal = + new net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .FixturePolicySeal( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .FIXTURE_POLICY_SEAL_SCHEMA, + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .SOURCE_RECEIPT_OWNER_SERVICE, + parseCanonicalNonNilUuid(response.getFixturePolicySealOperationId(), "sealOperationId"), + response.getFixturePolicySealRequestDigest(), + response.getFixturePolicySealEvidenceDigest()); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + expected, + response.getGameSessionTenantId(), + response.getGameInstanceId(), + parseCanonicalNonNilUuid(response.getCanonicalTenantId(), "canonicalTenantId"), + parseCanonicalNonNilUuid(response.getGameInstanceUuid(), "gameInstanceUuid"), + parseCanonicalNonNilUuid(response.getCanonicalVersionId(), "canonicalVersionId"), + parseCanonicalNonNilUuid(response.getCanonicalRealmId(), "canonicalRealmId"), + parseCanonicalNonNilUuid( + response.getPlayableStateNamespaceId(), "playableStateNamespaceId"), + response.getCatalogRevision(), + CurrentGameInstanceStatus.valueOf(response.getCurrentGameInstanceStatus()), + response.getCurrentRowVersion(), + response.getFixturePolicyRequestBytes().toByteArray(), + seal); + } + public static GetCanonicalGameInstanceLaunchAssociationRequest toRequest(Request request) { Objects.requireNonNull(request, "request"); return GetCanonicalGameInstanceLaunchAssociationRequest.newBuilder() @@ -40,6 +143,73 @@ public static GetCanonicalGameInstanceLaunchAssociationRequest toRequest(Request .build(); } + /** Decodes only the closed exact selector; decoding does not authenticate its caller. */ + public static Request fromRequest(GetCanonicalGameInstanceLaunchAssociationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoUnknownFields(request, "GetCanonicalGameInstanceLaunchAssociation request"); + try { + Request decoded = + new Request( + parseCanonicalNonNilUuid(request.getReadRequestId(), "readRequestId"), + request.getTargetNamespace(), + parseCanonicalNonNilUuid(request.getCanonicalTenantId(), "canonicalTenantId"), + request.getWorldSlug(), + parseCanonicalNonNilUuid(request.getGameInstanceUuid(), "gameInstanceUuid"), + request.getControlPlaneRequestId(), + request.getLaunchDescriptorId(), + request.getExpectedDescriptorRequestDigest(), + request.getExpectedDescriptorResultDigest(), + request.getExpectedReleaseAttestationEvidenceDigest()); + requireIndependentReadIdentity(decoded); + if (!toRequest(decoded).equals(request)) { + throw new IllegalArgumentException("Canonical launch association request is not canonical"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Exact canonical launch association request required", malformed); + } + } + + /** Encodes and revalidates the complete exact association read result. */ + public static GetCanonicalGameInstanceLaunchAssociationResponse toResponse(Result result) { + Objects.requireNonNull(result, "result"); + Request request = result.request(); + CompleteLaunchBindingEvidence binding = result.launchBindingEvidence(); + var completeRequest = completeBindingRequest(request); + var completeResponse = + AuthoredWorldLaunchDescriptorGrpcCodec.toCompleteResponse(completeRequest, binding); + var response = + GetCanonicalGameInstanceLaunchAssociationResponse.newBuilder() + .setReadRequestId(request.readRequestId().toString()) + .setTargetNamespace(request.targetNamespace()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setGameInstanceUuid(request.gameInstanceUuid().toString()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId(request.launchDescriptorId()) + .setDescriptorRequestDigest(request.expectedDescriptorRequestDigest()) + .setDescriptorResultDigest(request.expectedDescriptorResultDigest()) + .setReleaseAttestationEvidenceDigest(request.expectedReleaseAttestationEvidenceDigest()) + .setPlayableStateNamespaceId(result.playableStateNamespaceId().toString()) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setCurrentGameInstanceStatus(result.currentGameInstanceStatus().name()) + .setCurrentRowVersion(result.currentRowVersion()) + .setOwnerAttemptId(result.ownerAttemptId().toString()) + .setOwnerFence(result.ownerFence()) + .setLaunchDescriptor(completeResponse.getLaunchDescriptor()) + .setReleaseAttestation(completeResponse.getReleaseAttestation()) + .setPublicProduction(result.publicProduction()) + .build(); + if (!result.equals(fromResponse(request, response))) { + throw new IllegalArgumentException( + "Canonical launch association result did not survive its closed wire mapping"); + } + return response; + } + /** Validates all ten request echoes and the complete unchanged descriptor/release evidence. */ public static Result fromResponse( Request expectedRequest, GetCanonicalGameInstanceLaunchAssociationResponse response) { @@ -91,15 +261,7 @@ public static Result fromResponse( throw new IllegalArgumentException( "Game Session must return the complete descriptor and release attestation pair"); } - var completeRequest = - GetLaunchDescriptorRequest.newBuilder() - .setRequestId(expectedRequest.readRequestId().toString()) - .setCanonicalTenantId(expectedRequest.canonicalTenantId().toString()) - .setWorldSlug(expectedRequest.worldSlug()) - .setControlPlaneRequestId(expectedRequest.controlPlaneRequestId()) - .setExpectedRequestDigest(expectedRequest.expectedDescriptorRequestDigest()) - .setExpectedResultDigest(expectedRequest.expectedDescriptorResultDigest()) - .build(); + var completeRequest = completeBindingRequest(expectedRequest); var completeResponse = GetCompleteLaunchBindingResponse.newBuilder() .setRequestId(response.getReadRequestId()) @@ -151,6 +313,24 @@ public static Result fromResponse( binding); } + private static GetLaunchDescriptorRequest completeBindingRequest(Request request) { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.readRequestId().toString()) + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setWorldSlug(request.worldSlug()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setExpectedRequestDigest(request.expectedDescriptorRequestDigest()) + .setExpectedResultDigest(request.expectedDescriptorResultDigest()) + .build(); + } + + private static void requireIndependentReadIdentity(Request request) { + if (request.readRequestId().toString().equals(request.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Launch association read identity must remain separate from the original request"); + } + } + private static void requireEcho(String expected, String actual, String field) { if (actual.isEmpty() || !expected.equals(actual)) { throw new IllegalArgumentException( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java index a53c0b5511..dba7eef8a9 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentials.java @@ -9,8 +9,18 @@ /** Authenticates the exact server workload before gRPC releases request headers or body. */ public final class GrpcServerPeerIdentityCallCredentials extends CallCredentials { private final String expectedPeerUri; + private final String expectedLeafSha256; public GrpcServerPeerIdentityCallCredentials(String expectedPeerUri) { + this(expectedPeerUri, null); + } + + /** Pins an actual run-owned leaf in addition to the authenticated workload identity. */ + public GrpcServerPeerIdentityCallCredentials(String expectedPeerUri, String expectedLeafSha256) { + if (expectedLeafSha256 != null && !expectedLeafSha256.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact lowerhex server leaf fingerprint required"); + } + this.expectedLeafSha256 = expectedLeafSha256; this.expectedPeerUri = GrpcPeerIdentity.parseUri(expectedPeerUri) .map(GrpcPeerIdentity::uri) @@ -28,8 +38,12 @@ public void applyRequestMetadata( : requestInfo.getTransportAttrs().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); boolean exactPeer = GrpcPeerIdentity.fromSslSession(sslSession) - .map(peer -> expectedPeerUri.equals(peer.uri())) - .orElse(false); + .map(peer -> expectedPeerUri.equals(peer.uri())) + .orElse(false) + && (expectedLeafSha256 == null + || GrpcPeerCertificateEvidence.fromSslSession(sslSession) + .filter(certificate -> expectedLeafSha256.equals(certificate.leafSha256())) + .isPresent()); if (!exactPeer) { applier.fail( Status.UNAUTHENTICATED.withDescription( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java index cb8925834d..fa607c7c60 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java @@ -14,8 +14,19 @@ /** Rejects response content unless its TLS session proves one exact server workload URI. */ public final class GrpcServerPeerIdentityClientInterceptor implements ClientInterceptor { private final String expectedPeerUri; + private final String expectedLeafSha256; public GrpcServerPeerIdentityClientInterceptor(String expectedPeerUri) { + this(expectedPeerUri, null); + } + + /** Pins an actual run-owned leaf in addition to the authenticated workload identity. */ + public GrpcServerPeerIdentityClientInterceptor( + String expectedPeerUri, String expectedLeafSha256) { + if (expectedLeafSha256 != null && !expectedLeafSha256.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException("Exact lowerhex server leaf fingerprint required"); + } + this.expectedLeafSha256 = expectedLeafSha256; this.expectedPeerUri = GrpcPeerIdentity.parseUri(expectedPeerUri) .map(GrpcPeerIdentity::uri) @@ -45,9 +56,16 @@ private boolean requireVerifiedPeer() { } verified = GrpcPeerIdentity.fromSslSession( - call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) - .filter(peer -> expectedPeerUri.equals(peer.uri())) - .isPresent(); + call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .filter(peer -> expectedPeerUri.equals(peer.uri())) + .isPresent() + && (expectedLeafSha256 == null + || GrpcPeerCertificateEvidence.fromSslSession( + call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .filter( + certificate -> + expectedLeafSha256.equals(certificate.leafSha256())) + .isPresent()); if (!verified) { closed = true; listener.onClose( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java index 87899e9c5f..1a7002584f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java @@ -7,15 +7,20 @@ 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.Base64; import java.util.HashSet; +import java.util.HexFormat; import java.util.Map; import java.util.Set; +import java.util.TreeMap; import java.util.UUID; import java.util.regex.Pattern; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; @@ -54,6 +59,11 @@ public final class RunOwnedInitialAdmissionFixtureWireCodec { public static final String STATE_SCOPE = "SHARED"; public static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + public static final String FIXTURE_POLICY_SEAL_SCHEMA = + "firemud.run-owned-fixture-policy-seal.v1"; + private static final UUID FIXTURE_OPERATION_NAMESPACE = + UUID.fromString("2b7ca687-3637-4dc4-9b12-08ec4c6a9f76"); + private static final int MAX_WIRE_BYTES = 16 * 1024; private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); @@ -79,7 +89,8 @@ public final class RunOwnedInitialAdmissionFixtureWireCodec { "gameSessionUriSan", "caCertificateSha256", "worldManagementUriSan", - "worldManagementLeafSha256"); + "worldManagementLeafSha256", + "claimDigest"); private static final Set SOURCE_RECEIPT_FIELDS = Set.of( "schema", @@ -93,7 +104,23 @@ public final class RunOwnedInitialAdmissionFixtureWireCodec { "worldManagementUriSan", "worldManagementLeafSha256", "sourceEvidence", - "launchReadEvidence"); + "launchReadEvidence", + "creationEvidence", + "fixturePolicySeal"); + private static final Set CREATION_EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final Set FIXTURE_POLICY_SEAL_FIELDS = + Set.of("schema", "ownerService", "operationId", "requestDigest", "evidenceDigest"); private static final Set SOURCE_EVIDENCE_FIELDS = Set.of( "schemaVersion", @@ -157,7 +184,8 @@ public static Capability parseCapability(byte[] capabilityBytes) { requiredText(root, "gameSessionUriSan"), requiredText(root, "caCertificateSha256"), requiredText(root, "worldManagementUriSan"), - requiredText(root, "worldManagementLeafSha256")); + requiredText(root, "worldManagementLeafSha256"), + requiredText(root, "claimDigest")); requireValidCapability(capability); return capability; } @@ -187,6 +215,22 @@ public static SourceReceipt parseSourceReceipt(byte[] receiptBytes, Capability c LaunchReadEvidence launchReadEvidence = parseLaunchReadEvidence(root.get("launchReadEvidence"), capability, sourceEvidence); + FreshTenantCreationEvidence creationEvidence = + parseCreationEvidence(root.get("creationEvidence")); + FixturePolicySeal fixturePolicySeal = parseFixturePolicySeal(root.get("fixturePolicySeal")); + requireFixtureBinding(capability, creationEvidence, sourceEvidence, launchReadEvidence); + String policyRequestDigest = + fixturePolicyRequestDigest( + capability, creationEvidence, sourceEvidence, launchReadEvidence); + if (!FIXTURE_POLICY_SEAL_SCHEMA.equals(fixturePolicySeal.schema()) + || !SOURCE_RECEIPT_OWNER_SERVICE.equals(fixturePolicySeal.ownerService()) + || !UUID.fromString(capability.operationId()).equals(fixturePolicySeal.operationId()) + || !policyRequestDigest.equals(fixturePolicySeal.requestDigest()) + || !fixturePolicyEvidenceDigest(fixturePolicySeal.operationId(), policyRequestDigest) + .equals(fixturePolicySeal.evidenceDigest())) { + throw invalidWireData(); + } + if (!SOURCE_RECEIPT_SCHEMA.equals(schema) || !runId.equals(capability.runId()) || !composeProjectName.equals(capability.composeProjectName()) @@ -217,7 +261,9 @@ public static SourceReceipt parseSourceReceipt(byte[] receiptBytes, Capability c worldManagementUriSan, worldManagementLeafSha256, sourceEvidence, - launchReadEvidence); + launchReadEvidence, + creationEvidence, + fixturePolicySeal); } catch (InvalidProtocolBufferException | RuntimeException exception) { if (exception instanceof InvalidWireDataException invalid) { throw invalid; @@ -226,6 +272,222 @@ public static SourceReceipt parseSourceReceipt(byte[] receiptBytes, Capability c } } + /** Pure existing run-owned UUIDv5 derivation; it grants no authorization. */ + public static UUID fixtureOperationId( + String claimDigest, + String runId, + String projectName, + String gameSessionLeafSha256, + String caCertificateSha256) { + String identity = + String.join( + "\0", + CAPABILITY_SCHEMA, + claimDigest, + runId, + projectName, + gameSessionLeafSha256, + caCertificateSha256); + ByteBuffer namespace = + ByteBuffer.allocate(16) + .putLong(FIXTURE_OPERATION_NAMESPACE.getMostSignificantBits()) + .putLong(FIXTURE_OPERATION_NAMESPACE.getLeastSignificantBits()); + MessageDigest digest = newDigest("SHA-1"); + digest.update(namespace.array()); + byte[] value = digest.digest(identity.getBytes(StandardCharsets.UTF_8)); + value[6] = (byte) ((value[6] & 0x0f) | 0x50); + value[8] = (byte) ((value[8] & 0x3f) | 0x80); + ByteBuffer bytes = ByteBuffer.wrap(value); + return new UUID(bytes.getLong(), bytes.getLong()); + } + + /** Closed ordered length-framed commitment. Parsed/encoded records are never trusted ingress. */ + public static byte[] fixturePolicyRequestBytes( + Capability capability, + FreshTenantCreationEvidence creationEvidence, + AuthoredWorldSourceEvidence sourceEvidence, + LaunchReadEvidence launchReadEvidence) { + requireFixtureBinding(capability, creationEvidence, sourceEvidence, launchReadEvidence); + byte[][] parts = { + canonicalJson(capability), + canonicalJson(creationEvidence), + canonicalJson(sourceEvidence), + launchReadJson(launchReadEvidence) + }; + int size = 0; + for (byte[] part : parts) size = Math.addExact(size, Math.addExact(4, part.length)); + if (size > MAX_WIRE_BYTES) throw invalidWireData(); + ByteBuffer output = ByteBuffer.allocate(size); + for (byte[] part : parts) output.putInt(part.length).put(part); + return output.array(); + } + + public static String fixturePolicyRequestDigest( + Capability capability, + FreshTenantCreationEvidence creationEvidence, + AuthoredWorldSourceEvidence sourceEvidence, + LaunchReadEvidence launchReadEvidence) { + return sha256( + fixturePolicyRequestBytes( + capability, creationEvidence, sourceEvidence, launchReadEvidence)); + } + + public static String fixturePolicyEvidenceDigest(UUID operationId, String requestDigest) { + if (operationId == null + || operationId.equals(new UUID(0L, 0L)) + || requestDigest == null + || !requestDigest.matches("sha256:[0-9a-f]{64}")) throw invalidWireData(); + byte[] schema = FIXTURE_POLICY_SEAL_SCHEMA.getBytes(StandardCharsets.UTF_8); + byte[] operation = operationId.toString().getBytes(StandardCharsets.UTF_8); + byte[] request = requestDigest.getBytes(StandardCharsets.UTF_8); + return sha256( + ByteBuffer.allocate(12 + schema.length + operation.length + request.length) + .putInt(schema.length) + .put(schema) + .putInt(operation.length) + .put(operation) + .putInt(request.length) + .put(request) + .array()); + } + + /** Pure retained request decoding; the owning service must independently verify its authority. */ + public static FixturePolicyRequest parseFixturePolicyRequestBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_WIRE_BYTES) + throw invalidWireData(); + try { + ByteBuffer input = ByteBuffer.wrap(bytes); + byte[][] parts = new byte[4][]; + for (int i = 0; i < parts.length; i++) { + if (input.remaining() < 4) throw invalidWireData(); + int length = input.getInt(); + if (length <= 0 || length > input.remaining()) throw invalidWireData(); + parts[i] = new byte[length]; + input.get(parts[i]); + } + if (input.hasRemaining()) throw invalidWireData(); + Capability capability = parseCapability(parts[0]); + FreshTenantCreationEvidence creation = parseCreationEvidence(parseRoot(parts[1])); + AuthoredWorldSourceEvidence source = parseSourceEvidence(parseRoot(parts[2])); + LaunchReadEvidence launch = parseLaunchReadEvidence(parseRoot(parts[3]), capability, source); + if (!java.util.Arrays.equals( + bytes, fixturePolicyRequestBytes(capability, creation, source, launch))) + throw invalidWireData(); + return new FixturePolicyRequest(capability, creation, source, launch); + } catch (InvalidProtocolBufferException | RuntimeException exception) { + throw invalidWireData(); + } + } + + private static void requireFixtureBinding( + Capability capability, + FreshTenantCreationEvidence creation, + AuthoredWorldSourceEvidence source, + LaunchReadEvidence launch) { + requireValidCapability(capability); + if (creation == null + || source == null + || launch == null + || !SOURCE_TARGET_NAMESPACE.equals(creation.targetNamespace()) + || !creation.targetNamespace().equals(source.targetNamespace()) + || !creation.canonicalTenantId().equals(source.canonicalTenantId()) + || creation.sourceGameRowId() != source.sourceGameRowId() + || !creation.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !creation.provenanceKind().equals(source.provenanceKind()) + || !Long.toString(capability.tenantId()).equals(source.sourceGameTenantKey()) + || !capability.operationId().equals(source.registrationRequestId().toString()) + || !capability.worldSlug().equals(source.worldSlug()) + || !capability.worldDisplayName().equals(source.worldDisplayName()) + || !LAUNCH_READ_EVIDENCE_SCHEMA.equals(launch.schema()) + || capability.gameTemplateId() != launch.gameTemplateId()) throw invalidWireData(); + try { + // Existing full snapshot validation also applies to directly constructed wire records. + parseLaunchReadEvidence(parseRoot(launchReadJson(launch)), capability, source); + } catch (InvalidProtocolBufferException | RuntimeException exception) { + throw invalidWireData(); + } + } + + private static FreshTenantCreationEvidence parseCreationEvidence(JsonNode value) { + if (value == null || !value.isObject() || !hasExactFields(value, CREATION_EVIDENCE_FIELDS)) + throw invalidWireData(); + return new FreshTenantCreationEvidence( + requiredInt(value, "schemaVersion"), + requiredText(value, "targetNamespace"), + requiredUuid(value, "creationRequestId"), + requiredUuid(value, "operationId"), + requiredText(value, "requestDigest"), + requiredUuid(value, "canonicalTenantId"), + requiredPositiveLong(value, "sourceGameRowId"), + requiredText(value, "sourceGameTenantKey"), + requiredText(value, "provenanceKind"), + requiredText(value, "evidenceDigest")); + } + + private static FixturePolicySeal parseFixturePolicySeal(JsonNode value) { + if (value == null || !value.isObject() || !hasExactFields(value, FIXTURE_POLICY_SEAL_FIELDS)) + throw invalidWireData(); + return new FixturePolicySeal( + requiredText(value, "schema"), + requiredText(value, "ownerService"), + requiredUuid(value, "operationId"), + requiredText(value, "requestDigest"), + requiredText(value, "evidenceDigest")); + } + + private static byte[] launchReadJson(LaunchReadEvidence launch) { + Map values = new TreeMap<>(); + values.put("schema", launch.schema()); + values.put("gameTemplateId", launch.gameTemplateId()); + values.put( + "publishedReleaseBundleBase64", + Base64.getEncoder().encodeToString(launch.publishedReleaseBundle().toByteArray())); + values.put( + "versionAssetArtifactStateBase64", + Base64.getEncoder().encodeToString(launch.versionAssetArtifactState().toByteArray())); + values.put( + "versionStateBase64", + Base64.getEncoder().encodeToString(launch.versionState().toByteArray())); + values.put( + "launchDescriptorBase64", + Base64.getEncoder().encodeToString(launch.launchDescriptor().toByteArray())); + return STRICT_JSON_MAPPER.writeValueAsBytes(values); + } + + private static byte[] canonicalJson(Object record) { + JsonNode tree = STRICT_JSON_MAPPER.valueToTree(record); + Map fields = new TreeMap<>(); + tree.properties().forEach(field -> fields.put(field.getKey(), field.getValue())); + return STRICT_JSON_MAPPER.writeValueAsBytes(fields); + } + + private static String sha256(byte[] value) { + return "sha256:" + HexFormat.of().formatHex(newDigest("SHA-256").digest(value)); + } + + private static MessageDigest newDigest(String algorithm) { + try { + return MessageDigest.getInstance(algorithm); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + /** Pure untrusted retained fixture request projection. */ + public record FixturePolicyRequest( + Capability capability, + FreshTenantCreationEvidence creationEvidence, + AuthoredWorldSourceEvidence sourceEvidence, + LaunchReadEvidence launchReadEvidence) {} + + /** Owner seal wire data; only an independent committed owner readback establishes provenance. */ + public record FixturePolicySeal( + String schema, + String ownerService, + UUID operationId, + String requestDigest, + String evidenceDigest) {} + private static LaunchReadEvidence parseLaunchReadEvidence( JsonNode evidence, Capability capability, AuthoredWorldSourceEvidence sourceEvidence) throws InvalidProtocolBufferException { @@ -399,6 +661,16 @@ private static void requireValidCapability(Capability capability) { || !SAFE_ID.matcher(capability.runId()).matches() || !SAFE_ID.matcher(capability.composeProjectName()).matches() || !isCanonicalUuid(capability.operationId()) + || capability.claimDigest() == null + || !SHA_256.matcher(capability.claimDigest()).matches() + || !fixtureOperationId( + capability.claimDigest(), + capability.runId(), + capability.composeProjectName(), + capability.gameSessionLeafSha256(), + capability.caCertificateSha256()) + .toString() + .equals(capability.operationId()) || capability.tenantId() <= 0L || capability.gameTemplateId() <= 0L || capability.ownerAccountId() <= 0L @@ -615,7 +887,8 @@ public record Capability( String gameSessionUriSan, String caCertificateSha256, String worldManagementUriSan, - String worldManagementLeafSha256) {} + String worldManagementLeafSha256, + String claimDigest) {} /** Parsed source-receipt wire data. It is not a verified or trusted service carrier. */ public record SourceReceipt( @@ -630,7 +903,9 @@ public record SourceReceipt( String worldManagementUriSan, String worldManagementLeafSha256, AuthoredWorldSourceEvidence sourceEvidence, - LaunchReadEvidence launchReadEvidence) {} + LaunchReadEvidence launchReadEvidence, + FreshTenantCreationEvidence creationEvidence, + FixturePolicySeal fixturePolicySeal) {} /** Parsed launch projections and the actual immutable owner-issued descriptor message. */ @SuppressFBWarnings( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java index 21c6f4499d..e1c02c892e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java @@ -43,6 +43,12 @@ void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof( var result = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, response); + assertThat(CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toResponse(result)) + .isEqualTo(response); + assertThat( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toRequest(request))) + .isEqualTo(request); assertThat(result.ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); assertThat(result.ownerFence()).isEqualTo(4L); assertThat(result.playableStateScope()).isEqualTo(RealmEntryPolicy.StateScope.SHARED); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java new file mode 100644 index 0000000000..2bb60e0292 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.common.grpc; + +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.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.HexFormat; +import java.util.List; +import javax.net.ssl.SSLSession; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class GrpcServerPeerIdentityCallCredentialsTest { + private static final String EXPECTED_PEER_URI = + "spiffe://firemud/ns/firemud/sa/game-design-service"; + + @Test + void appliesMetadataForTheExactWorkloadAndPresentedLeaf() throws Exception { + RequestFixture fixture = + requestFixture(EXPECTED_PEER_URI, "expected leaf DER".getBytes(StandardCharsets.US_ASCII)); + assertThat(GrpcPeerIdentity.fromSslSession(fixture.sslSession())) + .get() + .extracting(GrpcPeerIdentity::uri, GrpcPeerIdentity::namespace, GrpcPeerIdentity::service) + .containsExactly(EXPECTED_PEER_URI, "firemud", "game-design-service"); + assertThat(GrpcPeerCertificateEvidence.fromSslSession(fixture.sslSession())) + .get() + .extracting(GrpcPeerCertificateEvidence::leafSha256) + .isEqualTo(fixture.leafSha256()); + + CallCredentials.MetadataApplier applier = mock(CallCredentials.MetadataApplier.class); + new GrpcServerPeerIdentityCallCredentials(EXPECTED_PEER_URI, fixture.leafSha256()) + .applyRequestMetadata(fixture.requestInfo(), Runnable::run, applier); + + verify(applier).apply(any(Metadata.class)); + verify(applier, never()).fail(any(Status.class)); + } + + @Test + void sameWorkloadWithDifferentPresentedLeafFailsUnauthenticatedWithoutApplyingMetadata() + throws Exception { + RequestFixture pinnedLeaf = + requestFixture(EXPECTED_PEER_URI, "pinned leaf DER".getBytes(StandardCharsets.US_ASCII)); + RequestFixture presentedLeaf = + requestFixture(EXPECTED_PEER_URI, "different leaf DER".getBytes(StandardCharsets.US_ASCII)); + assertThat(GrpcPeerIdentity.fromSslSession(presentedLeaf.sslSession())) + .get() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(EXPECTED_PEER_URI); + assertThat(GrpcPeerCertificateEvidence.fromSslSession(presentedLeaf.sslSession())) + .get() + .extracting(GrpcPeerCertificateEvidence::leafSha256) + .isNotEqualTo(pinnedLeaf.leafSha256()); + + CallCredentials.MetadataApplier applier = mock(CallCredentials.MetadataApplier.class); + new GrpcServerPeerIdentityCallCredentials(EXPECTED_PEER_URI, pinnedLeaf.leafSha256()) + .applyRequestMetadata(presentedLeaf.requestInfo(), Runnable::run, applier); + + ArgumentCaptor failure = ArgumentCaptor.forClass(Status.class); + verify(applier).fail(failure.capture()); + assertThat(failure.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(applier, never()).apply(any(Metadata.class)); + } + + @Test + void rejectsMalformedLeafFingerprint() { + assertThatThrownBy( + () -> new GrpcServerPeerIdentityCallCredentials(EXPECTED_PEER_URI, "A".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static RequestFixture requestFixture(String peerUri, byte[] leafDer) throws Exception { + X509Certificate certificate = mock(X509Certificate.class); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peerUri))); + when(certificate.getEncoded()).thenReturn(leafDer); + + SSLSession sslSession = mock(SSLSession.class); + when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + CallCredentials.RequestInfo requestInfo = mock(CallCredentials.RequestInfo.class); + when(requestInfo.getTransportAttrs()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build()); + String leafSha256 = + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(leafDer)); + return new RequestFixture(requestInfo, sslSession, leafSha256); + } + + private record RequestFixture( + CallCredentials.RequestInfo requestInfo, SSLSession sslSession, String leafSha256) {} +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java index d9b08d7541..134849527f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java @@ -123,6 +123,33 @@ void configuredIdentityMustBeOneExactCanonicalWorkloadUri() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void runOwnedLeafPinDeniesSameWorkloadWithAnotherCertificateBeforeContent() throws Exception { + var session = session(EXPECTED); + var certificate = (X509Certificate) session.getPeerCertificates()[0]; + byte[] der = "controlled-leaf-der".getBytes(java.nio.charset.StandardCharsets.UTF_8); + when(certificate.getEncoded()).thenReturn(der); + String pin = + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(der)); + Fixture correct = fixture(session, pin); + correct.call.listener.onHeaders(new Metadata()); + correct.call.listener.onMessage("owner evidence"); + assertThat(correct.messages).containsExactly("owner evidence"); + Fixture other = fixture(session, "0".repeat(64)); + other.call.listener.onHeaders(new Metadata()); + other.call.listener.onMessage("untrusted evidence"); + assertThat(other.messages).isEmpty(); + assertThat(other.headers).isEmpty(); + assertThat(other.statuses) + .singleElement() + .extracting(Status::getCode) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(other.call.cancelled).isTrue(); + assertThatThrownBy(() -> new GrpcServerPeerIdentityClientInterceptor(EXPECTED, "wrong")) + .isInstanceOf(IllegalArgumentException.class); + } + private static SSLSession session(String... peerUris) throws Exception { SSLSession session = mock(SSLSession.class); X509Certificate certificate = mock(X509Certificate.class); @@ -136,6 +163,10 @@ private static SSLSession session(String... peerUris) throws Exception { } private static Fixture fixture(SSLSession session) { + return fixture(session, null); + } + + private static Fixture fixture(SSLSession session, String expectedLeafSha256) { var fixture = new Fixture(); fixture.call.attributes = session == null @@ -144,7 +175,7 @@ private static Fixture fixture(SSLSession session) { Channel channel = mock(Channel.class); when(channel.newCall(null, CallOptions.DEFAULT)).thenReturn(fixture.call); ClientCall intercepted = - new GrpcServerPeerIdentityClientInterceptor(EXPECTED) + new GrpcServerPeerIdentityClientInterceptor(EXPECTED, expectedLeafSha256) .interceptCall(null, CallOptions.DEFAULT, channel); intercepted.start( new ClientCall.Listener<>() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java index cc3888461d..86582e03dd 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java @@ -4,15 +4,22 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.protobuf.UnknownFieldSet; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Base64; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.Capability; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.v1.ArtifactState; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; @@ -21,11 +28,16 @@ import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import org.junit.jupiter.api.Test; +import tools.jackson.databind.ObjectMapper; class RunOwnedInitialAdmissionFixtureWireCodecTest { private static final String RUN_ID = "fixture-wire-codec-test"; private static final String PROJECT_NAME = "firemud-fixture-wire-codec-test"; - private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final String CLAIM_DIGEST = "e".repeat(64); + private static final String OPERATION_ID = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, RUN_ID, PROJECT_NAME, "a".repeat(64), "b".repeat(64)) + .toString(); private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; private static final String LEAF_SHA = "a".repeat(64); private static final String WORLD_LEAF_SHA = "c".repeat(64); @@ -61,6 +73,12 @@ void rejectsCapabilityOutsideTheStrictBoundedGrammar() { assertInvalidCapability(valid + " {}\n"); assertInvalidCapability(valid.replace("\"tenantId\":7", "\"tenantId\":\"7\"")); assertInvalidCapability(valid.replace(OPERATION_ID, "not-a-canonical-uuid")); + assertInvalidCapability(valid.replace(LEAF_SHA, "d".repeat(64))); + assertInvalidCapability(valid.replace(CA_SHA, "d".repeat(64))); + assertInvalidCapability( + valid.replace( + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "spiffe://different/game-session")); assertInvalidCapability(valid.replace(WORLD_LEAF_SHA, "D".repeat(64))); assertInvalidCapability(valid.replace("\"visible\":true", "\"visible\":\"true\"")); assertInvalidCapabilityBytes(new byte[] {(byte) 0xc3, (byte) 0x28}); @@ -92,6 +110,16 @@ void rejectsReceiptEnvelopeAndProjectionViolations() { assertInvalidReceipt(valid.replace("\"schema\":", "\"schema\":\"duplicate\",\"schema\":")); assertInvalidReceipt(valid.replace(RUN_ID, "other-run")); assertInvalidReceipt(valid.replace(WORLD_LEAF_SHA, "d".repeat(64))); + assertInvalidReceipt(valid.replace(LEAF_SHA, "d".repeat(64))); + assertInvalidReceipt(valid.replace(CA_SHA, "d".repeat(64))); + assertInvalidReceipt( + valid.replace( + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "spiffe://different/game-session")); + assertInvalidReceipt( + valid.replaceFirst( + "\"canonicalTenantId\":\"" + CANONICAL_TENANT_ID + "\"", + "\"canonicalTenantId\":\"" + UUID.randomUUID() + "\"")); assertInvalidReceipt(valid.replace("\"sourceGameRowId\":13", "\"sourceGameRowId\":\"13\"")); assertInvalidReceipt( valid.replace( @@ -118,29 +146,180 @@ void rejectsRecursiveUnknownProtoFieldsAndDescriptorProjectionMismatches() { launchDescriptor().getAuthoredWorldBinding().toBuilder() .setUnknownFields(UNKNOWN_FIELD_SET)) .build(); + assertInvalidReceipt(receiptWithSubstitutedDescriptor(descriptorWithNestedUnknownFields)); assertInvalidReceipt( - sourceReceiptJson( - sourceEvidence(), + receiptWithSubstitutedDescriptor( + descriptorFor(12L, bundle().getId(), bundle().getPublishedReleaseBundleRef()))); + assertInvalidReceipt( + receiptWithSubstitutedDescriptor( + descriptorFor( + bundle().getVersionId(), bundle().getId(), "different-owner-release-ref"))); + } + + @Test + void rejectsFreshCreationAndSourceEvidenceWithDifferentValidProvenance() { + AuthoredWorldSourceEvidence retainedSourceEvidence = sourceEvidence("RETAINED_GAME_V29"); + LaunchDescriptor retainedSourceDescriptor = + descriptorFor( + retainedSourceEvidence, + bundle().getVersionId(), + bundle().getId(), + bundle().getPublishedReleaseBundleRef()); + LaunchReadEvidence retainedSourceLaunchRead = + new LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, bundle(), artifactState(), versionState(), - descriptorWithNestedUnknownFields)); + retainedSourceDescriptor); + + assertThat(creationEvidence().provenanceKind()).isEqualTo("NEW_GAME_ROW"); + assertThat(retainedSourceEvidence.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability(), + creationEvidence(), + retainedSourceEvidence, + retainedSourceLaunchRead)) + .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); + } + @Test + void retainsExactClaimCreationAndPolicySealAndRejectsReplaySubstitution() { + SourceReceipt receipt = parseSourceReceipt(validSourceReceiptJson(), capability()); + assertThat(receipt.creationEvidence()).isEqualTo(creationEvidence()); + assertThat(receipt.creationEvidence().creationRequestId()) + .isNotEqualTo(sourceEvidence().registrationRequestId()); + byte[] request = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability(), + receipt.creationEvidence(), + receipt.sourceEvidence(), + receipt.launchReadEvidence()); + var decoded = RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(request); + assertThat(decoded.capability()).isEqualTo(capability()); + assertThat(decoded.creationEvidence()).isEqualTo(receipt.creationEvidence()); + assertThat(decoded.sourceEvidence()).isEqualTo(receipt.sourceEvidence()); + assertThat(decoded.launchReadEvidence()).isEqualTo(receipt.launchReadEvidence()); + assertThat(request.length).isLessThan(16 * 1024); + assertInvalidCapability(validCapabilityJson().replace(CLAIM_DIGEST, "f".repeat(64))); + assertInvalidCapability( + validCapabilityJson().replace(OPERATION_ID, UUID.randomUUID().toString())); assertInvalidReceipt( - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorFor(12L, bundle().getId(), bundle().getPublishedReleaseBundleRef()))); + validSourceReceiptJson() + .replace(receipt.fixturePolicySeal().evidenceDigest(), "sha256:" + "0".repeat(64))); assertInvalidReceipt( - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorFor( - bundle().getVersionId(), bundle().getId(), "different-owner-release-ref"))); + validSourceReceiptJson() + .replace( + creationEvidence().creationRequestId().toString(), UUID.randomUUID().toString())); + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes( + Arrays.copyOf(request, request.length + 1))) + .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); + byte[] badLength = request.clone(); + ByteBuffer.wrap(badLength).putInt(Integer.MAX_VALUE); + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(badLength)) + .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); + } + + @Test + void closedFixtureAllocationReadRejectsChangedIdentitySealAndVersion() { + var result = fixtureAllocation(); + var request = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureRequest(result.request()); + assertThat(CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request)) + .isEqualTo(result.request()); + var response = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(result); + assertThat(response.getCurrentGameInstanceStatus()).isEqualTo("STARTING"); + assertThat( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + result.request(), response)) + .isEqualTo(result); + assertThat(result.gameSessionTenantId()).isNotEqualTo(capability().tenantId()); + byte[] bytes = result.fixturePolicyRequestBytes(); + bytes[0] ^= 1; + assertThat(result.fixturePolicyRequestBytes()).isNotEqualTo(bytes); + for (var wrong : + new net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse[] { + response.toBuilder().setCanonicalVersionId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setFixturePolicySealEvidenceDigest("sha256:" + "0".repeat(64)) + .build(), + response.toBuilder() + .setFixturePolicySealRequestDigest("sha256:" + "0".repeat(64)) + .build(), + response.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setFixtureOperationId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setExpectedFixturePolicyEvidenceDigest("sha256:" + "0".repeat(64)) + .build(), + response.toBuilder().clearPlayableStateScope().build(), + response.toBuilder() + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_ISOLATED) + .build(), + response.toBuilder().setPlayableStateScopeValue(999).build(), + response.toBuilder().setGameSessionTenantId(0L).build() + }) { + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + result.request(), wrong)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest( + request.toBuilder().setUnknownFields(UNKNOWN_FIELD_SET).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + result.request(), + response.toBuilder().setUnknownFields(UNKNOWN_FIELD_SET).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + result.request(), + response.toBuilder().setCurrentGameInstanceStatus("RUNNING").build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult + fixtureAllocation() { + var receipt = parseSourceReceipt(validSourceReceiptJson(), capability()); + var request = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + UUID.randomUUID(), + "dev", + UUID.fromString(OPERATION_ID), + receipt.fixturePolicySeal().evidenceDigest()); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + request, + 222L, + 333L, + CANONICAL_TENANT_ID, + UUID.randomUUID(), + UUID.fromString(bundle().getCanonicalVersionId()), + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, + 0L, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability(), + receipt.creationEvidence(), + receipt.sourceEvidence(), + receipt.launchReadEvidence()), + receipt.fixturePolicySeal()); } private static Capability capability() { @@ -178,7 +357,7 @@ private static void assertInvalidReceiptBytes(byte[] bytes) { private static String validCapabilityJson() { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"}\ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ """ .formatted( RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, @@ -189,7 +368,8 @@ private static String validCapabilityJson() { RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, CA_SHA, RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - WORLD_LEAF_SHA); + WORLD_LEAF_SHA, + CLAIM_DIGEST); } private static String validSourceReceiptJson() { @@ -197,47 +377,104 @@ private static String validSourceReceiptJson() { sourceEvidence(), bundle(), artifactState(), versionState(), launchDescriptor()); } + private static String receiptWithSubstitutedDescriptor(LaunchDescriptor descriptor) { + String valid = validSourceReceiptJson(); + String encodedValidDescriptor = encode(launchDescriptor().toByteArray()); + String encodedReplacementDescriptor = encode(descriptor.toByteArray()); + assertThat(valid).contains("\"launchDescriptorBase64\":\"" + encodedValidDescriptor + "\""); + return valid.replace(encodedValidDescriptor, encodedReplacementDescriptor); + } + private static String sourceReceiptJson( AuthoredWorldSourceEvidence source, PublishedReleaseBundle bundle, VersionAssetArtifactState artifactState, VersionStateSnapshot versionState, LaunchDescriptor descriptor) { - return """ + String receipt = + """ {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}}\ """ - .formatted( - RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, - RUN_ID, - PROJECT_NAME, - OPERATION_ID, - RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, - RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - LEAF_SHA, - CA_SHA, - RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - WORLD_LEAF_SHA, - source.schemaVersion(), - source.targetNamespace(), - source.registrationRequestId(), - source.operationId(), - source.requestDigest(), - source.canonicalTenantId(), - source.tenantSlug(), - source.worldSlug(), - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind(), - source.evidenceDigest(), + .formatted( + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + LEAF_SHA, + CA_SHA, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA, + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + encode(bundle.toByteArray()), + encode(artifactState.toByteArray()), + encode(versionState.toByteArray()), + encode(descriptor.toByteArray())); + var launch = + new LaunchReadEvidence( RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, - encode(bundle.toByteArray()), - encode(artifactState.toByteArray()), - encode(versionState.toByteArray()), - encode(descriptor.toByteArray())); + 17L, + bundle, + artifactState, + versionState, + descriptor); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability(), creationEvidence(), source, launch); + var seal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(OPERATION_ID), + requestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(OPERATION_ID), requestDigest)); + ObjectMapper mapper = new ObjectMapper(); + return receipt.substring(0, receipt.length() - 1) + + ",\"creationEvidence\":" + + mapper.writeValueAsString(creationEvidence()) + + ",\"fixturePolicySeal\":" + + mapper.writeValueAsString(seal) + + "}"; + } + + private static FreshTenantCreationEvidence creationEvidence() { + UUID request = UUID.fromString("945cc1d0-1e69-4532-b1c3-7dcde16c9256"); + UUID operation = UUID.fromString("e05352ce-7f61-4436-ac61-508edfe45e8a"); + String digest = "sha256:" + "f".repeat(64); + return new FreshTenantCreationEvidence( + 1, + "dev", + request, + operation, + digest, + CANONICAL_TENANT_ID, + 13L, + "7", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "dev", request, operation, digest, CANONICAL_TENANT_ID, 13L, "7", "NEW_GAME_ROW")); } private static AuthoredWorldSourceEvidence sourceEvidence() { + return sourceEvidence("NEW_GAME_ROW"); + } + + private static AuthoredWorldSourceEvidence sourceEvidence(String provenanceKind) { UUID registrationRequestId = UUID.fromString(OPERATION_ID); UUID operationId = UUID.fromString(SOURCE_OPERATION_ID); String namespace = RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE; @@ -264,7 +501,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { worldDisplayName, 13L, "7", - "NEW_GAME_ROW"); + provenanceKind); return new AuthoredWorldSourceEvidence( 1, namespace, @@ -277,7 +514,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { worldDisplayName, 13L, "7", - "NEW_GAME_ROW", + provenanceKind, evidenceDigest); } @@ -338,7 +575,11 @@ private static LaunchDescriptor launchDescriptor() { } private static LaunchDescriptor descriptorFor(long versionId, long bundleId, String bundleRef) { - AuthoredWorldSourceEvidence source = sourceEvidence(); + return descriptorFor(sourceEvidence(), versionId, bundleId, bundleRef); + } + + private static LaunchDescriptor descriptorFor( + AuthoredWorldSourceEvidence source, long versionId, long bundleId, String bundleRef) { var request = new AuthoredWorldLaunchDescriptorEvidence.Request( RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java index 939a5340bc..988eb4b290 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java @@ -51,6 +51,8 @@ public class RunOwnedFixtureLaunchReadback { private final VersionService versionService; private final VersionAssetArtifactService artifactService; private final LaunchDescriptorService launchDescriptorService; + private final net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository; @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -64,7 +66,9 @@ public RunOwnedFixtureLaunchReadback( GameAuthoredWorldSourceRepository sourceRepository, VersionService versionService, VersionAssetArtifactService artifactService, - LaunchDescriptorService launchDescriptorService) { + LaunchDescriptorService launchDescriptorService, + net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository) { this.gameRepository = gameRepository; this.templateRepository = templateRepository; this.versionRepository = versionRepository; @@ -73,6 +77,7 @@ public RunOwnedFixtureLaunchReadback( this.versionService = versionService; this.artifactService = artifactService; this.launchDescriptorService = launchDescriptorService; + this.creationRepository = creationRepository; } @Transactional(propagation = Propagation.MANDATORY, readOnly = true) @@ -115,6 +120,21 @@ public Snapshot readCommittedOutcome(Snapshot captured) { return readback; } + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence readCommittedCreation( + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence captured) { + var committed = + creationRepository + .read(captured.creationRequestId(), captured.targetNamespace()) + .orElseThrow( + () -> new IllegalStateException("Committed fixture creation receipt unavailable")); + if (!captured.equals(committed)) { + throw new IllegalStateException( + "Committed fixture creation differs from its original operation"); + } + return committed; + } + /** Resolves and independently reads the committed descriptor outside the seeder transaction. */ @Transactional(propagation = Propagation.NOT_SUPPORTED) public ResolvedLaunchDescriptorDto resolveAndReadLaunchDescriptor( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java new file mode 100644 index 0000000000..b3040cc534 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java @@ -0,0 +1,219 @@ +package net.firedevops.firemud.gamedesign.data; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import org.jooq.DSLContext; +import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.ObjectMapper; + +/** Fixed-capability fixture authority only; never emits human selected-publication evidence. */ +@Service +public final class RunOwnedFixturePolicyProducer { + private static final String SCHEMA = + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA; + private static final String OWNER = + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE; + private final DSLContext dsl; + private final RunOwnedFixtureLaunchReadback readback; + private final ObjectMapper json; + private final TransactionTemplate write; + private final TransactionTemplate read; + + RunOwnedFixturePolicyProducer( + DSLContext dsl, + RunOwnedFixtureLaunchReadback readback, + ObjectMapper json, + PlatformTransactionManager transactions) { + this.dsl = dsl; + this.readback = readback; + this.json = json; + write = new TransactionTemplate(transactions); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal sealAndRead( + TestDataSeeder.FixtureCapability trusted, + FreshTenantCreationEvidence creation, + RunOwnedFixtureLaunchReadback.Snapshot snapshot, + ResolvedLaunchDescriptorDto descriptor) { + var capability = trusted.wire(); + var source = snapshot.sourceEvidence(); + if (!creation.canonicalTenantId().equals(source.canonicalTenantId()) + || creation.sourceGameRowId() != source.sourceGameRowId() + || !creation.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !creation.provenanceKind().equals(source.provenanceKind()) + || !creation.targetNamespace().equals(source.targetNamespace()) + || snapshot.gameTemplateId() != trusted.gameTemplateId()) { + throw new IllegalStateException("Fixture creation, source and template bindings differ"); + } + var launch = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + snapshot.gameTemplateId(), + snapshot.bundleProto(), + snapshot.artifactProto(), + snapshot.versionProto(), + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + descriptor.authoredWorldBinding())); + byte[] request = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, creation, source, launch); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launch); + var binding = new LinkedHashMap(); + binding.put("targetNamespace", source.targetNamespace()); + binding.put("fixtureOperationId", trusted.operationId().toString()); + binding.put("creationOperationId", creation.operationId().toString()); + binding.put("creationEvidenceDigest", creation.evidenceDigest()); + binding.put("sourceOperationId", source.operationId().toString()); + binding.put("sourceEvidenceDigest", source.evidenceDigest()); + binding.put("sourceGameRowId", source.sourceGameRowId()); + binding.put("sourceGameTenantKey", source.sourceGameTenantKey()); + binding.put("gameTemplateId", snapshot.gameTemplateId()); + binding.put("versionStateEpoch", snapshot.versionState().versionStateEpoch()); + binding.put("releaseBundleId", snapshot.bundle().id()); + binding.put("publishedReleaseBundleRef", snapshot.bundle().publishedReleaseBundleRef()); + binding.put("artifactRowId", snapshot.artifact().id()); + binding.put("artifactStateEpoch", snapshot.artifact().stateEpoch()); + binding.put("launchDescriptorId", descriptor.launchDescriptorId()); + binding.put("descriptorRequestDigest", descriptor.authoredWorldBinding().requestDigest()); + binding.put("descriptorResultDigest", descriptor.authoredWorldBinding().resultDigest()); + var policy = + Map.ofEntries( + Map.entry("worldSlug", capability.worldSlug()), + Map.entry("worldDisplayName", capability.worldDisplayName()), + Map.entry("realmSlug", capability.realmSlug()), + Map.entry("realmDisplayName", capability.realmDisplayName()), + Map.entry("visible", capability.visible()), + Map.entry("publicProductionRealm", capability.publicProductionRealm()), + Map.entry("requiresCharacterSelection", capability.requiresCharacterSelection()), + Map.entry("stateScope", capability.stateScope()), + Map.entry("characterCreationPolicy", capability.characterCreationPolicy()), + Map.entry("tenantId", capability.tenantId()), + Map.entry("gameTemplateId", capability.gameTemplateId()), + Map.entry("ownerAccountId", capability.ownerAccountId())); + String bindingJson = serialize(binding); + String policyJson = serialize(policy); + write.executeWithoutResult( + ignored -> { + dsl.fetchSingle( + "SELECT id FROM game WHERE id=? AND tenant_id=? FOR UPDATE", + creation.sourceGameRowId(), + creation.sourceGameTenantKey()); + dsl.fetchSingle( + "SELECT id FROM version WHERE id=? AND tenant_id=? FOR UPDATE", + snapshot.version().id(), + creation.sourceGameTenantKey()); + UUID operationId = trusted.operationId(); + String evidenceDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + operationId, requestDigest); + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, sealed, " + + "fixture_operation_id, fixture_request_bytes, fixture_request_digest, fixture_evidence_digest, " + + "fixture_binding_json, fixture_policy_json) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?::jsonb, ?::jsonb) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", + source.canonicalTenantId(), + snapshot.version().canonicalVersionId(), + snapshot.version().id(), + snapshot.version().versionNumber(), + operationId, + request, + requestDigest, + evidenceDigest, + bindingJson, + policyJson); + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson); + }); + var seal = + Objects.requireNonNull( + read.execute( + ignored -> + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson))); + // Independent owner read after seal commit; changing upstream rows cannot publish a receipt. + readback.readCommittedCreation(creation); + var committedSnapshot = readback.readCommittedOutcome(snapshot); + var committedDescriptor = + readback.resolveAndReadLaunchDescriptor(descriptor.authoredWorldBinding().request()); + if (!descriptor.equals(committedDescriptor)) { + throw new IllegalStateException("Fixture descriptor changed after policy seal commit"); + } + readback.requireDescriptorMatchesSnapshot( + committedDescriptor, descriptor.authoredWorldBinding().request(), committedSnapshot); + return seal; + } + + private RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal requireExactRow( + RunOwnedFixtureLaunchReadback.Snapshot snapshot, + byte[] request, + String requestDigest, + String bindingJson, + String policyJson) { + var row = + dsl.fetchOne( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id=? AND canonical_version_id=?", + snapshot.sourceEvidence().canonicalTenantId(), + snapshot.version().canonicalVersionId()); + if (row == null + || !Boolean.TRUE.equals(row.get("sealed", Boolean.class)) + || row.get("fixture_operation_id", UUID.class) == null + || !Arrays.equals(request, row.get("fixture_request_bytes", byte[].class)) + || !requestDigest.equals(row.get("fixture_request_digest", String.class)) + || !sameJson(bindingJson, row.get("fixture_binding_json", String.class)) + || !sameJson(policyJson, row.get("fixture_policy_json", String.class))) { + throw new IllegalStateException( + "Fixture policy seal differs from its exact original evidence"); + } + UUID operation = row.get("fixture_operation_id", UUID.class); + if (!operation + .toString() + .equals( + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(request) + .capability() + .operationId())) { + throw new IllegalStateException("Fixture policy operation differs from its fixed capability"); + } + String digest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + operation, requestDigest); + if (!digest.equals(row.get("fixture_evidence_digest", String.class))) { + throw new IllegalStateException("Fixture policy seal committed readback digest differs"); + } + return new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + SCHEMA, OWNER, operation, requestDigest, digest); + } + + private String serialize(Object value) { + try { + return json.writeValueAsString(value); + } catch (Exception invalid) { + throw new IllegalStateException("Fixture policy serialization failed", invalid); + } + } + + private boolean sameJson(String expected, String actual) { + try { + return actual != null && json.readTree(expected).equals(json.readTree(actual)); + } catch (Exception invalid) { + throw new IllegalStateException("Fixture policy stored evidence invalid", invalid); + } + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index 61011426f6..3df85ac74f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -83,6 +83,9 @@ public class TestDataSeeder implements ApplicationRunner { private final VersionAssetArtifactRepository versionAssetArtifactRepository; private final RunOwnedFixtureLaunchReadback launchReadback; private final ObjectMapper objectMapper; + private final net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository; + private final RunOwnedFixturePolicyProducer fixturePolicyProducer; @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") private boolean initialAdmissionFixtureEnabled; @@ -139,6 +142,17 @@ public void run(ApplicationArguments args) { seedRetainedBaselineRuntime(); return; } + FixtureCapability verifiedCapability = + initialAdmissionFixtureEnabled ? loadFixtureCapability() : null; + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence creation = + verifiedCapability == null + ? null + : creationRepository.createCandidate( + FIXTURE_NAMESPACE, + verifiedCapability.operationId(), + DEMO_TENANT_ID, + "Demo Game", + "Seed game"); Game game = gameRepository.findByTenantId(DEMO_TENANT_ID); if (game == null) { game = new Game(); @@ -243,7 +257,7 @@ public void run(ApplicationArguments args) { } if (initialAdmissionFixtureEnabled) { - registerRunOwnedAuthoredWorldSource(game, template, version); + registerRunOwnedAuthoredWorldSource(game, template, version, verifiedCapability, creation); } } @@ -469,8 +483,11 @@ private boolean matchesDemoReleaseBundle( } private void registerRunOwnedAuthoredWorldSource( - Game game, GameTemplate template, Version version) { - FixtureCapability capability = loadFixtureCapability(); + Game game, + GameTemplate template, + Version version, + FixtureCapability capability, + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence creation) { if (!Objects.equals(template.getId(), capability.gameTemplateId())) { throw new IllegalStateException( "Run-owned fixture capability does not name the persisted default template"); @@ -503,7 +520,7 @@ private void registerRunOwnedAuthoredWorldSource( new TransactionSynchronization() { @Override public void afterCommit() { - publishCommittedSourceReceipt(capability, captured); + publishCommittedSourceReceipt(capability, creation, captured); } }); } @@ -531,7 +548,8 @@ private FixtureCapability loadFixtureCapability() { } if (!fixtureRunId.equals(capability.runId()) || !fixtureComposeProjectName.equals(capability.composeProjectName()) - || capability.tenantId() != 1L) { + || capability.tenantId() != 1L + || capability.ownerAccountId() != 1L) { throw new IllegalStateException( "Run-owned fixture capability does not match the configured Game Design scope"); } @@ -557,11 +575,15 @@ private FixtureCapability loadFixtureCapability() { gameSessionLeafDigest, FIXTURE_WORLD_MANAGEMENT_URI_SAN, worldManagementLeafDigest, - caDigest); + caDigest, + capability); } private void publishCommittedSourceReceipt( - FixtureCapability capability, RunOwnedFixtureLaunchReadback.Snapshot captured) { + FixtureCapability capability, + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence creation, + RunOwnedFixtureLaunchReadback.Snapshot captured) { + var committedCreation = launchReadback.readCommittedCreation(creation); RunOwnedFixtureLaunchReadback.Snapshot verifiedBeforeResolve = launchReadback.readCommittedOutcome(captured); AuthoredWorldSourceEvidence capturedSource = verifiedBeforeResolve.sourceEvidence(); @@ -588,7 +610,16 @@ private void publishCommittedSourceReceipt( launchReadback.readCommittedOutcome(captured); launchReadback.requireDescriptorMatchesSnapshot( resolvedDescriptor, launchRequest, committedAfterResolve); - byte[] receipt = serializeFixtureReceipt(capability, committedAfterResolve, resolvedDescriptor); + var fixturePolicySeal = + fixturePolicyProducer.sealAndRead( + capability, committedCreation, committedAfterResolve, resolvedDescriptor); + byte[] receipt = + serializeFixtureReceipt( + capability, + committedCreation, + fixturePolicySeal, + committedAfterResolve, + resolvedDescriptor); if (receipt.length == 0 || receipt.length > MAX_FIXTURE_FILE_BYTES) { throw new IllegalStateException("Run-owned authored-world receipt exceeds its 16 KiB bound"); } @@ -634,6 +665,8 @@ private void publishCommittedSourceReceipt( private byte[] serializeFixtureReceipt( FixtureCapability capability, + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence creation, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixturePolicySeal, RunOwnedFixtureLaunchReadback.Snapshot snapshot, ResolvedLaunchDescriptorDto launchDescriptor) { AuthoredWorldSourceEvidence source = snapshot.sourceEvidence(); @@ -664,6 +697,8 @@ private byte[] serializeFixtureReceipt( envelope.put("worldManagementLeafSha256", capability.worldManagementLeafSha256()); envelope.put("caCertificateSha256", capability.caCertificateSha256()); envelope.put("sourceEvidence", sourceEvidence); + envelope.put("creationEvidence", creation); + envelope.put("fixturePolicySeal", fixturePolicySeal); Map launchReadEvidence = new LinkedHashMap<>(); launchReadEvidence.put("schema", "firemud.run-owned-v1-launch-read-evidence.v1"); launchReadEvidence.put("gameTemplateId", snapshot.gameTemplateId()); @@ -815,11 +850,59 @@ private boolean validReceiptPath(String value) { && "run-owned-authored-world-source".equals(parentName.toString()); } - private record FixtureCapability( - UUID operationId, - long gameTemplateId, - String gameSessionLeafSha256, - String worldManagementUriSan, - String worldManagementLeafSha256, - String caCertificateSha256) {} + /** Created only after local fixed-capability and mounted TLS validation. */ + static final class FixtureCapability { + private final UUID operationId; + private final long gameTemplateId; + private final String gameSessionLeafSha256; + private final String worldManagementUriSan; + private final String worldManagementLeafSha256; + private final String caCertificateSha256; + private final RunOwnedInitialAdmissionFixtureWireCodec.Capability wire; + + private FixtureCapability( + UUID operationId, + long gameTemplateId, + String gameSessionLeafSha256, + String worldManagementUriSan, + String worldManagementLeafSha256, + String caCertificateSha256, + RunOwnedInitialAdmissionFixtureWireCodec.Capability wire) { + this.operationId = operationId; + this.gameTemplateId = gameTemplateId; + this.gameSessionLeafSha256 = gameSessionLeafSha256; + this.worldManagementUriSan = worldManagementUriSan; + this.worldManagementLeafSha256 = worldManagementLeafSha256; + this.caCertificateSha256 = caCertificateSha256; + this.wire = wire; + } + + UUID operationId() { + return operationId; + } + + long gameTemplateId() { + return gameTemplateId; + } + + String gameSessionLeafSha256() { + return gameSessionLeafSha256; + } + + String worldManagementUriSan() { + return worldManagementUriSan; + } + + String worldManagementLeafSha256() { + return worldManagementLeafSha256; + } + + String caCertificateSha256() { + return caCertificateSha256; + } + + RunOwnedInitialAdmissionFixtureWireCodec.Capability wire() { + return wire; + } + } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java index cbfb3d6b90..2b2c8ac3fa 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationRepository.java @@ -245,6 +245,12 @@ public Optional readPublishedSet(Targ private Optional readPublishedSet( TargetProof target, Record header) { + // Retained pre-fixture schemas have no private discriminator column. Actual fixture + // headers must never be interpreted as Human frozen publication evidence. + if (header.field("fixture_operation_id") != null + && header.get("fixture_operation_id", UUID.class) != null) { + throw new IllegalStateException("FIXTURE_POLICY_IS_NOT_HUMAN_PUBLICATION_EVIDENCE"); + } if (!Boolean.TRUE.equals(header.get("sealed", Boolean.class))) { throw new IllegalStateException("POLICY_PUBLICATION_SET_INCOMPLETE"); } diff --git a/services/game-design-service/src/main/resources/db/migration/V1031__run_owned_fixture_policy_owner_seal.sql b/services/game-design-service/src/main/resources/db/migration/V1031__run_owned_fixture_policy_owner_seal.sql new file mode 100644 index 0000000000..ec48419019 --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1031__run_owned_fixture_policy_owner_seal.sql @@ -0,0 +1,292 @@ +-- Distinct fixed-capability fixture seal in the existing policy owner header. +-- No retained row is rewritten; original selected-publication guards remain unchanged below. +ALTER TABLE game_design_published_realm_policy_set + ADD COLUMN fixture_operation_id UUID UNIQUE, + ADD COLUMN fixture_request_bytes BYTEA, + ADD COLUMN fixture_request_digest VARCHAR(71), + ADD COLUMN fixture_evidence_digest VARCHAR(71), + ADD COLUMN fixture_binding_json JSONB, + ADD COLUMN fixture_policy_json JSONB; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN source_commit_id DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN source_epoch DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN target_proof_json DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN operation_bytes DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN capture_bytes DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN terminal_evidence_bytes DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN release_content_bytes DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN published_release_bundle_ref DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN published_release_bundle_digest DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN publish_workflow_id DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN manifest_hash DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN publication_version_state_epoch DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN policy_count DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ALTER COLUMN policy_set_digest DROP NOT NULL; +ALTER TABLE game_design_published_realm_policy_set + ADD CONSTRAINT ck_realm_policy_owner_evidence_variant CHECK ( + (fixture_operation_id IS NULL AND fixture_request_bytes IS NULL AND fixture_request_digest IS NULL AND fixture_evidence_digest IS NULL AND fixture_binding_json IS NULL AND fixture_policy_json IS NULL + AND source_commit_id IS NOT NULL AND source_epoch IS NOT NULL AND target_proof_json IS NOT NULL AND operation_bytes IS NOT NULL AND capture_bytes IS NOT NULL AND terminal_evidence_bytes IS NOT NULL AND release_content_bytes IS NOT NULL AND published_release_bundle_ref IS NOT NULL AND published_release_bundle_digest IS NOT NULL AND publish_workflow_id IS NOT NULL AND manifest_hash IS NOT NULL AND publication_version_state_epoch IS NOT NULL AND policy_count IS NOT NULL AND policy_set_digest IS NOT NULL) + OR + (fixture_operation_id IS NOT NULL AND fixture_request_bytes IS NOT NULL AND fixture_request_digest IS NOT NULL AND fixture_evidence_digest IS NOT NULL AND fixture_binding_json IS NOT NULL AND fixture_policy_json IS NOT NULL + AND sealed AND source_commit_id IS NULL AND source_epoch IS NULL AND target_proof_json IS NULL AND operation_bytes IS NULL AND capture_bytes IS NULL AND terminal_evidence_bytes IS NULL AND release_content_bytes IS NULL AND published_release_bundle_ref IS NULL AND published_release_bundle_digest IS NULL AND publish_workflow_id IS NULL AND manifest_hash IS NULL AND publication_version_state_epoch IS NULL AND policy_count IS NULL AND policy_set_digest IS NULL)); + +-- Human source_commit_id remains mandatory under the closed variant check above; only +-- verified fixtures have NULL and may omit capture. Retained rows and guards are unchanged. +ALTER TABLE game_design_realm_policy_capture + ADD CONSTRAINT uq_realm_policy_capture_exact_commit + UNIQUE (canonical_tenant_id, canonical_version_id, commit_id); +-- PostgreSQL and H2 name the original implicit FK differently. Both drops stay strict. +-- The H2-only statement uses jOOQ's documented parser comment technique: +-- https://www.jooq.org/doc/latest/manual/sql-building/dsl-context/custom-settings/settings-parser/ +-- CONSTRAINT_145D43CA_10 is the inspected old two-column header-to-capture relationship. +-- Pinning it makes simulator naming changes fail instead of retaining stale generated metadata. +-- [jooq ignore start] +ALTER TABLE game_design_published_realm_policy_set + DROP CONSTRAINT game_design_published_realm__canonical_tenant_id_canonica_fkey1; +-- [jooq ignore stop] +/* [jooq ignore start] */ -- /* [jooq ignore stop] */ ALTER TABLE game_design_published_realm_policy_set DROP CONSTRAINT "CONSTRAINT_145D43CA_10"; +ALTER TABLE game_design_published_realm_policy_set + ADD CONSTRAINT fk_realm_policy_owner_exact_capture + FOREIGN KEY (canonical_tenant_id, canonical_version_id, source_commit_id) + REFERENCES game_design_realm_policy_capture + (canonical_tenant_id, canonical_version_id, commit_id); + +-- [jooq ignore start] +-- Insert only the closed fixture arm into the current owner functions. All existing Human +-- full-Version, capture, source, release/asset and commit guards remain byte-for-byte intact. +DO $migration$ +DECLARE + current_guard TEXT; + declaration_anchor TEXT := $anchor$ row_count BIGINT; realm_count BIGINT; production_count BIGINT; target_proof_key_count BIGINT;$anchor$; + begin_anchor TEXT := $anchor$BEGIN + IF TG_OP = 'DELETE' THEN$anchor$; +BEGIN + SELECT pg_get_functiondef('guard_published_realm_policy_set()'::REGPROCEDURE) INTO STRICT current_guard; + IF (length(current_guard)-length(replace(current_guard,declaration_anchor,'')))/length(declaration_anchor) <> 1 + OR (length(current_guard)-length(replace(current_guard,begin_anchor,'')))/length(begin_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current Human published-policy owner guard anchors'; + END IF; + current_guard := replace(current_guard, declaration_anchor, declaration_anchor || E'\n' + || ' fixture_parts JSONB[]; fixture_offset INTEGER; fixture_length INTEGER; fixture_index INTEGER;'); + current_guard := replace(current_guard, begin_anchor, $replacement$BEGIN + IF TG_OP = 'UPDATE' AND (OLD.fixture_operation_id IS NOT NULL OR NEW.fixture_operation_id IS NOT NULL) THEN + RAISE EXCEPTION 'fixture policy seal is immutable and cannot convert owner variants' USING ERRCODE = 'check_violation'; + END IF; + IF TG_OP = 'INSERT' AND NEW.fixture_operation_id IS NOT NULL THEN + fixture_offset := 0; + FOR fixture_index IN 1..4 LOOP + IF fixture_offset + 4 > octet_length(NEW.fixture_request_bytes) THEN + RAISE EXCEPTION 'fixture policy request framing is incomplete' USING ERRCODE = 'check_violation'; + END IF; + fixture_length := (get_byte(NEW.fixture_request_bytes, fixture_offset) << 24) + + (get_byte(NEW.fixture_request_bytes, fixture_offset + 1) << 16) + + (get_byte(NEW.fixture_request_bytes, fixture_offset + 2) << 8) + + get_byte(NEW.fixture_request_bytes, fixture_offset + 3); + fixture_offset := fixture_offset + 4; + IF fixture_length < 1 OR fixture_offset + fixture_length > octet_length(NEW.fixture_request_bytes) THEN + RAISE EXCEPTION 'fixture policy request frame is invalid' USING ERRCODE = 'check_violation'; + END IF; + fixture_parts[fixture_index] := convert_from(substring(NEW.fixture_request_bytes + FROM fixture_offset + 1 FOR fixture_length), 'UTF8')::JSONB; + IF convert_to('{' || (SELECT string_agg(to_json(key)::TEXT || ':' || value::TEXT, + ',' ORDER BY key COLLATE "C") FROM jsonb_each(fixture_parts[fixture_index])) || '}', 'UTF8') + IS DISTINCT FROM substring(NEW.fixture_request_bytes FROM fixture_offset + 1 FOR fixture_length) THEN + RAISE EXCEPTION 'fixture policy request requires closed canonical JSON without duplicate fields' USING ERRCODE = 'check_violation'; + END IF; + fixture_offset := fixture_offset + fixture_length; + END LOOP; + IF fixture_offset <> octet_length(NEW.fixture_request_bytes) + OR (SELECT count(*) FROM jsonb_object_keys(fixture_parts[1])) <> 22 + OR fixture_parts[1]->>'schema' IS DISTINCT FROM 'firemud.run-owned-initial-admission-fixture.v1' + OR jsonb_typeof(fixture_parts[1]->'runId') IS DISTINCT FROM 'string' + OR fixture_parts[1]->>'runId' !~ '^[a-z0-9][a-z0-9-]{0,127}$' + OR jsonb_typeof(fixture_parts[1]->'composeProjectName') IS DISTINCT FROM 'string' + OR fixture_parts[1]->>'composeProjectName' !~ '^[a-z0-9][a-z0-9-]{0,127}$' + OR jsonb_typeof(fixture_parts[1]->'claimDigest') IS DISTINCT FROM 'string' + OR fixture_parts[1]->>'claimDigest' !~ '^[0-9a-f]{64}$' + OR jsonb_typeof(fixture_parts[1]->'gameSessionLeafSha256') IS DISTINCT FROM 'string' + OR fixture_parts[1]->>'gameSessionLeafSha256' !~ '^[0-9a-f]{64}$' + OR jsonb_typeof(fixture_parts[1]->'worldManagementLeafSha256') IS DISTINCT FROM 'string' + OR fixture_parts[1]->>'worldManagementLeafSha256' !~ '^[0-9a-f]{64}$' + OR jsonb_typeof(fixture_parts[1]->'caCertificateSha256') IS DISTINCT FROM 'string' + OR fixture_parts[1]->>'caCertificateSha256' !~ '^[0-9a-f]{64}$' + OR fixture_parts[1]->>'operationId' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + OR fixture_parts[1]->>'gameSessionUriSan' IS DISTINCT FROM 'spiffe://firemud/ns/dev/sa/game-session-service' + OR fixture_parts[1]->>'worldManagementUriSan' IS DISTINCT FROM 'spiffe://firemud/ns/dev/sa/world-management-service' + OR fixture_parts[1]->>'operationId' IS DISTINCT FROM NEW.fixture_binding_json->>'fixtureOperationId' + OR fixture_parts[1]->>'operationId' IS DISTINCT FROM NEW.fixture_operation_id::TEXT + OR fixture_parts[2]->>'operationId' IS DISTINCT FROM NEW.fixture_binding_json->>'creationOperationId' + OR fixture_parts[2]->>'evidenceDigest' IS DISTINCT FROM NEW.fixture_binding_json->>'creationEvidenceDigest' + OR fixture_parts[2]->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR fixture_parts[3]->>'operationId' IS DISTINCT FROM NEW.fixture_binding_json->>'sourceOperationId' + OR fixture_parts[3]->>'evidenceDigest' IS DISTINCT FROM NEW.fixture_binding_json->>'sourceEvidenceDigest' + OR fixture_parts[3]->>'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR fixture_parts[1]->'gameTemplateId' IS DISTINCT FROM NEW.fixture_policy_json->'gameTemplateId' + OR (fixture_parts[1] - ARRAY['schema', 'runId', 'composeProjectName', 'operationId', 'claimDigest', + 'gameSessionLeafSha256', 'gameSessionUriSan', 'caCertificateSha256', + 'worldManagementUriSan', 'worldManagementLeafSha256']) IS DISTINCT FROM NEW.fixture_policy_json + OR fixture_parts[4]->'gameTemplateId' IS DISTINCT FROM NEW.fixture_policy_json->'gameTemplateId' + OR fixture_parts[4]->>'schema' IS DISTINCT FROM 'firemud.run-owned-v1-launch-read-evidence.v1' + OR (SELECT count(*) FROM jsonb_object_keys(fixture_parts[4])) <> 6 THEN + RAISE EXCEPTION 'fixture policy request differs from its complete immutable projections' USING ERRCODE = 'check_violation'; + END IF; + IF NEW.fixture_operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR octet_length(NEW.fixture_request_bytes) NOT BETWEEN 1 AND 16384 + OR NEW.fixture_request_digest IS DISTINCT FROM 'sha256:' || encode(sha256(NEW.fixture_request_bytes), 'hex') + OR NEW.fixture_evidence_digest IS DISTINCT FROM 'sha256:' || encode(sha256( + int4send(octet_length('firemud.run-owned-fixture-policy-seal.v1')) + || convert_to('firemud.run-owned-fixture-policy-seal.v1', 'UTF8') + || int4send(36) || convert_to(NEW.fixture_operation_id::TEXT, 'UTF8') + || int4send(71) || convert_to(NEW.fixture_request_digest, 'UTF8')), 'hex') + OR jsonb_typeof(NEW.fixture_binding_json) IS DISTINCT FROM 'object' + OR (SELECT count(*) FROM jsonb_object_keys(NEW.fixture_binding_json)) <> 17 + OR NEW.fixture_policy_json IS DISTINCT FROM jsonb_build_object( + 'worldSlug', 'demo', 'worldDisplayName', 'Demo World', 'realmSlug', 'production', + 'realmDisplayName', 'Live Realm', 'visible', TRUE, 'publicProductionRealm', TRUE, + 'requiresCharacterSelection', FALSE, 'stateScope', 'SHARED', 'characterCreationPolicy', 'ALLOW_NEW', + 'tenantId', 1, 'gameTemplateId', (NEW.fixture_binding_json->>'gameTemplateId')::BIGINT, 'ownerAccountId', 1) + OR NOT NEW.sealed THEN + RAISE EXCEPTION 'fixture policy seal requires closed exact fixed-capability evidence' USING ERRCODE = 'check_violation'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM version v + JOIN game g ON g.id=v.identity_source_game_row_id AND g.tenant_id=v.identity_source_game_tenant_key + JOIN game_tenant_creation_operations creation ON creation.source_game_row_id=g.id + JOIN game_design_authored_world_source_operations source ON source.source_game_row_id=g.id + JOIN game_templates template ON template.id=(NEW.fixture_binding_json->>'gameTemplateId')::BIGINT + JOIN published_release_bundle bundle ON bundle.id=(NEW.fixture_binding_json->>'releaseBundleId')::BIGINT + JOIN version_asset_artifact artifact ON artifact.id=(NEW.fixture_binding_json->>'artifactRowId')::BIGINT + JOIN launch_descriptor descriptor ON descriptor.launch_descriptor_id=NEW.fixture_binding_json->>'launchDescriptorId' + WHERE v.id=NEW.game_design_version_row_id AND v.canonical_tenant_id=NEW.canonical_tenant_id + AND v.canonical_version_id=NEW.canonical_version_id AND v.version_number=NEW.version_number + AND v.tenant_id='1' AND g.tenant_id='1' AND g.canonical_tenant_id=NEW.canonical_tenant_id + AND g.tenant_identity_provenance_kind='NEW_GAME_ROW' + AND v.identity_source_provenance_kind='NEW_GAME_ROW' AND v.version_state='PUBLISHED' + AND v.version_state_epoch=(NEW.fixture_binding_json->>'versionStateEpoch')::BIGINT + AND creation.operation_id=(NEW.fixture_binding_json->>'creationOperationId')::UUID + AND creation.creation_request_id=(fixture_parts[2]->>'creationRequestId')::UUID + AND creation.target_namespace=NEW.fixture_binding_json->>'targetNamespace' + AND creation.status='COMPLETED' AND creation.canonical_tenant_id=NEW.canonical_tenant_id + AND creation.source_game_tenant_key='1' AND creation.provenance_kind='NEW_GAME_ROW' + AND creation.evidence_digest=NEW.fixture_binding_json->>'creationEvidenceDigest' + AND fixture_parts[2] = jsonb_build_object('schemaVersion', creation.schema_version, + 'targetNamespace', creation.target_namespace, 'creationRequestId', creation.creation_request_id, + 'operationId', creation.operation_id, 'requestDigest', creation.request_digest, + 'canonicalTenantId', creation.canonical_tenant_id, 'sourceGameRowId', creation.source_game_row_id, + 'sourceGameTenantKey', creation.source_game_tenant_key, 'provenanceKind', creation.provenance_kind, + 'evidenceDigest', creation.evidence_digest) + AND g.id=(NEW.fixture_binding_json->>'sourceGameRowId')::BIGINT + AND NEW.fixture_binding_json->>'sourceGameTenantKey'='1' + AND source.operation_id=(NEW.fixture_binding_json->>'sourceOperationId')::UUID + AND source.registration_request_id=(fixture_parts[1]->>'operationId')::UUID + AND source.target_namespace=creation.target_namespace AND source.target_namespace='dev' + AND source.canonical_tenant_id=NEW.canonical_tenant_id AND source.source_game_tenant_key='1' + AND source.provenance_kind='NEW_GAME_ROW' AND source.world_slug='demo' + AND source.world_display_name='Demo World' + AND source.evidence_digest=NEW.fixture_binding_json->>'sourceEvidenceDigest' + AND fixture_parts[3] = jsonb_build_object('schemaVersion', source.schema_version, + 'targetNamespace', source.target_namespace, 'registrationRequestId', source.registration_request_id, + 'operationId', source.operation_id, 'requestDigest', source.request_digest, + 'canonicalTenantId', source.canonical_tenant_id, 'tenantSlug', source.tenant_slug, + 'worldSlug', source.world_slug, 'worldDisplayName', source.world_display_name, + 'sourceGameRowId', source.source_game_row_id, 'sourceGameTenantKey', source.source_game_tenant_key, + 'provenanceKind', source.provenance_kind, 'evidenceDigest', source.evidence_digest) + AND template.tenant_id='1' AND template.default_version_id=v.id AND template.name='Default Template' + AND bundle.tenant_id='1' AND bundle.version_id=v.id AND bundle.canonical_tenant_id=v.canonical_tenant_id + AND bundle.canonical_version_id=v.canonical_version_id + AND bundle.published_release_bundle_ref=NEW.fixture_binding_json->>'publishedReleaseBundleRef' + AND artifact.tenant_id='1' AND artifact.version_id=v.id AND artifact.artifact_state='PUBLISHED' + AND artifact.state_epoch=(NEW.fixture_binding_json->>'artifactStateEpoch')::BIGINT + AND artifact.manifest_hash=bundle.manifest_hash + AND descriptor.target_namespace=source.target_namespace AND descriptor.canonical_tenant_id=NEW.canonical_tenant_id + AND descriptor.authored_world_source_operation_id=source.operation_id + AND descriptor.authored_world_source_evidence_digest=source.evidence_digest + AND descriptor.outcome_status='SUCCESS' AND descriptor.game_template_id=template.id + AND descriptor.version_id=v.id AND descriptor.version_state_epoch=v.version_state_epoch + AND descriptor.release_bundle_id=bundle.id + AND descriptor.control_plane_request_id=fixture_parts[1]->>'operationId' + AND descriptor.request_digest=NEW.fixture_binding_json->>'descriptorRequestDigest' + AND descriptor.result_digest=NEW.fixture_binding_json->>'descriptorResultDigest' + ) THEN + RAISE EXCEPTION 'fixture policy seal lacks actual creation source and launch owner rows' USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN$replacement$); + EXECUTE current_guard; +END; +$migration$; + +DO $migration$ +DECLARE + current_guard TEXT; + count_anchor TEXT := $anchor$ SELECT count(*), count(DISTINCT realm_slug),$anchor$; +BEGIN + SELECT pg_get_functiondef('verify_published_realm_policy_set_commit()'::REGPROCEDURE) INTO STRICT current_guard; + IF (length(current_guard)-length(replace(current_guard,count_anchor,'')))/length(count_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current Human published-policy commit guard anchor'; + END IF; + current_guard := replace(current_guard, count_anchor, $replacement$ IF set_row.fixture_operation_id IS NOT NULL THEN + IF NOT set_row.sealed OR EXISTS (SELECT 1 FROM game_design_published_realm_policy + WHERE canonical_tenant_id=NEW.canonical_tenant_id AND canonical_version_id=NEW.canonical_version_id) THEN + RAISE EXCEPTION 'fixture policy seal cannot carry human policy children' USING ERRCODE = 'check_violation'; + END IF; + RETURN NULL; + END IF; + SELECT count(*), count(DISTINCT realm_slug),$replacement$); + EXECUTE current_guard; +END; +$migration$; +-- The current inventory-v2 trigger runs before the policy-header guard. Reuse the exact +-- closed fixture arm installed above so both guards validate real fixture owners independently; +-- a fixture never supplies a surrogate Human v2 operation or gains selected inventory authority. +DO $migration$ +DECLARE + header_guard TEXT; + inventory_guard TEXT; + fixture_start TEXT := $anchor$ IF TG_OP = 'UPDATE' AND (OLD.fixture_operation_id IS NOT NULL OR NEW.fixture_operation_id IS NOT NULL) THEN$anchor$; + fixture_end TEXT := $anchor$ IF TG_OP = 'DELETE' THEN$anchor$; + inventory_anchor TEXT := $anchor$BEGIN + IF selected_inventory_operation_nth(NEW.operation_bytes, 0)$anchor$; + fixture_arm TEXT; + start_position INTEGER; + end_position INTEGER; +BEGIN + SELECT pg_get_functiondef('guard_published_realm_policy_set()'::REGPROCEDURE) + INTO STRICT header_guard; + SELECT pg_get_functiondef('guard_published_policy_inventory_v2()'::REGPROCEDURE) + INTO STRICT inventory_guard; + IF (length(header_guard)-length(replace(header_guard,fixture_start,'')))/length(fixture_start) <> 1 + OR (length(header_guard)-length(replace(header_guard,fixture_end,'')))/length(fixture_end) <> 1 + OR (length(inventory_guard)-length(replace(inventory_guard,inventory_anchor,'')))/length(inventory_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact current fixture-header and Human inventory-v2 guard anchors'; + END IF; + start_position := strpos(header_guard, fixture_start); + end_position := strpos(header_guard, fixture_end); + IF end_position <= start_position THEN + RAISE EXCEPTION 'Closed fixture-header guard arm has invalid boundaries'; + END IF; + fixture_arm := substring(header_guard FROM start_position FOR end_position - start_position); + inventory_guard := replace(inventory_guard, inventory_anchor, + $replacement$DECLARE + fixture_parts JSONB[]; fixture_offset INTEGER; fixture_length INTEGER; fixture_index INTEGER; +BEGIN +$replacement$ || fixture_arm || $replacement$ IF selected_inventory_operation_nth(NEW.operation_bytes, 0)$replacement$); + EXECUTE inventory_guard; +END; +$migration$; + +-- [jooq ignore stop] diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index 71db99c203..c4c854fcae 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -35,6 +35,7 @@ import net.firedevops.firemud.gamedesign.dto.VersionAssetArtifactStateDto; import net.firedevops.firemud.gamedesign.dto.VersionStateDto; import net.firedevops.firemud.gamedesign.entity.VersionAssetArtifact; +import net.firedevops.firemud.gamedesign.jooq.tables.GameDesignPublishedRealmPolicySet; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; @@ -136,6 +137,11 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private Flyway flyway; @MockitoSpyBean private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameRepository gameRepository; + + @Autowired + private net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository; + @Autowired private GameTemplateRepository templateRepository; @Autowired private VersionRepository versionRepository; @Autowired private VersionAssetArtifactRepository artifactRepository; @@ -155,10 +161,28 @@ void resetDisposableServiceSchema() { seeder.run(new DefaultApplicationArguments(new String[] {})); } + @Test + void fixtureRefusesExistingUnownedDemoInsteadOfBackfillingCreation(@TempDir Path testDirectory) + throws Exception { + Fixture fixture = prepareFixture(testDirectory); + flyway.clean(); + flyway.migrate(); + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); + seeder.run(new DefaultApplicationArguments(new String[] {})); + var existing = gameRepository.findByTenantId("1"); + configureSeeder(fixture); + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .hasMessageContaining("already belongs to a game row"); + assertThat(gameRepository.findByTenantId("1").getId()).isEqualTo(existing.getId()); + assertThat(creationRepository.read(fixture.operationId(), NAMESPACE)).isEmpty(); + assertThat(fixture.receiptPath()).doesNotExist(); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS)).isZero(); + } + @Test void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( @TempDir Path testDirectory) throws Exception { - Fixture fixture = prepareFixture(testDirectory); + Fixture fixture = prepareFixture(testDirectory, false); configureSeeder(fixture); Path receiptPath = fixture.receiptPath(); @@ -176,10 +200,18 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( .isZero(); assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) .isZero(); + assertThat(gameRepository.findByTenantId("1")).isNull(); + assertThat(creationRepository.read(fixture.operationId(), NAMESPACE)).isEmpty(); assertThat( launchDescriptorRepository.findByPrivateRequest("1", fixture.operationId().toString())) .isEmpty(); + assertThat(dsl.fetchCount(DSL.table(DSL.name("game_design_published_realm_policy_set")))) + .isZero(); + // PostgreSQL sequences advance on rollback; reset this disposable schema so the capability's + // template ID matches the independently fresh committed first-entry attempt. + flyway.clean(); + flyway.migrate(); seeder.run(new DefaultApplicationArguments(new String[] {})); assertThat(receiptPath).isRegularFile(); @@ -191,7 +223,7 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ); JsonNode envelope = objectMapper.readTree(Files.readAllBytes(receiptPath)); - assertThat(envelope.size()).isEqualTo(12); + assertThat(envelope.size()).isEqualTo(14); assertThat(fieldNames(envelope)) .isEqualTo( Set.of( @@ -206,6 +238,8 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( "worldManagementLeafSha256", "caCertificateSha256", "sourceEvidence", + "creationEvidence", + "fixturePolicySeal", "launchReadEvidence")); assertThat(envelope.get("schema").textValue()) .isEqualTo("firemud.run-owned-authored-world-source-receipt.v1"); @@ -224,6 +258,91 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( .isEqualTo(fixture.worldManagementLeafSha256()); assertThat(envelope.get("caCertificateSha256").textValue()) .isEqualTo(fixture.caCertificateSha256()); + var creation = + objectMapper.treeToValue( + envelope.get("creationEvidence"), + net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence.class); + assertThat(creationRepository.read(fixture.operationId(), NAMESPACE)).contains(creation); + assertThat(gameRepository.findByTenantId("1").getCanonicalTenantId()) + .isEqualTo(creation.canonicalTenantId()); + var policySeal = + objectMapper.treeToValue( + envelope.get("fixturePolicySeal"), + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .FixturePolicySeal.class); + var storedPolicy = + dsl.fetchSingle( + "SELECT * FROM game_design_published_realm_policy_set " + "WHERE canonical_tenant_id=?", + creation.canonicalTenantId()); + assertThat(policySeal.operationId()).isEqualTo(fixture.operationId()); + assertThat(storedPolicy.get("fixture_operation_id", UUID.class)) + .isEqualTo(policySeal.operationId()); + assertThat(storedPolicy.get("fixture_request_digest", String.class)) + .isEqualTo(policySeal.requestDigest()); + assertThat(storedPolicy.get("fixture_evidence_digest", String.class)) + .isEqualTo(policySeal.evidenceDigest()); + for (String humanField : + Set.of( + "source_commit_id", + "source_epoch", + "target_proof_json", + "operation_bytes", + "capture_bytes", + "terminal_evidence_bytes", + "release_content_bytes", + "published_release_bundle_ref", + "published_release_bundle_digest", + "publish_workflow_id", + "manifest_hash", + "publication_version_state_epoch", + "policy_count", + "policy_set_digest")) { + assertThat(storedPolicy.get(humanField)).as(humanField).isNull(); + } + for (String humanTable : + Set.of( + "game_design_realm_policy_capture", + "game_design_publication_operation", + "game_design_published_realm_policy")) { + assertThat(dsl.fetchCount(DSL.table(DSL.name(humanTable)))).as(humanTable).isZero(); + } + var versionForPolicy = versionRepository.findByTenantIdAndVersionNumber("1", 1).orElseThrow(); + var fixtureTarget = + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + creation.canonicalTenantId(), + versionForPolicy.getCanonicalVersionId(), + versionForPolicy.getId(), + "1", + creation.sourceGameRowId(), + creation.sourceGameTenantKey(), + creation.provenanceKind()); + assertThatThrownBy( + () -> + new net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository( + dsl) + .readPublishedSet(fixtureTarget)) + .hasMessageContaining("FIXTURE_POLICY_IS_NOT_HUMAN_PUBLICATION_EVIDENCE"); + assertThat( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseFixturePolicyRequestBytes( + storedPolicy.get("fixture_request_bytes", byte[].class)) + .creationEvidence()) + .isEqualTo(creation); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM game_design_published_realm_policy " + + "WHERE canonical_tenant_id=?", + creation.canonicalTenantId()) + .get(0, Long.class)) + .isZero(); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_design_published_realm_policy_set " + + "SET fixture_request_digest=? WHERE canonical_tenant_id=?", + "sha256:" + "f".repeat(64), + creation.canonicalTenantId())) + .hasMessageContaining("fixture policy seal is immutable"); JsonNode sourceJson = envelope.get("sourceEvidence"); assertThat(sourceJson.size()).isEqualTo(13); assertThat(fieldNames(sourceJson)) @@ -543,9 +662,27 @@ void rejectsWrongGameSessionCertificatePinBeforeOwnerRegistration(@TempDir Path Files.setPosixFilePermissions( fixture.capabilityPath(), Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); - Files.writeString( - fixture.capabilityPath(), - capability.replace(fixture.gameSessionLeafSha256(), wrongLeafDigest)); + var changedCapability = + (tools.jackson.databind.node.ObjectNode) objectMapper.readTree(capability); + changedCapability.put("gameSessionLeafSha256", wrongLeafDigest); + UUID changedOperationId = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .fixtureOperationId( + changedCapability.get("claimDigest").textValue(), + changedCapability.get("runId").textValue(), + changedCapability.get("composeProjectName").textValue(), + wrongLeafDigest, + changedCapability.get("caCertificateSha256").textValue()); + changedCapability.put("operationId", changedOperationId.toString()); + byte[] changedCapabilityBytes = objectMapper.writeValueAsBytes(changedCapability); + // The fixed operation is derived from the GS leaf pin. Keep this wire input valid so + // the negative reaches the actual configured certificate comparison, before any owner write. + assertThat( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseCapability(changedCapabilityBytes) + .operationId()) + .isEqualTo(changedOperationId.toString()); + Files.write(fixture.capabilityPath(), changedCapabilityBytes); Files.setPosixFilePermissions( fixture.capabilityPath(), Set.of( @@ -558,6 +695,10 @@ void rejectsWrongGameSessionCertificatePinBeforeOwnerRegistration(@TempDir Path .isInstanceOf(IllegalStateException.class) .hasMessageContaining("TLS certificates do not match capability pins"); assertThat(fixture.receiptPath()).doesNotExist(); + assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(changedOperationId))) + .isZero(); + assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(changedOperationId))) + .isZero(); assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) .isZero(); assertThat(dsl.fetchCount(SOURCE_DELIVERIES, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) @@ -688,6 +829,11 @@ private void writeVersionStateEpoch( } private Fixture prepareFixture(Path testDirectory) throws Exception { + return prepareFixture(testDirectory, true); + } + + private Fixture prepareFixture(Path testDirectory, boolean prepareExistingOwner) + throws Exception { Path certificateDirectory = Files.createDirectory(testDirectory.resolve("certificates")); Path caKey = certificateDirectory.resolve("ca.key"); Path caCertificate = certificateDirectory.resolve("ca.crt"); @@ -824,14 +970,18 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { String leafDigest = certificateDigest(sessionCertificate); String worldManagementLeafDigest = certificateDigest(worldManagementCertificate); String caDigest = certificateDigest(caCertificate); - UUID operationId = UUID.randomUUID(); String runId = "fixture-commit-proof"; String composeProjectName = "firemud-smoke-fixture-commit-proof"; + String claimDigest = "e".repeat(64); + UUID operationId = + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .fixtureOperationId(claimDigest, runId, composeProjectName, leafDigest, caDigest); Path capabilityPath = testDirectory.resolve("run-owned-initial-admission-capability.json"); Map capability = new LinkedHashMap<>(); capability.put("schema", "firemud.run-owned-initial-admission-fixture.v1"); capability.put("runId", runId); capability.put("composeProjectName", composeProjectName); + capability.put("claimDigest", claimDigest); capability.put("operationId", operationId.toString()); capability.put("tenantId", 1); capability.put( @@ -876,18 +1026,34 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE, PosixFilePermission.OTHERS_EXECUTE)); - return new Fixture( - operationId, - runId, - composeProjectName, - capabilityPath, - receiptDirectory.resolve("source-receipt.json"), - sessionCertificate, - worldManagementCertificate, - caCertificate, - leafDigest, - worldManagementLeafDigest, - caDigest); + Fixture fixture = + new Fixture( + operationId, + runId, + composeProjectName, + capabilityPath, + receiptDirectory.resolve("source-receipt.json"), + sessionCertificate, + worldManagementCertificate, + caCertificate, + leafDigest, + worldManagementLeafDigest, + caDigest); + configureSeeder(fixture); + ReflectionTestUtils.invokeMethod(seeder, "loadFixtureCapability"); + // Disposable test schema only: create the real fixture owner from inception, never backfill. + flyway.clean(); + flyway.migrate(); + if (prepareExistingOwner) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> + creationRepository.createCandidate( + NAMESPACE, operationId, "1", "Demo Game", "Seed game")); + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); + seeder.run(new DefaultApplicationArguments(new String[] {})); + } + return fixture; } private void configureSeeder(Fixture fixture) { @@ -1217,6 +1383,68 @@ private void assertRetainedDescriptorInsertAndRead( .hasMessage("Launch descriptors are immutable"); } + @Test + void policyOwnerRetainsValidatedExactHumanCaptureForeignKey() { + var generatedCaptureReferences = + GameDesignPublishedRealmPolicySet.GAME_DESIGN_PUBLISHED_REALM_POLICY_SET + .getReferences() + .stream() + .filter( + reference -> + reference + .getKey() + .getTable() + .getName() + .equals("game_design_realm_policy_capture")) + .toList(); + assertThat(generatedCaptureReferences).hasSize(1); + var generatedCaptureReference = generatedCaptureReferences.getFirst(); + assertThat(generatedCaptureReference.getName()) + .isEqualTo("fk_realm_policy_owner_exact_capture"); + assertThat( + generatedCaptureReference.getFields().stream().map(field -> field.getName()).toList()) + .containsExactly("canonical_tenant_id", "canonical_version_id", "source_commit_id"); + assertThat( + generatedCaptureReference.getKey().getFields().stream() + .map(field -> field.getName()) + .toList()) + .containsExactly("canonical_tenant_id", "canonical_version_id", "commit_id"); + var captureForeignKey = + dsl.fetchSingle( + "SELECT constraint_row.convalidated, constraint_row.confmatchtype::text AS match_type, " + + "constraint_row.confupdtype::text AS update_action, " + + "constraint_row.confdeltype::text AS delete_action, " + + "constraint_row.confrelid = 'game_design_realm_policy_capture'::regclass AS exact_target, " + + "ARRAY(SELECT attribute.attname::text " + + "FROM unnest(constraint_row.conkey) WITH ORDINALITY AS key(attnum, ordinal) " + + "JOIN pg_attribute attribute ON attribute.attrelid = constraint_row.conrelid " + + "AND attribute.attnum = key.attnum ORDER BY key.ordinal) AS owner_columns, " + + "ARRAY(SELECT attribute.attname::text " + + "FROM unnest(constraint_row.confkey) WITH ORDINALITY AS key(attnum, ordinal) " + + "JOIN pg_attribute attribute ON attribute.attrelid = constraint_row.confrelid " + + "AND attribute.attnum = key.attnum ORDER BY key.ordinal) AS capture_columns " + + "FROM pg_constraint constraint_row " + + "WHERE constraint_row.conrelid = 'game_design_published_realm_policy_set'::regclass " + + "AND constraint_row.contype = 'f' " + + "AND constraint_row.conname = 'fk_realm_policy_owner_exact_capture'"); + assertThat(captureForeignKey.get("convalidated", Boolean.class)).isTrue(); + assertThat(captureForeignKey.get("exact_target", Boolean.class)).isTrue(); + assertThat(captureForeignKey.get("match_type", String.class)).isEqualTo("s"); + assertThat(captureForeignKey.get("update_action", String.class)).isEqualTo("a"); + assertThat(captureForeignKey.get("delete_action", String.class)).isEqualTo("a"); + assertThat(captureForeignKey.get("owner_columns", String[].class)) + .containsExactly("canonical_tenant_id", "canonical_version_id", "source_commit_id"); + assertThat(captureForeignKey.get("capture_columns", String[].class)) + .containsExactly("canonical_tenant_id", "canonical_version_id", "commit_id"); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM pg_constraint " + + "WHERE conrelid = 'game_design_published_realm_policy_set'::regclass " + + "AND conname = 'game_design_published_realm__canonical_tenant_id_canonica_fkey1'") + .get(0, Long.class)) + .isZero(); + } + private FoundationFixture foundationFixture(String target) { String schema = "foundation_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = @@ -1280,7 +1508,11 @@ void seed() { new VersionAssetArtifactRepository(dsl), org.mockito.Mockito.mock( net.firedevops.firemud.gamedesign.data.RunOwnedFixtureLaunchReadback.class), - new ObjectMapper()); + new ObjectMapper(), + org.mockito.Mockito.mock( + net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.gamedesign.data.RunOwnedFixturePolicyProducer.class)); transactions.executeWithoutResult( status -> seeder.run(new DefaultApplicationArguments(new String[] {}))); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index 1c8c002f4a..22e514dc6b 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; @@ -88,6 +89,55 @@ class RealmPolicyPublicationPostgresIntegrationTest { static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Test + void fixtureOwnerMigrationPreservesGenuineHumanPolicyRowsAndExactRetry() throws Exception { + // Account and remote-owner authority remain the existing ISOLATED test inputs; capture, + // publication, header and policy children are produced by the actual Game Design owners. + Fixture fixture = fixture(true, "1026"); + GameDesignPublicationOperation operation = fixture.prepare(true); + fixture.writePublish(operation, false); + var original = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + var originalRows = retainedPolicyOwnerRows(fixture); + originalRows.forEach((table, rows) -> assertThat(rows).as(table).hasSize(1)); + + var source = + (DriverManagerDataSource) + java.util.Objects.requireNonNull( + fixture.transactions().getDataSource(), "fixture transaction data source"); + migrate(source, source.getSchema(), "1031"); + + assertThat(retainedPolicyOwnerRows(fixture)).isEqualTo(originalRows); + var retained = fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow(); + assertPublishedSetUnchanged(original, retained); + var retainedHeader = + fixture + .dsl() + .fetchSingle( + "SELECT * FROM game_design_published_realm_policy_set " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + for (String fixtureField : + List.of( + "fixture_operation_id", + "fixture_request_bytes", + "fixture_request_digest", + "fixture_evidence_digest", + "fixture_binding_json", + "fixture_policy_json")) { + assertThat(retainedHeader.get(fixtureField)).as(fixtureField).isNull(); + } + var retry = + fixture.tx( + () -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); + assertPublishedSetUnchanged(original, retry); + assertThat(retainedPolicyOwnerRows(fixture)).isEqualTo(originalRows); + } + @Test void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exception { Fixture fixture = fixture(true); @@ -425,12 +475,17 @@ void missingPolicyCaptureFailsClosedForEveryFullVersionRelease() throws Exceptio } private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception { + return fixture(isolatedPolicyBaseline, null); + } + + private static Fixture fixture(boolean isolatedPolicyBaseline, String migrationTarget) + throws Exception { String schema = "gd_realm_policy_pub_" + UUID.randomUUID().toString().replace("-", ""); var source = new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); source.setSchema(schema); - migrate(source, schema); + migrate(source, schema, migrationTarget); var transactions = new DataSourceTransactionManager(source); var write = new TransactionTemplate(transactions); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); @@ -487,16 +542,45 @@ private static Fixture fixture(boolean isolatedPolicyBaseline) throws Exception publicationReads); } - private static void migrate(DriverManagerDataSource source, String schema) { - Flyway.configure() - .dataSource(source) - .schemas(schema) - .defaultSchema(schema) - .placeholders(Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .table("flyway_schema_history_game_design_service") - .load() - .migrate(); + private static void migrate( + DriverManagerDataSource source, String schema, String migrationTarget) { + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .table("flyway_schema_history_game_design_service"); + if (migrationTarget != null) configuration.target(migrationTarget); + configuration.load().migrate(); + } + + private static Map> retainedPolicyOwnerRows(Fixture fixture) { + Map> rows = new LinkedHashMap<>(); + for (String table : + List.of( + "game_design_published_realm_policy_set", + "game_design_realm_policy_capture", + "game_design_published_realm_policy")) { + rows.put( + table, + fixture + .dsl() + .fetch( + "SELECT jsonb_build_object('row', to_jsonb(owner) - " + + "ARRAY['fixture_operation_id', 'fixture_request_bytes', 'fixture_request_digest', " + + "'fixture_evidence_digest', 'fixture_binding_json', 'fixture_policy_json'], " + + "'xmin', owner.xmin::text, 'ctid', owner.ctid::text)::text AS retained_row " + + "FROM " + + table + + " owner WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "ORDER BY owner.ctid", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()) + .getValues("retained_row", String.class)); + } + return rows; } private static DraftCommitBinding baseline( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index 97132ac70b..b2da73bad2 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -11,14 +11,18 @@ import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.MessageDigest; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.HexFormat; import java.util.List; import java.util.Optional; +import java.util.Set; import java.util.UUID; import javax.security.auth.x500.X500Principal; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; @@ -35,6 +39,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -55,6 +60,11 @@ class TestDataSeederTest { @Mock VersionAssetArtifactRepository versionAssetArtifactRepository; @Mock RunOwnedFixtureLaunchReadback launchReadback; + @Mock + net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository creationRepository; + + @Mock RunOwnedFixturePolicyProducer fixturePolicyProducer; + private TestDataSeeder seeder; @BeforeEach @@ -70,7 +80,9 @@ void setup() { publishedReleaseBundleRepository, versionAssetArtifactRepository, launchReadback, - new ObjectMapper()); + new ObjectMapper(), + creationRepository, + fixturePolicyProducer); } @Test @@ -288,6 +300,75 @@ void retainedBaselineRejectsMismatchedExistingArtifactWithoutSavingIt() { verify(versionAssetArtifactRepository, never()).save(any(VersionAssetArtifact.class)); } + @Test + void independentlyReadsExactCommittedCreationAndRejectsChangedOrMissingOwnerEvidence() { + var creationRepository = + org.mockito.Mockito.mock( + net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository.class); + var readback = + new RunOwnedFixtureLaunchReadback( + gameRepository, + templateRepository, + versionRepository, + versionAssetArtifactRepository, + authoredWorldSourceRepository, + org.mockito.Mockito.mock( + net.firedevops.firemud.gamedesign.service.VersionService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService.class), + org.mockito.Mockito.mock( + net.firedevops.firemud.gamedesign.service.LaunchDescriptorService.class), + creationRepository); + var requestId = java.util.UUID.randomUUID(); + var operationId = java.util.UUID.randomUUID(); + var tenantId = java.util.UUID.randomUUID(); + String requestDigest = + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.requestDigest( + "dev", requestId, "1", "Demo Game", "Seed game"); + var captured = + new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "dev", + requestId, + operationId, + requestDigest, + tenantId, + 17L, + "1", + "NEW_GAME_ROW", + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.evidenceDigest( + "dev", requestId, operationId, requestDigest, tenantId, 17L, "1", "NEW_GAME_ROW")); + when(creationRepository.read(requestId, "dev")).thenReturn(java.util.Optional.of(captured)); + assertThat(readback.readCommittedCreation(captured)).isEqualTo(captured); + + var changed = + new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "dev", + requestId, + operationId, + requestDigest, + tenantId, + 18L, + "1", + "NEW_GAME_ROW", + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.evidenceDigest( + "dev", requestId, operationId, requestDigest, tenantId, 18L, "1", "NEW_GAME_ROW")); + when(creationRepository.read(requestId, "dev")).thenReturn(java.util.Optional.of(changed)); + assertThatThrownBy(() -> readback.readCommittedCreation(captured)) + .hasMessageContaining("differs from its original operation"); + when(creationRepository.read(requestId, "dev")).thenReturn(java.util.Optional.empty()); + assertThatThrownBy(() -> readback.readCommittedCreation(captured)) + .hasMessageContaining("creation receipt unavailable"); + verify(creationRepository, org.mockito.Mockito.times(3)).read(requestId, "dev"); + org.mockito.Mockito.verifyNoInteractions( + gameRepository, + templateRepository, + versionRepository, + versionAssetArtifactRepository, + authoredWorldSourceRepository); + } + @Test void acceptsExpectedWorkloadUriAlongsideGeneratedDnsSans() throws Exception { CertificateFixture gameSession = @@ -419,6 +500,76 @@ void refusesFixtureSourceRegistrationWithoutExactRunAndProjectBinding() throws E .register(any(), any(), any(), any(), any(), any()); } + @Test + void rejectsWrongOwnerAccountBeforeAnySeederOwnerWrites(@TempDir Path directory) + throws Exception { + String runId = "compose-smoke-owner-3206"; + String projectName = "firemud-smoke-compose-smoke-owner-3206"; + String claimDigest = "d".repeat(64); + String gameSessionLeafDigest = "a".repeat(64); + String caDigest = "b".repeat(64); + String worldManagementLeafDigest = "c".repeat(64); + String operationId = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + claimDigest, runId, projectName, gameSessionLeafDigest, caDigest) + .toString(); + Path capabilityPath = directory.resolve("run-owned-initial-admission-capability.json"); + String capabilityJson = + """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":1,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}%n\ + """ + .formatted( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + runId, + projectName, + operationId, + gameSessionLeafDigest, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + caDigest, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + worldManagementLeafDigest, + claimDigest); + Files.writeString(capabilityPath, capabilityJson); + Files.setPosixFilePermissions( + capabilityPath, Set.of(java.nio.file.attribute.PosixFilePermission.OWNER_READ)); + + ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", true); + ReflectionTestUtils.setField(seeder, "fixtureRunId", runId); + ReflectionTestUtils.setField(seeder, "fixtureComposeProjectName", projectName); + ReflectionTestUtils.setField(seeder, "fixtureCapabilityPath", capabilityPath.toString()); + ReflectionTestUtils.setField( + seeder, + "fixtureReceiptPath", + directory + .resolve("run-owned-authored-world-source") + .resolve("source-receipt.json") + .toString()); + ReflectionTestUtils.setField( + seeder, "gameSessionLeafCertPath", directory.resolve("game-session.crt").toString()); + ReflectionTestUtils.setField( + seeder, + "worldManagementLeafCertPath", + directory.resolve("world-management.crt").toString()); + ReflectionTestUtils.setField(seeder, "caCertPath", directory.resolve("ca.crt").toString()); + ReflectionTestUtils.setField(seeder, "workloadNamespace", "dev"); + + assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("does not match the configured Game Design scope"); + + verifyNoInteractions( + creationRepository, + fixturePolicyProducer, + gameRepository, + authoredWorldSourceRepository, + templateRepository, + revisionRepository, + versionRepository, + publishedReleaseBundleRepository, + versionAssetArtifactRepository, + launchReadback); + } + private PublishedReleaseBundle stubExistingSeedData() { UUID canonicalTenantId = UUID.fromString("00000000-0000-0000-0000-000000000001"); UUID canonicalVersionId = UUID.fromString("00000000-0000-0000-0000-000000000007"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java new file mode 100644 index 0000000000..8210a9ee2f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java @@ -0,0 +1,200 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.ClientInterceptors; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.FileBackedGrpcMtlsPolicy; +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.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Session workload client for exact Game Design fresh-creation readback. */ +public final class GameDesignFreshTenantCreationClient + extends AbstractReloadingBlockingGrpcClient< + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String workloadNamespace; + private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + private volatile boolean initialized; + private volatile boolean closed; + + public GameDesignFreshTenantCreationClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProperties), + channelFactory, + GameDesignFreshTenantCreationClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.serverPeerIdentityInterceptor = + new GrpcServerPeerIdentityClientInterceptor(gameDesignServerPeerUri(workloadNamespace)); + } + + /** Initializes this client only when the owning Game Session composition explicitly uses it. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Game Design fresh-tenant client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException("Game Design fresh-tenant client has no gRPC stub"); + } + initialized = true; + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub buildStub( + ManagedChannel channel) { + String expectedPeerUri = gameDesignServerPeerUri(workloadNamespace); + return TenantIdentityServiceGrpc.newBlockingStub( + ClientInterceptors.intercept(channel, serverPeerIdentityInterceptor)) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withCompression("gzip"); + } + + @Override + public void close() throws IOException { + synchronized (this) { + closed = true; + initialized = false; + } + super.close(); + } + + private TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub requireStub() { + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Game Design fresh-tenant client is not initialized and available"); + } + return currentStub; + } + + /** + * Reads one immutable receipt from Game Design without opening or joining a Game Session SQL + * transaction. Game Design independently admits only the same-namespace Game Session mTLS peer. + */ + public FreshTenantCreationEvidence resolveCreation( + UUID creationRequestId, String expectedRequestDigest) { + var currentStub = requireStub(); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Design fresh-tenant evidence must be resolved outside a Game Session transaction"); + } + if (creationRequestId == null || NIL_UUID.equals(creationRequestId)) { + throw new IllegalArgumentException("Canonical nonnil creation request ID is required"); + } + if (!GameTenantCreationDigest.isDigest(expectedRequestDigest)) { + throw new IllegalArgumentException("Canonical expected request digest is required"); + } + + ResolveFreshTenantCreationResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(creationRequestId.toString()) + .setExpectedRequestDigest(expectedRequestDigest) + .build()); + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidOwnerEvidence("Game Design fresh tenant evidence contains unknown fields"); + } + + FreshTenantCreationEvidence evidence; + try { + evidence = + new FreshTenantCreationEvidence( + response.getSchemaVersion(), + response.getTargetNamespace(), + parseCanonicalNonNilUuid(response.getCreationRequestId()), + parseCanonicalNonNilUuid(response.getOperationId()), + response.getRequestDigest(), + parseCanonicalNonNilUuid(response.getCanonicalTenantId()), + response.getSourceGameRowId(), + response.getSourceGameTenantKey(), + response.getProvenanceKind(), + response.getEvidenceDigest()); + } catch (IllegalArgumentException exception) { + throw invalidOwnerEvidence("Game Design fresh tenant evidence is invalid", exception); + } + + if (!workloadNamespace.equals(evidence.targetNamespace()) + || !creationRequestId.equals(evidence.creationRequestId()) + || !expectedRequestDigest.equals(evidence.requestDigest())) { + throw invalidOwnerEvidence( + "Game Design fresh tenant evidence differs from the exact request"); + } + return evidence; + } + + private static String gameDesignServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + } + + private static UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + throw new IllegalArgumentException("UUID evidence is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("UUID evidence must be canonical lowercase", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("UUID evidence must be canonical and nonnil"); + } + return parsed; + } + + private static IllegalStateException invalidOwnerEvidence(String message) { + return new IllegalStateException(message); + } + + private static IllegalStateException invalidOwnerEvidence(String message, Throwable cause) { + return new IllegalStateException(message, cause); + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProperties) { + return FileBackedGrpcMtlsPolicy.require( + tlsProperties, + "Fresh tenant identity reads", + "Game Session gRPC TLS configuration is required", + "Fresh tenant identity reads require Game Session workload mTLS"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java index 0f978a05a4..9e40e0f067 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java @@ -1,15 +1,15 @@ package net.firedevops.firemud.gamesession.config; -import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; -import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -26,11 +26,8 @@ public class CanonicalInitialAdmissionOwnerConfiguration { CanonicalInitialAdmissionRepository canonicalInitialAdmissionRepository( DSLContext dsl, GameSessionCanonicalRealmCatalogRepository catalogRepository, - GameSessionCanonicalAdmissionPointerRepository pointerRepository, - CanonicalGameInstanceLaunchAssociationRepository launchRepository, - GameplayAdmissionPointerEventRepository eventRepository) { - return new CanonicalInitialAdmissionRepository( - dsl, catalogRepository, pointerRepository, launchRepository, eventRepository); + GameSessionCanonicalAdmissionPointerRepository pointerRepository) { + return new CanonicalInitialAdmissionRepository(dsl, catalogRepository, pointerRepository); } @Bean @@ -43,3 +40,22 @@ CanonicalInitialAdmissionService canonicalInitialAdmissionService( repository, pointerRepository, worldVerifier, transactionManager); } } + +/** The existing isolated-fixture flag supplies its canonical STARTING launch owner. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +class RunOwnedFixtureCanonicalLaunchOwnerConfiguration { + @Bean + GameSessionCanonicalInstanceLaunchRepository runOwnedFixtureCanonicalLaunchOwner( + DSLContext dsl, + @Qualifier("transactionManager") PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameSessionCanonicalInstanceLaunchRepository( + dsl, + transactionManager, + workloadNamespace, + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, workloadNamespace)); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwner.java new file mode 100644 index 0000000000..e42f6bec11 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwner.java @@ -0,0 +1,361 @@ +package net.firedevops.firemud.gamesession.data; + +import java.nio.file.Path; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.FixtureCanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.FixtureCanonicalRealmCatalog; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Bounded, internal-only launch preparation for an explicitly claimed run-owned Compose fixture. + */ +@Component +public final class RunOwnedCanonicalLaunchPreparationOwner { + private final boolean enabled; + private final String capabilityPath; + private final String sourceReceiptPath; + private final String runId; + private final String composeProjectName; + private final CommonGrpcClientProperties grpcProperties; + private final ObjectProvider configuredLaunchOwners; + private final String workloadNamespace; + private final GameSessionCanonicalInstanceLaunchRepository fixedLaunchOwner; + private final AtomicReference acceptedCapability = + new AtomicReference<>(); + private final AtomicReference + acceptedSourceReceipt = new AtomicReference<>(); + + @Autowired + public RunOwnedCanonicalLaunchPreparationOwner( + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String sourceReceiptPath, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, + CommonGrpcClientProperties grpcProperties, + ObjectProvider configuredLaunchOwners, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this( + enabled, + capabilityPath, + sourceReceiptPath, + runId, + composeProjectName, + grpcProperties, + configuredLaunchOwners, + workloadNamespace, + null); + } + + RunOwnedCanonicalLaunchPreparationOwner( + boolean enabled, + String capabilityPath, + String sourceReceiptPath, + String runId, + String composeProjectName, + CommonGrpcClientProperties grpcProperties, + GameSessionCanonicalInstanceLaunchRepository launchOwner, + String workloadNamespace) { + this( + enabled, + capabilityPath, + sourceReceiptPath, + runId, + composeProjectName, + grpcProperties, + null, + workloadNamespace, + Objects.requireNonNull(launchOwner, "launchOwner")); + } + + private RunOwnedCanonicalLaunchPreparationOwner( + boolean enabled, + String capabilityPath, + String sourceReceiptPath, + String runId, + String composeProjectName, + CommonGrpcClientProperties grpcProperties, + ObjectProvider configuredLaunchOwners, + String workloadNamespace, + GameSessionCanonicalInstanceLaunchRepository fixedLaunchOwner) { + this.enabled = enabled; + this.capabilityPath = capabilityPath; + this.sourceReceiptPath = sourceReceiptPath; + this.runId = runId; + this.composeProjectName = composeProjectName; + this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); + this.configuredLaunchOwners = configuredLaunchOwners; + this.workloadNamespace = workloadNamespace; + this.fixedLaunchOwner = fixedLaunchOwner; + } + + /** Explicit source preparation; no scheduler or read RPC invokes this owner write. */ + public CommittedFixtureLaunchOwnerEvidence prepareFixedVerifiedFixtureLaunch() { + FixedSourceReceipt source = loadFixedVerifiedSourceReceipt(); + return prepareVerifiedFixtureLaunch(source.capability(), source.receipt()); + } + + CommittedFixtureLaunchOwnerEvidence prepareVerifiedFixtureLaunch( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { + if (!enabled) { + throw unresolved(); + } + Objects.requireNonNull(capability, "capability"); + requireExactSourceReceipt(capability, sourceReceipt); + RunOwnedInitialAdmissionLaunchEvidence launchEvidence = + RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt(capability, sourceReceipt); + launchEvidence.requireVerifiedFixture(); + + GameSessionCanonicalInstanceLaunchRepository launchOwner = launchOwner(); + FixtureCanonicalInstanceLaunch committed = + Objects.requireNonNull( + launchOwner.createVerifiedFixtureStartingLaunch(launchEvidence), + "Fixture launch owner returned no committed STARTING allocation"); + FixtureCanonicalInstanceLaunch independent = + Objects.requireNonNull( + launchOwner.readVerifiedFixtureLaunch(launchEvidence), + "Independent fixture launch readback returned no allocation"); + requireExactStartingLaunch(capability, launchEvidence, committed, independent); + return new CommittedFixtureLaunchOwnerEvidence(launchEvidence, independent); + } + + /** Loads only the fixed, independently verified fixture source; it performs no owner writes. */ + public RunOwnedInitialAdmissionLaunchEvidence loadFixedVerifiedEvidence() { + FixedSourceReceipt source = loadFixedVerifiedSourceReceipt(); + return RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt( + source.capability(), source.receipt()); + } + + private FixedSourceReceipt loadFixedVerifiedSourceReceipt() { + if (!enabled) { + throw unresolved(); + } + RunOwnedInitialAdmissionFixtureCapability capability = + acceptCapability( + RunOwnedInitialAdmissionFixtureCapability.load( + declaredCapabilityPath(), runId, composeProjectName, grpcProperties)); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = + acceptSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + declaredSourceReceiptPath(), + runId, + composeProjectName, + capability, + grpcProperties)); + requireExactSourceReceipt(capability, sourceReceipt); + return new FixedSourceReceipt(capability, sourceReceipt); + } + + /** Authenticates the fixed World peer before reading any caller-selectable fixture state. */ + public RunOwnedInitialAdmissionLaunchEvidence loadFixedVerifiedEvidenceForWorldPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !"world-management-service".equals(peer.service()) + || !workloadNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + workloadNamespace + "/sa/world-management-service") + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Fixed fixture read requires the exact World workload peer"); + } + RunOwnedInitialAdmissionLaunchEvidence evidence = loadFixedVerifiedEvidence(); + GrpcPeerCertificateEvidence certificate = GrpcPeerCertificateEvidence.current(); + if (certificate == null + || !evidence + .fixtureCapability() + .worldManagementLeafSha256() + .equals(certificate.leafSha256())) { + throw new AdminAuthorizationException( + "Fixed fixture read requires the retained World recipient leaf"); + } + return evidence; + } + + /** Reads the actual allocation through the canonical launch repository. */ + public FixtureCanonicalInstanceLaunch readFixedFixtureLaunch( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + Objects.requireNonNull(evidence, "evidence").requireVerifiedFixture(); + if (!Objects.equals(workloadNamespace, evidence.sourceEvidence().targetNamespace())) { + throw unresolved(); + } + return launchOwner().readVerifiedFixtureLaunch(evidence); + } + + private RunOwnedInitialAdmissionFixtureCapability acceptCapability( + RunOwnedInitialAdmissionFixtureCapability capability) { + RunOwnedInitialAdmissionFixtureCapability first = + acceptedCapability.updateAndGet(existing -> existing == null ? capability : existing); + if (!Objects.equals(first, capability)) { + throw unresolved(); + } + return first; + } + + private RunOwnedInitialAdmissionFixtureCapability.SourceReceipt acceptSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt first = + acceptedSourceReceipt.updateAndGet(existing -> existing == null ? sourceReceipt : existing); + if (!Objects.equals(first, sourceReceipt)) { + throw unresolved(); + } + return first; + } + + private GameSessionCanonicalInstanceLaunchRepository launchOwner() { + if (fixedLaunchOwner != null) { + return fixedLaunchOwner; + } + GameSessionCanonicalInstanceLaunchRepository configured = + configuredLaunchOwners == null ? null : configuredLaunchOwners.getIfAvailable(); + if (configured == null) { + throw unresolved(); + } + return configured; + } + + private Path declaredCapabilityPath() { + if (capabilityPath == null || capabilityPath.isBlank()) { + throw unresolved(); + } + try { + return Path.of(capabilityPath); + } catch (RuntimeException exception) { + throw unresolved(); + } + } + + private Path declaredSourceReceiptPath() { + if (sourceReceiptPath == null || sourceReceiptPath.isBlank()) { + throw unresolved(); + } + try { + return Path.of(sourceReceiptPath); + } catch (RuntimeException exception) { + throw unresolved(); + } + } + + private static void requireExactStartingLaunch( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionLaunchEvidence evidence, + FixtureCanonicalInstanceLaunch committed, + FixtureCanonicalInstanceLaunch independent) { + FixtureCanonicalRealmCatalog catalog = independent.catalog(); + var snapshot = catalog.snapshot(); + var association = catalog.association(); + var source = evidence.sourceEvidence(); + var creation = evidence.creationEvidence(); + if (!committed.equals(independent) + || independent.status() != CurrentGameInstanceStatus.STARTING + || independent.gameInstanceId() <= 0L + || independent.gameInstanceUuid() == null + || new UUID(0L, 0L).equals(independent.gameInstanceUuid()) + || independent.rowVersion() != 0L + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE.equals( + snapshot.targetNamespace()) + || !source.targetNamespace().equals(snapshot.targetNamespace()) + || !source.canonicalTenantId().equals(snapshot.tenantId()) + || !source.tenantSlug().equals(snapshot.tenantSlug()) + || !capability.worldSlug().equals(snapshot.worldSlug()) + || !capability.realmSlug().equals(snapshot.realmSlug()) + || !capability.realmDisplayName().equals(snapshot.realmDisplayName()) + || capability.visible() != snapshot.visible() + || capability.publicProductionRealm() != snapshot.publicProduction() + || !capability.stateScope().equals(snapshot.stateScope()) + || !capability.characterCreationPolicy().equals(snapshot.characterCreationPolicy()) + || snapshot.catalogRevision() <= 0L + || !source.targetNamespace().equals(association.targetNamespace()) + || !source.canonicalTenantId().equals(association.canonicalTenantId()) + || association.gameSessionTenantId() <= 0L + || !creation.equals(association.sourceEvidence()) + || !evidence.fixtureCapability().operationId().equals(capability.operationId()) + || evidence.fixturePolicySeal() == null) { + throw unresolved(); + } + } + + static void requireExactSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { + if (receipt == null + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA.equals(receipt.schema()) + || !capability.runId().equals(receipt.runId()) + || !capability.composeProjectName().equals(receipt.composeProjectName()) + || !capability.operationId().equals(receipt.fixtureOperationId()) + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE.equals( + receipt.ownerService()) + || !capability.gameSessionUriSan().equals(receipt.gameSessionUriSan()) + || !capability.gameSessionLeafSha256().equals(receipt.gameSessionLeafSha256()) + || !capability.caCertificateSha256().equals(receipt.caCertificateSha256()) + || !capability.worldManagementUriSan().equals(receipt.worldManagementUriSan()) + || !capability.worldManagementLeafSha256().equals(receipt.worldManagementLeafSha256()) + || receipt.creationEvidence() == null + || receipt.fixturePolicySeal() == null + || receipt.sourceEvidence() == null + || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE.equals( + receipt.sourceEvidence().targetNamespace()) + || !receipt + .creationEvidence() + .targetNamespace() + .equals(receipt.sourceEvidence().targetNamespace()) + || !receipt + .creationEvidence() + .canonicalTenantId() + .equals(receipt.sourceEvidence().canonicalTenantId()) + || receipt.creationEvidence().sourceGameRowId() + != receipt.sourceEvidence().sourceGameRowId() + || !receipt + .creationEvidence() + .sourceGameTenantKey() + .equals(receipt.sourceEvidence().sourceGameTenantKey()) + || !receipt + .creationEvidence() + .provenanceKind() + .equals(receipt.sourceEvidence().provenanceKind()) + || receipt.launchReadEvidence() == null + || receipt.launchReadEvidence().launchDescriptor() == null + || !RunOwnedInitialAdmissionFixtureCapability.LAUNCH_READ_EVIDENCE_SCHEMA.equals( + receipt.launchReadEvidence().schema()) + || receipt.launchReadEvidence().gameTemplateId() != capability.gameTemplateId() + || !capability + .operationId() + .equals(receipt.sourceEvidence().registrationRequestId().toString()) + || !capability.worldSlug().equals(receipt.sourceEvidence().worldSlug()) + || !capability.worldDisplayName().equals(receipt.sourceEvidence().worldDisplayName()) + || !Long.toString(capability.tenantId()) + .equals(receipt.sourceEvidence().sourceGameTenantKey())) { + throw unresolved(); + } + } + + private record FixedSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) {} + + private static RuntimeException unresolved() { + return new IllegalStateException("Run-owned fixture launch preparation remains unresolved"); + } + + public record CommittedFixtureLaunchOwnerEvidence( + RunOwnedInitialAdmissionLaunchEvidence launchEvidence, + FixtureCanonicalInstanceLaunch launch) { + public CommittedFixtureLaunchOwnerEvidence { + Objects.requireNonNull(launchEvidence, "launchEvidence"); + Objects.requireNonNull(launch, "launch"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index a37d3ca2a1..724eef9a40 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; @@ -47,7 +48,8 @@ record RunOwnedInitialAdmissionFixtureCapability( String gameSessionUriSan, String caCertificateSha256, String worldManagementUriSan, - String worldManagementLeafSha256) { + String worldManagementLeafSha256, + String claimDigest) { public static final String CAPABILITY_SCHEMA = RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA; public static final String GAME_SESSION_URI_SAN = @@ -164,13 +166,15 @@ static SourceReceipt parseSourceReceipt( parsedLaunchEvidence.publishedReleaseBundle(), parsedLaunchEvidence.versionAssetArtifactState(), parsedLaunchEvidence.versionState(), - parsedLaunchEvidence.launchDescriptor())); + parsedLaunchEvidence.launchDescriptor()), + parsed.creationEvidence(), + parsed.fixturePolicySeal()); } catch (RuntimeException exception) { throw invalidSourceReceipt(); } } - private static RunOwnedInitialAdmissionFixtureWireCodec.Capability toWireCapability( + static RunOwnedInitialAdmissionFixtureWireCodec.Capability toWireCapability( RunOwnedInitialAdmissionFixtureCapability capability) { return new RunOwnedInitialAdmissionFixtureWireCodec.Capability( CAPABILITY_SCHEMA, @@ -193,7 +197,8 @@ private static RunOwnedInitialAdmissionFixtureWireCodec.Capability toWireCapabil capability.gameSessionUriSan(), capability.caCertificateSha256(), capability.worldManagementUriSan(), - capability.worldManagementLeafSha256()); + capability.worldManagementLeafSha256(), + capability.claimDigest()); } static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( @@ -235,7 +240,8 @@ static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( parsed.gameSessionUriSan(), parsed.caCertificateSha256(), parsed.worldManagementUriSan(), - parsed.worldManagementLeafSha256()); + parsed.worldManagementLeafSha256(), + parsed.claimDigest()); } catch (RuntimeException exception) { throw invalidCapability(); } @@ -369,7 +375,9 @@ record SourceReceipt( String worldManagementUriSan, String worldManagementLeafSha256, AuthoredWorldSourceEvidence sourceEvidence, - LaunchReadEvidence launchReadEvidence) {} + LaunchReadEvidence launchReadEvidence, + FreshTenantCreationEvidence creationEvidence, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixturePolicySeal) {} record LaunchReadEvidence( String schema, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java index bb08ac29d7..58aa4d6e41 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidence.java @@ -2,7 +2,9 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; @@ -12,6 +14,7 @@ public final class RunOwnedInitialAdmissionLaunchEvidence { public static final String SCHEMA = "firemud.run-owned-v1-launch-read-evidence.v1"; + private final Verification verification; private final AuthoredWorldSourceEvidence sourceEvidence; private final String schema; private final long gameTemplateId; @@ -28,6 +31,27 @@ public final class RunOwnedInitialAdmissionLaunchEvidence { VersionAssetArtifactState versionAssetArtifactState, VersionStateSnapshot versionState, LaunchDescriptor launchDescriptor) { + this( + UnverifiedProjection.INSTANCE, + sourceEvidence, + schema, + gameTemplateId, + publishedReleaseBundle, + versionAssetArtifactState, + versionState, + launchDescriptor); + } + + private RunOwnedInitialAdmissionLaunchEvidence( + Verification verification, + AuthoredWorldSourceEvidence sourceEvidence, + String schema, + long gameTemplateId, + PublishedReleaseBundle publishedReleaseBundle, + VersionAssetArtifactState versionAssetArtifactState, + VersionStateSnapshot versionState, + LaunchDescriptor launchDescriptor) { + this.verification = Objects.requireNonNull(verification, "verification"); this.sourceEvidence = Objects.requireNonNull(sourceEvidence, "sourceEvidence"); this.schema = Objects.requireNonNull(schema, "schema"); if (gameTemplateId <= 0L) { @@ -45,10 +69,11 @@ public final class RunOwnedInitialAdmissionLaunchEvidence { static RunOwnedInitialAdmissionLaunchEvidence fromVerifiedSourceReceipt( RunOwnedInitialAdmissionFixtureCapability capability, RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { - RunOwnedInitialAdmissionFixtureCoordinator.requireExactSourceReceipt(capability, receipt); + RunOwnedCanonicalLaunchPreparationOwner.requireExactSourceReceipt(capability, receipt); RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence readEvidence = receipt.launchReadEvidence(); return new RunOwnedInitialAdmissionLaunchEvidence( + new VerifiedFixture(capability, receipt), receipt.sourceEvidence(), readEvidence.schema(), readEvidence.gameTemplateId(), @@ -58,6 +83,90 @@ static RunOwnedInitialAdmissionLaunchEvidence fromVerifiedSourceReceipt( readEvidence.launchDescriptor()); } + /** This check cannot be satisfied by the package's unchecked preflight-test constructor. */ + public void requireVerifiedFixture() { + verified(); + } + + public RunOwnedInitialAdmissionFixtureWireCodec.Capability fixtureCapability() { + return RunOwnedInitialAdmissionFixtureCapability.toWireCapability(verified().capability()); + } + + public FreshTenantCreationEvidence creationEvidence() { + return verified().receipt().creationEvidence(); + } + + public RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixturePolicySeal() { + return verified().receipt().fixturePolicySeal(); + } + + /** + * Existing runtime identity columns retain bare SHA-256; the policy owner retains its prefixed + * seal. + */ + public String fixtureRuntimeRequestDigest() { + return fixturePolicySeal().requestDigest().substring("sha256:".length()); + } + + public byte[] fixturePolicyRequestBytes() { + return RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + fixtureCapability(), creationEvidence(), sourceEvidence, wireLaunchReadEvidence()); + } + + public RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence wireLaunchReadEvidence() { + verified(); + return new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + schema, + gameTemplateId, + publishedReleaseBundle, + versionAssetArtifactState, + versionState, + launchDescriptor); + } + + private VerifiedFixture verified() { + if (!(verification instanceof VerifiedFixture fixture)) { + throw new IllegalArgumentException("Verified run-owned fixture provenance is required"); + } + RunOwnedCanonicalLaunchPreparationOwner.requireExactSourceReceipt( + fixture.capability(), fixture.receipt()); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + RunOwnedInitialAdmissionFixtureCapability.toWireCapability(fixture.capability()), + fixture.receipt().creationEvidence(), + sourceEvidence, + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + schema, + gameTemplateId, + publishedReleaseBundle, + versionAssetArtifactState, + versionState, + launchDescriptor)); + var seal = fixture.receipt().fixturePolicySeal(); + if (!RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA.equals(seal.schema()) + || !RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE.equals( + seal.ownerService()) + || !java.util.UUID.fromString(fixture.capability().operationId()).equals(seal.operationId()) + || !requestDigest.equals(seal.requestDigest()) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + seal.operationId(), requestDigest) + .equals(seal.evidenceDigest())) { + throw new IllegalArgumentException("Exact owner-issued fixture policy seal is required"); + } + return fixture; + } + + private sealed interface Verification permits UnverifiedProjection, VerifiedFixture {} + + private enum UnverifiedProjection implements Verification { + INSTANCE + } + + private record VerifiedFixture( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) + implements Verification {} + public AuthoredWorldSourceEvidence sourceEvidence() { return sourceEvidence; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java index 1d3a995898..a260a2ded2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionIntentSnapshot.java @@ -193,10 +193,10 @@ public static void requireExactBinding( private static void requireIntentRequestId(String value) { if (value == null || value.isBlank() - || value.codePointCount(0, value.length()) > 120 + || value.codePointCount(0, value.length()) > 128 || value.codePoints().anyMatch(Character::isISOControl)) { throw new IllegalArgumentException( - "Initial-admission request ID must fit the immutable V28 120-character intent column"); + "Initial-admission request ID must fit the V34.3 128-character intent column"); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java index ee5f4a78bd..b3eaff2e42 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -58,13 +58,16 @@ public CanonicalGameInstanceLaunchAssociationRepository( /** * Captures an existing STARTING owner row and its exact launch binding in the same writable READ - * COMMITTED transaction. This method does not allocate or create a runtime row. + * COMMITTED transaction, binding the exact Human tuple and catalog identity. This method does not + * allocate or create a runtime row. */ public CanonicalGameInstanceLaunchAssociation capture( FreshGameSessionTenantAssociation tenantAssociation, long gameInstanceId, - CompleteLaunchBindingEvidence launchBindingEvidence) { + CompleteLaunchBindingEvidence launchBindingEvidence, + StartSessionPostAuthorizationExecutionTuple originalTuple) { requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(originalTuple, "originalTuple"); Objects.requireNonNull(tenantAssociation, "tenantAssociation"); requirePositive(gameInstanceId, "gameInstanceId"); ValidatedBinding binding = validateBinding(launchBindingEvidence); @@ -72,22 +75,38 @@ public CanonicalGameInstanceLaunchAssociation capture( throw new IllegalArgumentException("Launch binding targets another Game Session namespace"); } + var action = originalTuple.preAuthorizationTuple().action(); + if (!"human_operator".equals(originalTuple.issuanceKind()) + || !"StartSession".equals(originalTuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(originalTuple.preAuthorizationTuple().targetOwner()) + || !workloadNamespace.equals(action.scope().targetNamespace()) + || !binding.descriptor().canonicalTenantId().equals(action.scope().tenantId()) + || !binding + .descriptor() + .controlPlaneRequestId() + .equals(originalTuple.controlPlaneRequestId()) + || binding.descriptor().gameTemplateId() != action.target().gameTemplateId()) { + throw new IllegalArgumentException("Original tuple differs from the exact canonical launch"); + } + lockRequest(binding.descriptor().controlPlaneRequestId()); + requireOriginalPinsBeforeStarting(originalTuple, binding.evidence()); RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); requireFreshSourceIdentity(tenantAssociation, source); if (!binding.descriptor().canonicalTenantId().equals(source.canonicalTenantId())) { throw new IllegalArgumentException("Launch binding does not match its fresh tenant owner"); } - lockRequest(binding.descriptor().controlPlaneRequestId()); FreshTenantOwnerMapping mapping = requireFreshTenantMapping(tenantAssociation); GameInstanceRow runtime = requireLockedRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); - RealmOwnerProjection realm = requirePublicSharedRealm(binding.descriptor()); + RealmOwnerProjection realm = requirePublicSharedRealm(binding.evidence()); CanonicalGameInstanceLaunchAssociation existing = findByRequest(binding.descriptor().controlPlaneRequestId(), true) .map(this::toAssociation) .orElse(null); if (existing != null) { + requireExactCapturedOwnerIdentity( + binding.descriptor().controlPlaneRequestId(), originalTuple, realm); requireExactRetry( existing, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); return existing; @@ -108,9 +127,11 @@ public CanonicalGameInstanceLaunchAssociation capture( + "game_instance_uuid, canonical_realm_id, world_slug, playable_state_namespace_id, playable_state_scope, " + "public_production, captured_starting_row_version, game_template_id, " + "launch_descriptor_id, version_id, release_bundle_id, generation_config_revision, " - + "version_state_epoch, complete_launch_binding_evidence) " + + "version_state_epoch, complete_launch_binding_evidence, original_start_session_tuple, " + + "catalog_creation_request_id, catalog_revision, catalog_source_intake_operation_id, " + + "catalog_source_intake_request_id) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, " - + "'SHARED', TRUE, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + + "'SHARED', TRUE, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb), ?, ?, ?, ?, ?)", workloadNamespace, binding.descriptor().controlPlaneRequestId(), tenantAssociation.legacyGameSessionTenantId(), @@ -136,8 +157,15 @@ public CanonicalGameInstanceLaunchAssociation capture( binding.descriptor().releaseBundleId(), binding.descriptor().generationConfigRevision(), binding.descriptor().versionStateEpoch(), - evidenceJson); - + evidenceJson, + originalTuple.canonicalBytes(), + realm.creationRequestId(), + realm.catalogRevision(), + realm.sourceIntakeOperationId(), + realm.sourceIntakeRequestId()); + + requireExactCapturedOwnerIdentity( + binding.descriptor().controlPlaneRequestId(), originalTuple, realm); CanonicalGameInstanceLaunchAssociation inserted = findByRequest(binding.descriptor().controlPlaneRequestId(), true) .map(this::toAssociation) @@ -150,6 +178,33 @@ public CanonicalGameInstanceLaunchAssociation capture( return inserted; } + private void requireExactCapturedOwnerIdentity( + String requestId, + StartSessionPostAuthorizationExecutionTuple tuple, + RealmOwnerProjection realm) { + Record row = + dsl.fetchOne( + "SELECT original_start_session_tuple, catalog_creation_request_id, " + + "catalog_revision, catalog_source_intake_operation_id, catalog_source_intake_request_id " + + "FROM game_session_canonical_instance_launch WHERE target_namespace=? AND control_plane_request_id=?", + workloadNamespace, + requestId); + if (row == null + || !Arrays.equals( + tuple.canonicalBytes(), row.get("original_start_session_tuple", byte[].class)) + || !realm.creationRequestId().equals(row.get("catalog_creation_request_id", UUID.class)) + || realm.catalogRevision() != requiredLong(row, "catalog_revision") + || !realm + .sourceIntakeOperationId() + .equals(row.get("catalog_source_intake_operation_id", UUID.class)) + || !realm + .sourceIntakeRequestId() + .equals(row.get("catalog_source_intake_request_id", UUID.class))) { + throw new IllegalStateException( + "Captured original tuple or catalog owner identity differs from exact retry"); + } + } + /** Serializes a STARTING-row producer on the exact namespace/request key used by capture. */ public void lockRequestForStartingGameInstance(String controlPlaneRequestId) { requireWritableReadCommittedOwnerTransaction(); @@ -157,6 +212,30 @@ public void lockRequestForStartingGameInstance(String controlPlaneRequestId) { lockRequest(controlPlaneRequestId); } + /** Reads Human launch evidence with mandatory values captured by its actual catalog owner. */ + public Optional readWithCatalog(String controlPlaneRequestId) { + requireOutsideTransaction(); + requireRequestId(controlPlaneRequestId); + return findByRequest(controlPlaneRequestId, false) + .map( + row -> + new HumanLaunchAssociation( + toAssociation(row), + requiredUuid(row, "canonical_realm_id"), + requiredLong(row, "catalog_revision"))); + } + + public record HumanLaunchAssociation( + CanonicalGameInstanceLaunchAssociation association, + UUID canonicalRealmId, + long catalogRevision) { + public HumanLaunchAssociation { + Objects.requireNonNull(association, "association"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requirePositive(catalogRevision, "catalogRevision"); + } + } + /** * Reads one committed immutable owner association plus the transient current GameInstance row. */ @@ -225,6 +304,105 @@ public Optional readOriginalStartSessionAssocia } } + /** Verifies the existing canonical pins under the original owner lock before STARTING exists. */ + public void requireOriginalPinsBeforeStarting( + StartSessionPostAuthorizationExecutionTuple tuple, CompleteLaunchBindingEvidence binding) { + requireWritableReadCommittedOwnerTransaction(); + String namespace = tuple.preAuthorizationTuple().action().scope().targetNamespace(); + if (!workloadNamespace.equals(namespace)) { + throw new IllegalStateException("Original pin namespace differs from configured owner"); + } + Record row = + dsl.fetchOne( + "SELECT attempt.owner_attempt_id, attempt.owner_fence, " + + "attempt.account_redemption_projection AS owner_projection, " + + "association_pin.canonical_tenant_id AS pin_canonical_tenant_id, " + + "association_pin.template_id AS pin_template_id, " + + "association_pin.canonical_version_id AS pin_canonical_version_id, " + + "association_pin.selected_commit_id AS pin_selected_commit_id, " + + "association_pin.publish_workflow_id AS pin_publish_workflow_id, " + + "association_pin.publication_selection_digest AS pin_publication_selection_digest, " + + "association_pin.association_digest AS pin_association_digest, " + + "association_pin.world_intake_request_id AS pin_world_intake_request_id, " + + "association_pin.world_operation_id AS pin_world_operation_id, " + + "association_pin.source_operation_id AS pin_source_operation_id, " + + "association_pin.source_evidence_digest AS pin_source_evidence_digest, " + + "association_pin.association_request_wire, association_pin.association_response_wire, " + + "association_pin.association_request_digest, association_pin.association_response_digest, " + + "association_pin.post_authorization_tuple_digest, association_pin.account_redemption_projection_digest, " + + "descriptor_pin.descriptor_request_wire, descriptor_pin.descriptor_response_wire, " + + "descriptor_pin.descriptor_request_digest, descriptor_pin.descriptor_response_digest " + + "FROM game_session_start_session_operator_attempt attempt " + + "JOIN game_session_start_session_template_association_pin association_pin " + + "ON association_pin.target_namespace=attempt.target_namespace " + + "AND association_pin.control_plane_request_id=attempt.control_plane_request_id " + + "AND association_pin.canonical_tenant_id=attempt.canonical_tenant_id " + + "AND association_pin.owner_attempt_id=attempt.owner_attempt_id " + + "AND association_pin.owner_fence=attempt.owner_fence " + + "AND association_pin.post_authorization_execution_tuple=attempt.post_authorization_execution_tuple " + + "JOIN game_session_start_session_launch_descriptor_pin descriptor_pin " + + "ON descriptor_pin.target_namespace=attempt.target_namespace " + + "AND descriptor_pin.control_plane_request_id=attempt.control_plane_request_id " + + "AND descriptor_pin.canonical_tenant_id=attempt.canonical_tenant_id " + + "AND descriptor_pin.owner_attempt_id=attempt.owner_attempt_id " + + "AND descriptor_pin.owner_fence=attempt.owner_fence " + + "AND descriptor_pin.association_request_digest=association_pin.association_request_digest " + + "AND descriptor_pin.association_response_digest=association_pin.association_response_digest " + + "WHERE attempt.target_namespace=? AND attempt.control_plane_request_id=? " + + "AND attempt.post_authorization_execution_tuple=? AND attempt.phase_state='OWNER_EXECUTION_PENDING' " + + "AND attempt.lease_expires_at>clock_timestamp() " + + "FOR UPDATE OF attempt, association_pin, descriptor_pin", + namespace, + tuple.controlPlaneRequestId(), + tuple.canonicalBytes()); + if (row == null) + throw new IllegalStateException("Exact canonical pins are required before STARTING"); + byte[] projection = requiredBytes(row, "owner_projection"); + StartSessionAccountRedemptionProjection.requireCurrentBinding(projection, tuple); + byte[] associationRequest = requiredBytes(row, "association_request_wire"); + byte[] associationResponse = requiredBytes(row, "association_response_wire"); + byte[] descriptorRequest = requiredBytes(row, "descriptor_request_wire"); + byte[] descriptorResponse = requiredBytes(row, "descriptor_response_wire"); + if (!sha256(tuple.canonicalBytes()) + .equals(row.get("post_authorization_tuple_digest", String.class)) + || !sha256(projection).equals(row.get("account_redemption_projection_digest", String.class)) + || !sha256(associationRequest).equals(row.get("association_request_digest", String.class)) + || !sha256(associationResponse).equals(row.get("association_response_digest", String.class)) + || !sha256(descriptorRequest).equals(row.get("descriptor_request_digest", String.class)) + || !sha256(descriptorResponse) + .equals(row.get("descriptor_response_digest", String.class))) { + throw new IllegalStateException("Canonical pin bytes differ from their exact owner digests"); + } + Result selection = + decodeAssociationPin( + row, + tuple, + requiredUuid(row, "owner_attempt_id"), + requiredLong(row, "owner_fence"), + associationRequest, + associationResponse); + Resolved descriptor = decodeDescriptorPin(selection, descriptorRequest, descriptorResponse); + if (!(descriptor.outcome() instanceof DescriptorOutcome outcome) + || !outcome.descriptor().equals(binding.descriptor())) { + throw new IllegalStateException( + "Canonical descriptor pin differs from complete launch binding"); + } + Record current = + dsl.fetchOne( + "SELECT lease_expires_at>clock_timestamp() AS live " + + "FROM game_session_start_session_operator_attempt WHERE target_namespace=? " + + "AND control_plane_request_id=? AND owner_attempt_id=? AND owner_fence=? " + + "AND phase_state='OWNER_EXECUTION_PENDING' AND post_authorization_execution_tuple=?", + namespace, + tuple.controlPlaneRequestId(), + requiredUuid(row, "owner_attempt_id"), + requiredLong(row, "owner_fence"), + tuple.canonicalBytes()); + if (current == null || !Boolean.TRUE.equals(current.get("live", Boolean.class))) { + throw new IllegalStateException("Original pin owner lease expired before STARTING"); + } + } + private Record findHistoricalOriginalStartSessionOwnerEvidence( HistoricalOriginalStartSessionOwnerEvidence.Request request) { var selector = request.associationSelector(); @@ -320,6 +498,7 @@ private Record findHistoricalOriginalStartSessionOwnerEvidence( StartSessionPostAuthorizationExecutionTuple tuple = StartSessionPostAuthorizationExecutionTuple.decode(ownerTupleBytes); if (!Arrays.equals(tuple.canonicalBytes(), ownerTupleBytes) + || !Arrays.equals(ownerTupleBytes, requiredBytes(row, "original_start_session_tuple")) || !request.expectedOwnerAttemptId().equals(ownerAttemptId) || request.expectedOwnerFence() != ownerFence || !workloadNamespace.equals( @@ -598,6 +777,10 @@ private Record findOriginalStartSessionAssociation( + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + "AND realm.world_slug = association.world_slug " + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.catalog_revision = association.catalog_revision " + + "AND realm.creation_request_id = association.catalog_creation_request_id " + + "AND realm.source_intake_operation_id = association.catalog_source_intake_operation_id " + + "AND realm.source_intake_request_id = association.catalog_source_intake_request_id " + "AND realm.visible = TRUE AND realm.public_production = TRUE " + "AND realm.state_scope = 'SHARED' " + "JOIN game_session_start_session_operator_attempt attempt " @@ -738,7 +921,13 @@ private OriginalStartSessionAssociation decodeOriginalStartSessionAssociation(Re throw new IllegalStateException( "Original StartSession descriptor or association pin differs from the STARTING binding"); } - return new OriginalStartSessionAssociation(association, tuple, ownerAttemptId, ownerFence); + return new OriginalStartSessionAssociation( + association, + tuple, + ownerAttemptId, + ownerFence, + requiredUuid(row, "canonical_realm_id"), + requiredLong(row, "catalog_revision")); } private static Result decodeAssociationPin( @@ -1135,14 +1324,16 @@ private GameInstanceRow requireLockedRuntime(long tenantId, long gameInstanceId) return toRuntime(row, "status", "row_version"); } - private RealmOwnerProjection requirePublicSharedRealm( - net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { + private RealmOwnerProjection requirePublicSharedRealm(CompleteLaunchBindingEvidence binding) { + var descriptor = binding.descriptor(); Record row = dsl.fetchOne( - "SELECT realm_id, playable_state_namespace_id, state_scope, public_production, visible " + "SELECT realm_id, playable_state_namespace_id, state_scope, public_production, visible, " + + "creation_request_id, catalog_revision, source_intake_operation_id, source_intake_request_id, " + + "source_operation_id, source_evidence_digest, complete_policy_set_evidence, fixture_policy_request_bytes " + "FROM game_session_canonical_realm_catalog WHERE target_namespace = ? " + "AND canonical_tenant_id = ? AND world_slug = ? AND public_production = TRUE " - + "AND visible = TRUE", + + "AND visible = TRUE FOR KEY SHARE", workloadNamespace, descriptor.canonicalTenantId(), descriptor.worldSlug()); @@ -1159,7 +1350,59 @@ private RealmOwnerProjection requirePublicSharedRealm( UUID realmId = row.get("realm_id", UUID.class); requireNonNil(namespaceId, "playableStateNamespaceId"); requireNonNil(realmId, "canonicalRealmId"); - return new RealmOwnerProjection(realmId, namespaceId); + if (row.get("fixture_policy_request_bytes", byte[].class) != null + || !descriptor + .authoredWorldSourceOperationId() + .equals(row.get("source_operation_id", UUID.class)) + || !descriptor + .authoredWorldSourceEvidenceDigest() + .equals(row.get("source_evidence_digest", String.class))) { + throw new IllegalStateException( + "Human capture requires its exact authored-source catalog provenance"); + } + byte[] policyBytes = requiredBytes(row, "complete_policy_set_evidence"); + var policy = + net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec.decode( + policyBytes); + if (!policy + .target() + .canonicalVersionId() + .equals(binding.releaseAttestation().canonicalVersionId()) + || !policy.target().canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !policy.publishedReleaseBundleRef().equals(descriptor.publishedReleaseBundleRef()) + || !policy.publishWorkflowId().equals(binding.releaseAttestation().publishWorkflowId())) { + throw new IllegalStateException( + "Human capture catalog policy differs from its selected release"); + } + long revision = requiredLong(row, "catalog_revision"); + requirePositive(revision, "catalogRevision"); + var catalog = + new GameSessionCanonicalRealmCatalogRepository(dsl) + .lockExactInitialPublicProduction( + workloadNamespace, + descriptor.canonicalTenantId(), + realmId, + requiredUuid(row, "creation_request_id"), + revision); + if (!catalog.playableStateNamespaceId().equals(namespaceId) + || !catalog + .sourceIntakeReceipt() + .operationId() + .equals(requiredUuid(row, "source_intake_operation_id")) + || !catalog + .sourceIntakeReceipt() + .intakeRequestId() + .equals(requiredUuid(row, "source_intake_request_id"))) { + throw new IllegalStateException( + "Human capture catalog differs from its complete owner readback"); + } + return new RealmOwnerProjection( + realmId, + namespaceId, + requiredUuid(row, "creation_request_id"), + revision, + requiredUuid(row, "source_intake_operation_id"), + requiredUuid(row, "source_intake_request_id")); } private FreshTenantOwnerMapping requireFreshTenantMapping( @@ -1241,6 +1484,10 @@ private Optional findByRequest(String controlPlaneRequestId, boolean for + "AND realm.canonical_tenant_id = association.canonical_tenant_id " + "AND realm.world_slug = association.world_slug " + "AND realm.playable_state_namespace_id = association.playable_state_namespace_id " + + "AND realm.catalog_revision = association.catalog_revision " + + "AND realm.creation_request_id = association.catalog_creation_request_id " + + "AND realm.source_intake_operation_id = association.catalog_source_intake_operation_id " + + "AND realm.source_intake_request_id = association.catalog_source_intake_request_id " + "AND realm.visible = TRUE AND realm.public_production = TRUE " + "AND realm.state_scope = 'SHARED' " + "WHERE association.target_namespace = ? AND association.control_plane_request_id = ?" @@ -1558,7 +1805,13 @@ private record ValidatedBinding(CompleteLaunchBindingEvidence evidence) { private record FreshTenantOwnerMapping(UUID operationId) {} - private record RealmOwnerProjection(UUID realmId, UUID playableStateNamespaceId) {} + private record RealmOwnerProjection( + UUID realmId, + UUID playableStateNamespaceId, + UUID creationRequestId, + long catalogRevision, + UUID sourceIntakeOperationId, + UUID sourceIntakeRequestId) {} private record GameInstanceRow( long id, @@ -1580,12 +1833,16 @@ public record OriginalStartSessionAssociation( CanonicalGameInstanceLaunchAssociation association, StartSessionPostAuthorizationExecutionTuple postAuthorizationExecutionTuple, UUID ownerAttemptId, - long ownerFence) { + long ownerFence, + UUID canonicalRealmId, + long catalogRevision) { public OriginalStartSessionAssociation { Objects.requireNonNull(association, "association"); Objects.requireNonNull(postAuthorizationExecutionTuple, "postAuthorizationExecutionTuple"); requireNonNil(ownerAttemptId, "ownerAttemptId"); requirePositive(ownerFence, "ownerFence"); + requireNonNil(canonicalRealmId, "canonicalRealmId"); + requirePositive(catalogRevision, "catalogRevision"); var scope = postAuthorizationExecutionTuple.preAuthorizationTuple().action().scope(); if (!association.targetNamespace().equals(scope.targetNamespace()) || !association.canonicalTenantId().equals(scope.tenantId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java index 3208bbcbd4..79bc06b0be 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java @@ -68,7 +68,7 @@ public CanonicalInitialAdmissionIntentSnapshot reserve( } try { - insertIntent(holdRequest, holdBytes, lifecycleBytes, sources.binding()); + insertIntent(holdRequest, holdBytes, lifecycleBytes, sources); } catch (DataAccessException failure) { if ("23505".equals(failure.sqlState())) { throw conflict("A competing initial-admission intent already owns this request or realm"); @@ -185,7 +185,36 @@ private LockedSources lockSources(Request request) { request.realmId(), request.canonicalGameInstanceId()); SourceBinding source = sourceBinding(catalog, launch); - return new LockedSources(source); + Record retainedLaunch = + dsl.fetchOne( + "SELECT original_start_session_tuple, catalog_source_intake_operation_id, " + + "catalog_source_intake_request_id FROM game_session_canonical_instance_launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND canonical_tenant_id = ? AND canonical_realm_id = ? " + + "AND game_instance_uuid = ? AND game_session_tenant_id = ? " + + "AND game_instance_id = ? FOR UPDATE", + source.targetNamespace(), + source.controlPlaneRequestId(), + source.canonicalTenantId(), + source.realmId(), + source.canonicalGameInstanceId(), + source.gameSessionTenantId(), + source.gameInstanceId()); + if (retainedLaunch == null) { + throw conflict("Exact captured original launch evidence is unavailable for intent storage"); + } + byte[] originalTuple = required(retainedLaunch, "original_start_session_tuple", byte[].class); + UUID intakeOperation = catalog.sourceIntakeReceipt().operationId(); + UUID intakeRequest = catalog.sourceIntakeReceipt().intakeRequestId(); + if (originalTuple.length == 0 + || originalTuple.length > 262_144 + || !intakeOperation.equals( + required(retainedLaunch, "catalog_source_intake_operation_id", UUID.class)) + || !intakeRequest.equals( + required(retainedLaunch, "catalog_source_intake_request_id", UUID.class))) { + throw conflict("Captured original launch differs from the locked catalog source identity"); + } + return new LockedSources(source, originalTuple.clone(), intakeOperation, intakeRequest); } private static SourceBinding sourceBinding( @@ -222,7 +251,8 @@ private static SourceBinding sourceBinding( } private void insertIntent( - Request request, byte[] holdBytes, byte[] lifecycleBytes, SourceBinding source) { + Request request, byte[] holdBytes, byte[] lifecycleBytes, LockedSources sources) { + SourceBinding source = sources.binding(); dsl.execute( "INSERT INTO " + INTENT_TABLE @@ -234,10 +264,11 @@ private void insertIntent( + "game_instance_id, canonical_version_id, runtime_version_id, control_plane_request_id, " + "launch_descriptor_id, captured_starting_row_version, current_row_version, " + "descriptor_request_digest, descriptor_result_digest, release_attestation_digest, " + + "catalog_source_intake_operation_id, catalog_source_intake_request_id, original_start_session_tuple, " + "canonical_hold_request_bytes, canonical_lifecycle_request_bytes, hold_identity_bytes, " + "state, created_at, updated_at, terminal_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + "?, ?, ?, ?, ?, NULL, ?, clock_timestamp(), clock_timestamp(), NULL)", + + "?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, clock_timestamp(), clock_timestamp(), NULL)", request.targetNamespace(), request.initialAdmissionRequestId(), request.initialAdmissionRequestDigest(), @@ -265,6 +296,9 @@ private void insertIntent( source.descriptorRequestDigest(), source.descriptorResultDigest(), source.releaseAttestationDigest(), + sources.catalogSourceIntakeOperationId(), + sources.catalogSourceIntakeRequestId(), + sources.originalStartSessionTuple(), holdBytes, lifecycleBytes, IntentState.PENDING_HOLD.name()); @@ -474,10 +508,10 @@ private static void requireSelector(String targetNamespace, String requestId) { private static void requireIntentRequestId(String value) { if (value == null || value.isBlank() - || value.codePointCount(0, value.length()) > 120 + || value.codePointCount(0, value.length()) > 128 || value.codePoints().anyMatch(Character::isISOControl)) { throw new IllegalArgumentException( - "Initial-admission request ID must fit the immutable V28 120-character intent column"); + "Initial-admission request ID must fit the immutable V34.3 128-character intent column"); } } @@ -496,5 +530,18 @@ private static T required(Record row, String column, Class type) { message); } - private record LockedSources(SourceBinding binding) {} + private record LockedSources( + SourceBinding binding, + byte[] originalStartSessionTuple, + UUID catalogSourceIntakeOperationId, + UUID catalogSourceIntakeRequestId) { + private LockedSources { + originalStartSessionTuple = originalStartSessionTuple.clone(); + } + + @Override + public byte[] originalStartSessionTuple() { + return originalStartSessionTuple.clone(); + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index 7f5b8bed88..2f3672c3d9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -1,18 +1,14 @@ package net.firedevops.firemud.gamesession.repository; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; -import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.sql.Connection; import java.time.Instant; import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.temporal.ChronoUnit; import java.util.Collections; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -23,22 +19,19 @@ import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; -import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; -import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.ExpectedClosedEvidence; -import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; import org.jooq.DSLContext; import org.jooq.Record; -import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Durable Game Session owner transaction and exact readback for one canonical first-OPEN bind. */ +/** + * Exact Game Session owner readback for one canonical first-OPEN bind; Human writes remain closed. + */ public class CanonicalInitialAdmissionRepository { private static final String COMMITTED = "COMMITTED"; private static final String PENDING = "PENDING"; @@ -53,8 +46,6 @@ public class CanonicalInitialAdmissionRepository { private final DSLContext dsl; private final GameSessionCanonicalRealmCatalogRepository catalogRepository; private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; - private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; - private final GameplayAdmissionPointerEventRepository eventRepository; /** One exact current pointer row plus its validated owner result and GS-owned snapshot digest. */ public record CurrentOpenSnapshot( @@ -80,263 +71,35 @@ public record CurrentOpenSnapshot( public CanonicalInitialAdmissionRepository( DSLContext dsl, GameSessionCanonicalRealmCatalogRepository catalogRepository, - GameSessionCanonicalAdmissionPointerRepository pointerRepository, - CanonicalGameInstanceLaunchAssociationRepository launchRepository, - GameplayAdmissionPointerEventRepository eventRepository) { + GameSessionCanonicalAdmissionPointerRepository pointerRepository) { this.dsl = Objects.requireNonNull(dsl, "dsl"); this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); - this.launchRepository = Objects.requireNonNull(launchRepository, "launchRepository"); - this.eventRepository = Objects.requireNonNull(eventRepository, "eventRepository"); } - /** Persists the immutable request identity before remote World verification is attempted. */ - @Transactional(isolation = Isolation.READ_COMMITTED) + /** Denies fresh Human intent before owner effects while Account protection is unavailable. */ public void reserve(CanonicalInitialAdmissionRequest request) { Objects.requireNonNull(request, "request"); - requireWritableReadCommittedOwnerTransaction(); - lockTarget(request); - Attempt existing = - findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); - if (existing != null && !PENDING.equals(existing.status())) { - requireSameRequestIdentity(existing, request); - return; - } - if (existing == null - && request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - lockAllAdmissionRepresentationsForNoPrior(); - } - CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); - CanonicalInitialAdmissionLaunchTarget launchTarget = - lockLaunchTarget(request, existing == null); - requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); - - if (existing != null) { - requireSameRequest(existing, request, launchTarget); - return; - } - Attempt otherPending = findPendingForRealm(request, true); - if (otherPending != null) { - throw new CanonicalInitialAdmissionConflictException( - "Another initial-admission request already owns the pending realm attempt"); - } - - if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - pointerRepository.requireNoAdmissionPointerRepresentations( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.worldSlug(), - catalog.realmSlug(), - launchTarget.association().gameSessionTenantId(), - launchTarget.gameInstanceId()); - } else { - pointerRepository.lockExpectedClosedForRealm( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.expectedPriorPointerVersion(), - request.expectedCatalogRevision()); - } - - Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); - int inserted = - dsl.execute( - "INSERT INTO " - + OPERATION_TABLE - + " (target_namespace, initial_admission_request_id, request_digest, " - + "canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id, " - + "playable_state_scope, canonical_game_instance_id, game_session_tenant_id, " - + "game_instance_id, canonical_version_id, runtime_version_id, " - + "expected_catalog_revision, origin_kind, " - + "expected_prior_pointer_version, active_lifecycle_epoch, hold_id, hold_fence, " - + "hold_binding_digest, status, created_at, updated_at) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', " - + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ)) ON CONFLICT DO NOTHING", - request.targetNamespace(), - request.initialAdmissionRequestId(), - request.requestDigest(), - request.canonicalTenantId(), - request.worldSlug(), - request.realmId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - request.canonicalGameInstanceId(), - launchTarget.association().gameSessionTenantId(), - launchTarget.gameInstanceId(), - request.canonicalVersionId(), - launchTarget.runtimeVersionId(), - request.expectedCatalogRevision(), - request.originKind().name(), - request.expectedPriorPointerVersion(), - request.activeLifecycleEpoch(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest(), - utc(now), - utc(now)); - Attempt reserved = - findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); - if (reserved == null) { - throw new CanonicalInitialAdmissionConflictException( - "Initial-admission request reservation conflicted with durable owner state"); - } - requireSameRequest(reserved, request, launchTarget); - if (inserted == 0 && !PENDING.equals(reserved.status())) { - throw new CanonicalInitialAdmissionConflictException( - "Initial-admission request identity was concurrently terminalized"); - } + throw unavailableHumanAdmissionProtection(); } /** - * Commits the first pointer, append-only audit and terminal owner result in one short - * transaction. + * Denies Human commit before pointer, audit, or terminal owner effects while Account protection + * remains unavailable. */ - @Transactional(isolation = Isolation.READ_COMMITTED) public void commit( - CanonicalInitialAdmissionRequest request, - CanonicalInitialAdmissionWorldProof worldProof, - PreparedExpectedClosed preparedExpectedClosed) { + CanonicalInitialAdmissionRequest request, CanonicalInitialAdmissionWorldProof worldProof) { Objects.requireNonNull(request, "request"); Objects.requireNonNull(worldProof, "worldProof"); worldProof.requireMatches(request); - requireWritableReadCommittedOwnerTransaction(); - lockTarget(request); - if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - lockAllAdmissionRepresentationsForNoPrior(); - } - CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); - Attempt attempt = requireAttemptForUpdate(request); - CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, true); - requireSameRequest(attempt, request, launchTarget); - requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); - if (!PENDING.equals(attempt.status())) { - return; - } - - ExpectedClosedEvidence closedOrigin = lockExpectedClosedOrigin(request, preparedExpectedClosed); - if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - pointerRepository.requireNoAdmissionPointerRepresentations( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.worldSlug(), - catalog.realmSlug(), - launchTarget.association().gameSessionTenantId(), - launchTarget.gameInstanceId()); - } - - long pointerVersion = - request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER - ? 1L - : Math.addExact(request.expectedPriorPointerVersion(), 1L); - Instant committedAt = nextTimestamp(attempt.updatedAt()); - long pointerId = writeOpenPointer(request, catalog, launchTarget, pointerVersion, committedAt); - long auditEventId = - eventRepository.appendCanonicalInitialAdmissionOpen( - request, catalog, launchTarget, pointerVersion, catalog.catalogRevision(), committedAt); - String proofDigest = - commitProofDigest( - attempt, - pointerVersion, - auditEventId, - committedAt, - closedOrigin == null ? null : closedOrigin.originalRequestId(), - closedOrigin == null ? null : closedOrigin.requestDigest(), - closedOrigin == null ? null : closedOrigin.auditEventId()); - int updated = - dsl.execute( - "UPDATE " - + OPERATION_TABLE - + " SET status = 'COMMITTED', pointer_id = ?, pointer_version = ?, " - + "audit_event_id = ?, prior_pointer_request_id = ?, " - + "prior_pointer_request_digest = ?, prior_pointer_audit_event_id = ?, " - + "commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " - + "terminal_at = CAST(? AS TIMESTAMPTZ) " - + "WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", - pointerId, - pointerVersion, - auditEventId, - closedOrigin == null ? null : closedOrigin.originalRequestId(), - closedOrigin == null ? null : closedOrigin.requestDigest(), - closedOrigin == null ? null : closedOrigin.auditEventId(), - proofDigest, - utc(committedAt), - utc(committedAt), - request.targetNamespace(), - request.initialAdmissionRequestId()); - if (updated != 1) { - throw new CanonicalInitialAdmissionConflictException( - "Initial-admission attempt was concurrently terminalized before pointer commit"); - } + throw unavailableHumanAdmissionProtection(); } - /** - * Records a terminal local abort only while the exact expected prior authority is still current. - */ - @Transactional(isolation = Isolation.READ_COMMITTED) - public void abort( - CanonicalInitialAdmissionRequest request, - PreparedExpectedClosed preparedExpectedClosed, - String reason) { + /** Denies Human abort before owner effects while Account terminal protection is unavailable. */ + public void abort(CanonicalInitialAdmissionRequest request, String reason) { Objects.requireNonNull(request, "request"); requireText(reason, "reason", 500); - requireWritableReadCommittedOwnerTransaction(); - lockTarget(request); - if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - lockAllAdmissionRepresentationsForNoPrior(); - } - CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); - Attempt attempt = requireAttemptForUpdate(request); - CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, false); - requireSameRequest(attempt, request, launchTarget); - requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); - if (!PENDING.equals(attempt.status())) { - return; - } - - ExpectedClosedEvidence closedOrigin = lockExpectedClosedOrigin(request, preparedExpectedClosed); - if (closedOrigin == null) { - pointerRepository.requireNoAdmissionPointerRepresentations( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.worldSlug(), - catalog.realmSlug(), - launchTarget.association().gameSessionTenantId(), - launchTarget.gameInstanceId()); - } - Instant terminalAt = nextTimestamp(attempt.updatedAt()); - String abortProofDigest = - abortProofDigest( - attempt, - reason, - terminalAt, - closedOrigin == null ? null : closedOrigin.originalRequestId(), - closedOrigin == null ? null : closedOrigin.requestDigest(), - closedOrigin == null ? null : closedOrigin.auditEventId()); - int updated = - dsl.execute( - "UPDATE " - + OPERATION_TABLE - + " SET status = 'ABORTED', prior_pointer_request_id = ?, " - + "prior_pointer_request_digest = ?, prior_pointer_audit_event_id = ?, " - + "abort_proof_digest = ?, abort_reason = ?, updated_at = CAST(? AS TIMESTAMPTZ), " - + "terminal_at = CAST(? AS TIMESTAMPTZ) " - + "WHERE target_namespace = ? AND initial_admission_request_id = ? AND status = 'PENDING'", - closedOrigin == null ? null : closedOrigin.originalRequestId(), - closedOrigin == null ? null : closedOrigin.requestDigest(), - closedOrigin == null ? null : closedOrigin.auditEventId(), - abortProofDigest, - reason, - utc(terminalAt), - utc(terminalAt), - request.targetNamespace(), - request.initialAdmissionRequestId()); - if (updated != 1) { - throw new CanonicalInitialAdmissionConflictException( - "Initial-admission attempt was concurrently terminalized before abort"); - } + throw unavailableHumanAdmissionProtection(); } /** Reads the exact durable result only after the owner transaction has committed. */ @@ -344,7 +107,7 @@ public void abort( public Optional read( String targetNamespace, String initialAdmissionRequestId) { requireOutsideTransaction(); - Record row = findAttemptRecord(targetNamespace, initialAdmissionRequestId, false); + Record row = findAttemptRecord(targetNamespace, initialAdmissionRequestId); if (row == null) { return Optional.empty(); } @@ -458,152 +221,25 @@ private static void requireCurrentOpenReadSelector( requireNonNil(realmId, "realmId"); } - private static void requireNonNil(UUID value, String label) { - Objects.requireNonNull(value, label); - if (new UUID(0L, 0L).equals(value)) { - throw new IllegalArgumentException(label + " must be a non-nil UUID"); - } + /** No callable Account owner acquires and settles canonical Human terminal protection. */ + public static CanonicalHumanAdmissionProtectionUnavailableException + unavailableHumanAdmissionProtection() { + return new CanonicalHumanAdmissionProtectionUnavailableException( + "Canonical Human initial admission requires unavailable Account terminal protection"); } - private ExpectedClosedEvidence lockExpectedClosedOrigin( - CanonicalInitialAdmissionRequest request, PreparedExpectedClosed prepared) { - if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - if (prepared != null) { - throw new CanonicalInitialAdmissionConflictException( - "NO_PRIOR_POINTER cannot carry prepared CLOSED-origin evidence"); - } - return null; - } - if (prepared == null) { - throw new CanonicalInitialAdmissionReconciliationRequiredException( - "EXPECT_CLOSED requires prepared original CLOSED owner evidence"); - } - ExpectedClosedEvidence evidence = pointerRepository.lockExpectedClosed(prepared); - if (!evidence.targetNamespace().equals(request.targetNamespace()) - || !evidence.canonicalTenantId().equals(request.canonicalTenantId()) - || !evidence.realmId().equals(request.realmId()) - || evidence.pointerVersion() != request.expectedPriorPointerVersion() - || evidence.catalogRevision() != request.expectedCatalogRevision()) { - throw new CanonicalInitialAdmissionReconciliationRequiredException( - "Locked original CLOSED authority does not match the tagged request origin"); + public static final class CanonicalHumanAdmissionProtectionUnavailableException + extends IllegalStateException { + public CanonicalHumanAdmissionProtectionUnavailableException(String message) { + super(message); } - return evidence; } - private long writeOpenPointer( - CanonicalInitialAdmissionRequest request, - CanonicalRealmCatalogSnapshot catalog, - CanonicalInitialAdmissionLaunchTarget launchTarget, - long pointerVersion, - Instant updatedAt) { - CanonicalGameInstanceLaunchAssociation association = launchTarget.association(); - if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - Record inserted = - dsl.fetchOne( - "INSERT INTO gameplay_admission_pointer (" - + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " - + "game_instance_id, pointer_version, visible, requires_character_selection, " - + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " - + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " - + "playable_state_namespace_id, representation_version, target_namespace, " - + "canonical_tenant_id, admission_state, canonical_game_instance_id, " - + "canonical_version_id, runtime_version_id, initial_admission_request_id, " - + "initial_admission_request_digest, initial_admission_origin_kind, " - + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " - + "initial_admission_hold_id, initial_admission_hold_fence, " - + "initial_admission_hold_binding_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 'game-session-canonical-initial-admission', " - + "'World-held initial admission', ?, ?, ?, ?, ?, ?, 3, ?, ?, 'OPEN', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " - + "RETURNING id", - catalog.worldSlug(), - catalog.realmSlug(), - catalog.sourceIntakeReceipt().source().worldDisplayName(), - catalog.realmDisplayName(), - association.gameSessionTenantId(), - launchTarget.gameInstanceId(), - pointerVersion, - catalog.visible(), - catalog.stateScope(), - catalog.characterCreationPolicy(), - toLocalDateTime(updatedAt), - toLocalDateTime(updatedAt), - catalog.publicProduction(), - catalog.catalogRevision(), - catalog.realmId(), - catalog.playableStateNamespaceId(), - request.targetNamespace(), - request.canonicalTenantId(), - request.canonicalGameInstanceId(), - request.canonicalVersionId(), - launchTarget.runtimeVersionId(), - request.initialAdmissionRequestId(), - request.requestDigest(), - request.originKind().name(), - request.expectedPriorPointerVersion(), - request.activeLifecycleEpoch(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest()); - if (inserted == null || inserted.get("id", Long.class) == null) { - throw new CanonicalInitialAdmissionConflictException( - "Canonical initial OPEN pointer insert returned no owner row"); - } - return inserted.get("id", Long.class); - } - - Record pointer = - dsl.fetchOne( - "UPDATE gameplay_admission_pointer SET world_slug = ?, realm_slug = ?, " - + "world_display_name = ?, realm_display_name = ?, tenant_id = ?, game_instance_id = ?, " - + "pointer_version = ?, visible = ?, requires_character_selection = NULL, " - + "state_scope = ?, character_creation_policy = ?, " - + "last_updated_by = 'game-session-canonical-initial-admission', " - + "last_update_reason = 'World-held initial admission', updated_at = ?, " - + "public_production_realm = ?, catalog_revision = ?, playable_state_namespace_id = ?, " - + "representation_version = 3, admission_state = 'OPEN', canonical_game_instance_id = ?, " - + "canonical_version_id = ?, runtime_version_id = ?, initial_admission_request_id = ?, " - + "initial_admission_request_digest = ?, initial_admission_origin_kind = ?, " - + "initial_admission_prior_pointer_version = ?, initial_admission_active_epoch = ?, " - + "initial_admission_hold_id = ?, initial_admission_hold_fence = ?, " - + "initial_admission_hold_binding_digest = ? " - + "WHERE representation_version = 2 AND target_namespace = ? " - + "AND canonical_tenant_id = ? AND realm_id = ? AND admission_state = 'CLOSED' " - + "AND pointer_version = ? AND catalog_revision = ? RETURNING id", - catalog.worldSlug(), - catalog.realmSlug(), - catalog.sourceIntakeReceipt().source().worldDisplayName(), - catalog.realmDisplayName(), - association.gameSessionTenantId(), - launchTarget.gameInstanceId(), - pointerVersion, - catalog.visible(), - catalog.stateScope(), - catalog.characterCreationPolicy(), - toLocalDateTime(updatedAt), - catalog.publicProduction(), - catalog.catalogRevision(), - catalog.playableStateNamespaceId(), - request.canonicalGameInstanceId(), - request.canonicalVersionId(), - launchTarget.runtimeVersionId(), - request.initialAdmissionRequestId(), - request.requestDigest(), - request.originKind().name(), - request.expectedPriorPointerVersion(), - request.activeLifecycleEpoch(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest(), - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.expectedPriorPointerVersion(), - request.expectedCatalogRevision()); - if (pointer == null || pointer.get("id", Long.class) == null) { - throw new CanonicalInitialAdmissionConflictException( - "Original CLOSED pointer changed before the initial OPEN CAS"); + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); } - return pointer.get("id", Long.class); } private void verifyCommittedReadback(Attempt attempt) { @@ -779,7 +415,7 @@ private void verifyCommittedReadback(Attempt attempt) { "Committed initial-admission pointer, audit, request and catalog readback disagree"); } if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { - verifyOriginalClosedOrigin(attempt, false); + verifyOriginalClosedOrigin(attempt); } String expectedProof = commitProofDigest( @@ -814,7 +450,7 @@ private void verifyAbortReadback(Attempt attempt) { // The ABORTED terminal result is historical. A later distinct request may legitimately open // this route; retain and verify the original CLOSED request/event without mistaking the later // OPEN row for the terminal result of this aborted request. - verifyOriginalClosedOrigin(attempt, false); + verifyOriginalClosedOrigin(attempt); } String expectedProof = abortProofDigest( @@ -830,7 +466,7 @@ private void verifyAbortReadback(Attempt attempt) { } } - private void verifyOriginalClosedOrigin(Attempt attempt, boolean requireCurrent) { + private void verifyOriginalClosedOrigin(Attempt attempt) { if (attempt.priorPointerRequestId() == null || attempt.priorPointerRequestDigest() == null || attempt.priorPointerAuditEventId() == null @@ -839,17 +475,12 @@ private void verifyOriginalClosedOrigin(Attempt attempt, boolean requireCurrent) "EXPECT_CLOSED terminal result has no exact original CLOSED origin identity"); } CanonicalClosedAdmissionPointerSnapshot origin = - (requireCurrent - ? pointerRepository.readByRequest( - attempt.targetNamespace(), attempt.priorPointerRequestId()) - : pointerRepository.readOriginalClosedOrigin( - attempt.targetNamespace(), attempt.priorPointerRequestId())) + pointerRepository + .readOriginalClosedOrigin(attempt.targetNamespace(), attempt.priorPointerRequestId()) .orElseThrow( () -> new CanonicalInitialAdmissionReconciliationRequiredException( - requireCurrent - ? "Original CLOSED route is no longer current owner authority" - : "Immutable original CLOSED request/event evidence is unavailable")); + "Immutable original CLOSED request/event evidence is unavailable")); if (!origin.canonicalTenantId().equals(attempt.canonicalTenantId()) || !origin.realmId().equals(attempt.realmId()) || !origin.requestDigest().equals(attempt.priorPointerRequestDigest()) @@ -893,47 +524,6 @@ private CanonicalRealmCatalogSnapshot readExactCatalog(CanonicalInitialAdmission return catalog; } - private CanonicalInitialAdmissionLaunchTarget readExactLaunchTarget( - CanonicalInitialAdmissionRequest request) { - CanonicalInitialAdmissionLaunchTarget target = - launchRepository - .readForInitialAdmission( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.canonicalGameInstanceId()) - .orElseThrow( - () -> - new CanonicalInitialAdmissionReconciliationRequiredException( - "Exact canonical launch association is unavailable for owner readback")); - requireRequestMatchesLaunch(request, target); - return target; - } - - private CanonicalRealmCatalogSnapshot lockCatalog(CanonicalInitialAdmissionRequest request) { - CanonicalRealmCatalogSnapshot catalog = - catalogRepository.lockInitialAdmissionTarget( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.expectedCatalogRevision()); - requireRequestMatchesCatalog(request, catalog); - return catalog; - } - - private CanonicalInitialAdmissionLaunchTarget lockLaunchTarget( - CanonicalInitialAdmissionRequest request, boolean requireRunning) { - CanonicalInitialAdmissionLaunchTarget launchTarget = - launchRepository.lockForInitialAdmission( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.canonicalGameInstanceId(), - requireRunning); - requireRequestMatchesLaunch(request, launchTarget); - return launchTarget; - } - private static void requireRequestMatchesCatalog( CanonicalInitialAdmissionRequest request, CanonicalRealmCatalogSnapshot catalog) { if (!request.targetNamespace().equals(catalog.targetNamespace()) @@ -950,130 +540,14 @@ private static void requireRequestMatchesCatalog( } } - private static void requireRequestMatchesLaunch( - CanonicalInitialAdmissionRequest request, - CanonicalInitialAdmissionLaunchTarget launchTarget) { - CanonicalGameInstanceLaunchAssociation association = launchTarget.association(); - if (!request.targetNamespace().equals(association.targetNamespace()) - || !request.canonicalTenantId().equals(association.canonicalTenantId()) - || !request.worldSlug().equals(association.worldSlug()) - || !request.realmId().equals(launchTarget.realmId()) - || !request.playableStateNamespaceId().equals(association.playableStateNamespaceId()) - || !request.playableStateScope().equals(association.playableStateScope().name()) - || !request.canonicalGameInstanceId().equals(association.gameInstanceUuid()) - || !request.canonicalVersionId().equals(launchTarget.canonicalVersionId()) - || !association.publicProduction()) { - throw new CanonicalInitialAdmissionReconciliationRequiredException( - "Canonical launch association does not match the exact initial-admission target tuple"); - } - } - - private static void requireRequestMatchesCatalogAndLaunch( - CanonicalInitialAdmissionRequest request, - CanonicalRealmCatalogSnapshot catalog, - CanonicalInitialAdmissionLaunchTarget launchTarget) { - requireRequestMatchesCatalog(request, catalog); - requireRequestMatchesLaunch(request, launchTarget); - } - - private void lockTarget(CanonicalInitialAdmissionRequest request) { - dsl.fetchOne( - "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ? || ':' || ?, 0))", - request.targetNamespace(), - request.canonicalTenantId().toString(), - request.realmId().toString()); - } - - /** - * Existing pointer and legacy writers do not participate in this canonical target lock. Briefly - * excluding every representation table closes the otherwise-open absence-check gap; V9 numeric - * identifiers are used only to find collisions, never as canonical proof. - */ - private void lockAllAdmissionRepresentationsForNoPrior() { - dsl.execute( - "LOCK TABLE gameplay_admission_pointer, gameplay_admission_pointer_event, " - + "game_session_canonical_closed_admission_pointer_request, " - + "gameplay_initial_admission_bind_catalog, gameplay_initial_admission_bind_attempt " - + "IN SHARE ROW EXCLUSIVE MODE"); - } - - private Attempt requireAttemptForUpdate(CanonicalInitialAdmissionRequest request) { - Attempt attempt = - findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); - if (attempt == null) { - throw new CanonicalInitialAdmissionReconciliationRequiredException( - "Initial-admission request was not durably reserved before owner proof or commit"); - } - return attempt; - } - - private void requireSameRequest( - Attempt attempt, - CanonicalInitialAdmissionRequest request, - CanonicalInitialAdmissionLaunchTarget launchTarget) { - requireSameRequestIdentity(attempt, request); - if (attempt.runtimeVersionId() != launchTarget.runtimeVersionId() - || attempt.gameSessionTenantId() != launchTarget.association().gameSessionTenantId() - || attempt.gameInstanceId() != launchTarget.gameInstanceId()) { - throw new CanonicalInitialAdmissionConflictException( - "Initial-admission request identity was reused with a changed canonical tuple or digest"); - } - } - - private void requireSameRequestIdentity( - Attempt attempt, CanonicalInitialAdmissionRequest request) { - if (!attempt.targetNamespace().equals(request.targetNamespace()) - || !attempt.initialAdmissionRequestId().equals(request.initialAdmissionRequestId()) - || !attempt.requestDigest().equals(request.requestDigest()) - || !attempt.canonicalTenantId().equals(request.canonicalTenantId()) - || !attempt.worldSlug().equals(request.worldSlug()) - || !attempt.realmId().equals(request.realmId()) - || !attempt.playableStateNamespaceId().equals(request.playableStateNamespaceId()) - || !attempt.playableStateScope().equals(request.playableStateScope()) - || !attempt.canonicalGameInstanceId().equals(request.canonicalGameInstanceId()) - || !attempt.canonicalVersionId().equals(request.canonicalVersionId()) - || !attempt.holdBindingDigest().equals(request.holdBindingDigest()) - || attempt.expectedCatalogRevision() != request.expectedCatalogRevision() - || attempt.originKind() != request.originKind() - || !Objects.equals( - attempt.expectedPriorPointerVersion(), request.expectedPriorPointerVersion()) - || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() - || !attempt.holdId().equals(request.holdId()) - || !attempt.holdFence().equals(request.holdFence())) { - throw new CanonicalInitialAdmissionConflictException( - "Initial-admission request identity was reused with a changed canonical tuple or digest"); - } - } - - private Attempt findPendingForRealm(CanonicalInitialAdmissionRequest request, boolean forUpdate) { - String sql = - "SELECT * FROM " - + OPERATION_TABLE - + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " - + "AND status = 'PENDING'" - + (forUpdate ? " FOR UPDATE" : ""); - return Optional.ofNullable( - dsl.fetchOne( - sql, request.targetNamespace(), request.canonicalTenantId(), request.realmId())) - .map(CanonicalInitialAdmissionRepository::toAttempt) - .orElse(null); - } - - private Attempt findAttempt(String targetNamespace, String requestId, boolean forUpdate) { - return Optional.ofNullable(findAttemptRecord(targetNamespace, requestId, forUpdate)) - .map(CanonicalInitialAdmissionRepository::toAttempt) - .orElse(null); - } - - private Record findAttemptRecord(String targetNamespace, String requestId, boolean forUpdate) { + private Record findAttemptRecord(String targetNamespace, String requestId) { if (targetNamespace == null || requestId == null || requestId.isBlank()) { throw new IllegalArgumentException("Initial-admission read selector is incomplete"); } return dsl.fetchOne( "SELECT * FROM " + OPERATION_TABLE - + " WHERE target_namespace = ? AND initial_admission_request_id = ?" - + (forUpdate ? " FOR UPDATE" : ""), + + " WHERE target_namespace = ? AND initial_admission_request_id = ?", targetNamespace, requestId); } @@ -1237,45 +711,6 @@ private static String digest(List fields) { } } - private static Instant nextTimestamp(Instant previous) { - Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); - if (previous != null && !now.isAfter(previous)) { - return previous.plus(1, ChronoUnit.MICROS); - } - return now; - } - - private static OffsetDateTime utc(Instant instant) { - return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); - } - - private void requireWritableReadCommittedOwnerTransaction() { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw new IllegalStateException( - "Canonical initial-admission owner mutation requires a writable transaction"); - } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Canonical initial-admission owner mutation requires READ COMMITTED isolation"); - } - return null; - }); - Record isolation = - dsl.fetchOne( - "SELECT current_setting('transaction_isolation') AS isolation, " - + "current_setting('transaction_read_only') AS read_only"); - if (isolation == null - || !"read committed".equals(isolation.get("isolation", String.class)) - || !"off".equals(isolation.get("read_only", String.class))) { - throw new IllegalStateException( - "Canonical initial-admission owner mutation requires writable READ COMMITTED isolation"); - } - } - private static void requireOutsideTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java new file mode 100644 index 0000000000..6c37a0458d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java @@ -0,0 +1,545 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.FixtureCanonicalRealmCatalog; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Fixture allocation on the canonical Game Session launch owner; Human owners remain separate. */ +public final class GameSessionCanonicalInstanceLaunchRepository { + private static final ObjectMapper JSON = + new ObjectMapper().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final String workloadNamespace; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + public GameSessionCanonicalInstanceLaunchRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + String workloadNamespace, + GameSessionCanonicalRealmCatalogRepository catalogRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is missing or invalid"); + } + this.workloadNamespace = workloadNamespace; + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.writeTransaction = new TransactionTemplate(transactionManager); + this.writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.readTransaction = new TransactionTemplate(transactionManager); + this.readTransaction.setReadOnly(true); + this.readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** + * Fixture-only typed input. Raw wire records and unchecked projections cannot call this owner. + */ + public FixtureCanonicalInstanceLaunch createVerifiedFixtureStartingLaunch( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireNoActiveOwnerTransaction(); + evidence.requireVerifiedFixture(); + if (!workloadNamespace.equals(evidence.sourceEvidence().targetNamespace())) { + throw new InvalidCanonicalInstanceLaunchException( + "Fixture source differs from configured launch owner"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = fixtureDescriptor(evidence); + FixtureCanonicalRealmCatalog catalog = + catalogRepository.establishVerifiedFixtureRealm(evidence); + FixtureCanonicalInstanceLaunch committed = + writeTransaction.execute( + status -> { + requireOwnerTransaction(); + dsl.execute( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "canonical-launch:" + + workloadNamespace + + ":" + + descriptor.controlPlaneRequestId()); + FixtureCanonicalRealmCatalog actual = + catalogRepository.readVerifiedFixtureRealmInOwnerTransaction(evidence); + if (!catalog.equals(actual)) { + throw new InvalidCanonicalInstanceLaunchException( + "Fixture catalog changed before STARTING"); + } + Record existing = + readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), true); + if (existing != null) return readFixtureLaunch(existing, evidence, actual, false); + if (dsl.fetchOne( + "SELECT id FROM game_instances WHERE tenant_id = ? AND run_owned_start_request_id = ? FOR UPDATE", + actual.association().gameSessionTenantId(), + descriptor.controlPlaneRequestId()) + != null) { + throw new InvalidCanonicalInstanceLaunchException( + "Runtime identity has no exact immutable fixture association"); + } + UUID instanceUuid = newNonNilUuid(); + Record runtime = + dsl.fetchOne( + "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, status, row_version," + + " game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id," + + " generation_config_revision, version_state_epoch, run_owned_start_request_id," + + " run_owned_start_request_digest, run_owned_start_published_release_bundle_ref)" + + " VALUES (?, ?, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + actual.association().gameSessionTenantId(), + Long.toString(descriptor.versionId()), + evidence.fixtureCapability().ownerAccountId(), + instanceUuid, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + descriptor.controlPlaneRequestId(), + evidence.fixtureRuntimeRequestDigest(), + descriptor.publishedReleaseBundleRef()); + long instanceId = required(runtime, "id", Long.class); + insertFixtureAssociation(evidence, descriptor, actual, instanceId, instanceUuid); + return readFixtureLaunch( + readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), false), + evidence, + actual, + true); + }); + Objects.requireNonNull(committed, "Fixture launch transaction returned no result"); + FixtureCanonicalInstanceLaunch independent = readVerifiedFixtureLaunch(evidence); + if (independent.gameInstanceId() != committed.gameInstanceId() + || !independent.gameInstanceUuid().equals(committed.gameInstanceUuid())) { + throw new InvalidCanonicalInstanceLaunchException( + "Fixture launch independent readback changed allocation"); + } + return independent; + } + + public FixtureCanonicalInstanceLaunch readVerifiedFixtureLaunch( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireNoActiveOwnerTransaction(); + evidence.requireVerifiedFixture(); + return Objects.requireNonNull( + readTransaction.execute( + status -> + readFixtureLaunch( + readLaunchRowByOperationInTransaction( + evidence.fixtureCapability().operationId(), false), + evidence, + catalogRepository.readVerifiedFixtureRealmInOwnerTransaction(evidence), + false)), + "Fixture launch independent read returned no result"); + } + + /** + * Locks and revalidates the exact fixture catalog, launch association, and live runtime row in + * the caller's canonical initial-admission owner transaction. + * + *

The public result record is not authority. Only the immutable verified receipt and this + * owner-transaction read can produce the target used by a fixture intent or terminal write. + */ + public FixtureCanonicalInstanceLaunch lockVerifiedFixtureLaunchInOwnerTransaction( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireOwnerTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Fixture initial-admission source lock requires a writable owner transaction"); + } + Objects.requireNonNull(evidence, "evidence").requireVerifiedFixture(); + var descriptor = fixtureDescriptor(evidence); + if (!workloadNamespace.equals(evidence.sourceEvidence().targetNamespace())) { + throw new InvalidCanonicalInstanceLaunchException( + "Fixture source differs from the configured launch owner"); + } + + Record lockedCatalog = + dsl.fetchOne( + "SELECT realm_id FROM game_session_canonical_realm_catalog " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + workloadNamespace, + evidence.sourceEvidence().canonicalTenantId(), + catalogRepository + .readVerifiedFixtureRealmInOwnerTransaction(evidence) + .snapshot() + .realmId()); + if (lockedCatalog == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Exact fixture catalog row is unavailable for initial-admission locking"); + } + + Record launch = readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), true); + if (launch == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Exact fixture launch association is unavailable for initial-admission locking"); + } + long tenantId = required(launch, "game_session_tenant_id", Long.class); + long instanceId = required(launch, "game_instance_id", Long.class); + UUID instanceUuid = required(launch, "game_instance_uuid", UUID.class); + Record runtimeLock = + dsl.fetchOne( + "SELECT id FROM game_instances " + + "WHERE tenant_id = ? AND id = ? AND game_instance_uuid = ? FOR UPDATE", + tenantId, + instanceId, + instanceUuid); + if (runtimeLock == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Exact fixture runtime allocation is unavailable for initial-admission locking"); + } + + Record current = + readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), false); + FixtureCanonicalRealmCatalog catalog = + catalogRepository.readVerifiedFixtureRealmInOwnerTransaction(evidence); + return readFixtureLaunch(current, evidence, catalog, false); + } + + private static AuthoredWorldLaunchDescriptorEvidence fixtureDescriptor( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + evidence.requireVerifiedFixture(); + var source = evidence.sourceEvidence(); + var cap = evidence.fixtureCapability(); + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + source.targetNamespace(), + cap.operationId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + cap.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + request, evidence.launchDescriptor()); + } + + private String fixtureBindingJson(RunOwnedInitialAdmissionLaunchEvidence evidence) { + try { + return JSON.writeValueAsString( + Map.of( + "descriptor", + fixtureDescriptor(evidence), + "fixturePolicySeal", + evidence.fixturePolicySeal())); + } catch (JsonProcessingException invalid) { + throw new InvalidCanonicalInstanceLaunchException( + "Fixture binding cannot be retained", invalid); + } + } + + private void insertFixtureAssociation( + RunOwnedInitialAdmissionLaunchEvidence evidence, + AuthoredWorldLaunchDescriptorEvidence descriptor, + FixtureCanonicalRealmCatalog catalog, + long instanceId, + UUID instanceUuid) { + var association = catalog.association(); + var fresh = association.sourceEvidence(); + var realm = catalog.snapshot(); + var seal = evidence.fixturePolicySeal(); + requireOne( + dsl.execute( + "INSERT INTO game_session_canonical_instance_launch" + + " (target_namespace, control_plane_request_id, game_session_tenant_id, canonical_tenant_id," + + " tenant_association_operation_id, tenant_association_request_id, tenant_source_schema_version," + + " tenant_source_target_namespace, tenant_source_request_id, tenant_source_canonical_tenant_id," + + " tenant_source_game_row_id, tenant_source_game_tenant_key, tenant_source_provenance_kind," + + " tenant_association_kind, game_instance_id, game_instance_uuid, canonical_realm_id, world_slug," + + " playable_state_namespace_id, playable_state_scope, public_production, captured_starting_row_version," + + " game_template_id, launch_descriptor_id, version_id, release_bundle_id, generation_config_revision," + + " version_state_epoch, complete_launch_binding_evidence, catalog_creation_request_id, catalog_revision," + + " catalog_source_intake_operation_id, catalog_source_intake_request_id, fixture_policy_request_bytes," + + " fixture_policy_seal_operation_id, fixture_policy_seal_request_digest, fixture_policy_seal_evidence_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, 'SHARED', TRUE," + + " 0, ?, ?, ?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, ?, ?, ?, ?)", + workloadNamespace, + descriptor.controlPlaneRequestId(), + association.gameSessionTenantId(), + fresh.canonicalTenantId(), + association.associationOperationId(), + fresh.creationRequestId(), + fresh.schemaVersion(), + fresh.targetNamespace(), + fresh.creationRequestId(), + fresh.canonicalTenantId(), + fresh.sourceGameRowId(), + fresh.sourceGameTenantKey(), + fresh.provenanceKind(), + instanceId, + instanceUuid, + realm.realmId(), + realm.worldSlug(), + realm.playableStateNamespaceId(), + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + fixtureBindingJson(evidence), + realm.creationRequestId(), + realm.catalogRevision(), + realm.sourceIntakeReceipt().operationId(), + realm.sourceIntakeReceipt().intakeRequestId(), + evidence.fixturePolicyRequestBytes(), + seal.operationId(), + seal.requestDigest(), + seal.evidenceDigest()), + "fixture canonical launch association"); + } + + private FixtureCanonicalInstanceLaunch readFixtureLaunch( + Record row, + RunOwnedInitialAdmissionLaunchEvidence evidence, + FixtureCanonicalRealmCatalog catalog, + boolean starting) { + evidence.requireVerifiedFixture(); + var descriptor = fixtureDescriptor(evidence); + var realm = catalog.snapshot(); + var association = catalog.association(); + var fresh = evidence.creationEvidence(); + var seal = evidence.fixturePolicySeal(); + if (row == null + || row.get("original_start_session_tuple", byte[].class) != null + || !Arrays.equals( + evidence.fixturePolicyRequestBytes(), + row.get("fixture_policy_request_bytes", byte[].class)) + || !seal.operationId().equals(row.get("fixture_policy_seal_operation_id", UUID.class)) + || !seal.requestDigest().equals(row.get("fixture_policy_seal_request_digest", String.class)) + || !seal.evidenceDigest() + .equals(row.get("fixture_policy_seal_evidence_digest", String.class)) + || !workloadNamespace.equals(row.get("target_namespace", String.class)) + || !descriptor + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || association.gameSessionTenantId() != required(row, "game_session_tenant_id", Long.class) + || !fresh.canonicalTenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || !association + .associationOperationId() + .equals(row.get("tenant_association_operation_id", UUID.class)) + || !fresh.creationRequestId().equals(row.get("tenant_association_request_id", UUID.class)) + || fresh.schemaVersion() != required(row, "tenant_source_schema_version", Integer.class) + || !fresh.targetNamespace().equals(row.get("tenant_source_target_namespace", String.class)) + || !fresh.creationRequestId().equals(row.get("tenant_source_request_id", UUID.class)) + || !fresh + .canonicalTenantId() + .equals(row.get("tenant_source_canonical_tenant_id", UUID.class)) + || fresh.sourceGameRowId() != required(row, "tenant_source_game_row_id", Long.class) + || !fresh + .sourceGameTenantKey() + .equals(row.get("tenant_source_game_tenant_key", String.class)) + || !fresh.provenanceKind().equals(row.get("tenant_source_provenance_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class)) + || !realm.realmId().equals(row.get("canonical_realm_id", UUID.class)) + || !realm + .playableStateNamespaceId() + .equals(row.get("playable_state_namespace_id", UUID.class)) + || !realm.worldSlug().equals(row.get("world_slug", String.class)) + || !"SHARED".equals(row.get("playable_state_scope", String.class)) + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class)) + || !realm.creationRequestId().equals(row.get("catalog_creation_request_id", UUID.class)) + || realm.catalogRevision() != required(row, "catalog_revision", Long.class) + || !realm + .sourceIntakeReceipt() + .operationId() + .equals(row.get("catalog_source_intake_operation_id", UUID.class)) + || !realm + .sourceIntakeReceipt() + .intakeRequestId() + .equals(row.get("catalog_source_intake_request_id", UUID.class)) + || !sameJson( + fixtureBindingJson(evidence), + required(row, "gs_complete_launch_binding_json", String.class)) + || !evidence + .fixtureRuntimeRequestDigest() + .equals(row.get("gs_runtime_request_digest", String.class)) + || descriptor.gameTemplateId() != required(row, "game_template_id", Long.class) + || !descriptor.launchDescriptorId().equals(row.get("launch_descriptor_id", String.class)) + || descriptor.versionId() != required(row, "version_id", Long.class) + || descriptor.releaseBundleId() != required(row, "release_bundle_id", Long.class) + || !descriptor + .generationConfigRevision() + .equals(row.get("generation_config_revision", String.class)) + || descriptor.versionStateEpoch() != required(row, "version_state_epoch", Long.class)) { + throw new InvalidCanonicalInstanceLaunchException( + "Retained launch is not this exact verified fixture provenance"); + } + UUID instanceUuid = required(row, "game_instance_uuid", UUID.class); + long captured = required(row, "captured_starting_row_version", Long.class); + long currentVersion = required(row, "gs_current_row_version", Long.class); + var status = parseStatus(required(row, "gs_current_status", String.class)); + if (!instanceUuid.equals(row.get("gs_runtime_instance_uuid", UUID.class)) + || association.gameSessionTenantId() != required(row, "gs_runtime_tenant_id", Long.class) + || evidence.fixtureCapability().ownerAccountId() + != required(row, "gs_runtime_owner_account_id", Long.class) + || descriptor.gameTemplateId() != required(row, "gs_runtime_game_template_id", Long.class) + || !descriptor + .launchDescriptorId() + .equals(row.get("gs_runtime_launch_descriptor_id", String.class)) + || descriptor.versionId() != required(row, "gs_runtime_version_id", Long.class) + || descriptor.releaseBundleId() != required(row, "gs_runtime_release_bundle_id", Long.class) + || !descriptor + .generationConfigRevision() + .equals(row.get("gs_runtime_generation_config_revision", String.class)) + || descriptor.versionStateEpoch() + != required(row, "gs_runtime_version_state_epoch", Long.class) + || !descriptor + .controlPlaneRequestId() + .equals(row.get("gs_runtime_request_id", String.class)) + || !descriptor + .publishedReleaseBundleRef() + .equals(row.get("gs_runtime_release_ref", String.class)) + || currentVersion < captured + || captured != 0L + || (starting + && (currentVersion != captured + || status + != CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING))) { + throw new InvalidCanonicalInstanceLaunchException( + "Fixture association differs from actual runtime owner row"); + } + return new FixtureCanonicalInstanceLaunch( + required(row, "game_instance_id", Long.class), + instanceUuid, + catalog, + status, + currentVersion); + } + + private static boolean sameJson(String left, String right) { + try { + return JSON.readTree(left).equals(JSON.readTree(right)); + } catch (JsonProcessingException invalid) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored fixture JSON is malformed", invalid); + } + } + + public record FixtureCanonicalInstanceLaunch( + long gameInstanceId, + UUID gameInstanceUuid, + FixtureCanonicalRealmCatalog catalog, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus status, + long rowVersion) {} + + private Record readLaunchRowByOperationInTransaction( + String controlPlaneRequestId, boolean forUpdate) { + requireOwnerTransaction(); + String suffix = forUpdate ? " FOR UPDATE OF launch" : ""; + return dsl.fetchOne( + "SELECT launch.*, runtime.status AS gs_current_status," + + " runtime.row_version AS gs_current_row_version," + + " runtime.game_instance_uuid AS gs_runtime_instance_uuid," + + " runtime.tenant_id AS gs_runtime_tenant_id," + + " runtime.runtime_version AS gs_runtime_version," + + " runtime.owner_account_uuid AS gs_runtime_owner_account_uuid," + + " runtime.owner_account_id AS gs_runtime_owner_account_id," + + " runtime.game_template_id AS gs_runtime_game_template_id," + + " runtime.launch_descriptor_id AS gs_runtime_launch_descriptor_id," + + " runtime.version_id AS gs_runtime_version_id," + + " runtime.release_bundle_id AS gs_runtime_release_bundle_id," + + " runtime.generation_config_revision AS gs_runtime_generation_config_revision," + + " runtime.version_state_epoch AS gs_runtime_version_state_epoch," + + " runtime.run_owned_start_request_id AS gs_runtime_request_id," + + " runtime.run_owned_start_request_digest AS gs_runtime_request_digest," + + " runtime.run_owned_start_published_release_bundle_ref AS gs_runtime_release_ref," + + " launch.complete_launch_binding_evidence::text AS gs_complete_launch_binding_json" + + " FROM game_session_canonical_instance_launch launch" + + " LEFT JOIN game_instances runtime" + + " ON runtime.tenant_id = launch.game_session_tenant_id" + + " AND runtime.id = launch.game_instance_id" + + " AND runtime.game_instance_uuid = launch.game_instance_uuid" + + " WHERE launch.target_namespace = ? AND launch.control_plane_request_id = ?" + + suffix, + workloadNamespace, + controlPlaneRequestId); + } + + private static CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + parseStatus(String value) { + try { + return CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.valueOf( + value); + } catch (IllegalArgumentException unknown) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored Game Instance has an unsupported current lifecycle status", unknown); + } + } + + private static UUID newNonNilUuid() { + UUID value = UUID.randomUUID(); + if (NIL_UUID.equals(value)) { + throw new IllegalStateException("Game Session UUID allocator returned nil"); + } + return value; + } + + private static void requireNoActiveOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical launch owner operation requires its own independent transaction"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session canonical launch storage access requires an active owner transaction"); + } + } + + private static T required(Record row, String field, Class type) { + if (row == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Game Session canonical launch storage returned no row"); + } + T value = row.get(field, type); + if (value == null) { + throw new InvalidCanonicalInstanceLaunchException( + "Stored canonical launch is missing required evidence: " + field); + } + return value; + } + + private static void requireOne(int affectedRows, String label) { + if (affectedRows != 1) { + throw new InvalidCanonicalInstanceLaunchException( + "Game Session " + label + " insert did not affect exactly one row"); + } + } + + public static final class InvalidCanonicalInstanceLaunchException extends IllegalStateException { + public InvalidCanonicalInstanceLaunchException(String message) { + super(message); + } + + public InvalidCanonicalInstanceLaunchException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index b82f5c4a4b..d09ee159b1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -9,24 +9,37 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; +import java.util.Arrays; import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.Record; import org.jooq.Table; import org.jooq.impl.DSL; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; /** * Game Session-owned immutable initial realm catalog creation and exact readback. @@ -115,6 +128,9 @@ public class GameSessionCanonicalRealmCatalogRepository { "Fail-fast validation is local; no overridable callback or partially initialized object escapes.") public GameSessionCanonicalRealmCatalogRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.workloadNamespace = null; + this.writeTransaction = null; + this.readTransaction = null; } /** @@ -124,7 +140,8 @@ public GameSessionCanonicalRealmCatalogRepository(DSLContext dsl) { */ @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) public PreparedInitialPublicProduction prepareInitialPublicProduction( - CreateCanonicalRealmCatalogRequest request) { + CreateCanonicalRealmCatalogRequest request, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { Objects.requireNonNull(request, "request"); requireCommittedRead(); Record binding = @@ -152,7 +169,12 @@ public PreparedInitialPublicProduction prepareInitialPublicProduction( requireRequestMatchesSource(request, committedSource); requireFreshSource(committedSource.source()); requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); - return new PreparedInitialPublicProduction(request, committedSource); + byte[] policyBytes = + RealmPolicyPublishedEvidenceCodec.encode( + Objects.requireNonNull(publishedSet, "publishedSet")); + validateCompleteCatalogPolicy(request, committedSource, publishedSet); + verifyStoredFreshAssociation(committedSource.source(), request.canonicalTenantId()); + return new PreparedInitialPublicProduction(request, committedSource, publishedSet, policyBytes); } /** @@ -167,6 +189,8 @@ public CanonicalRealmCatalogSnapshot createInitialPublicProduction( requireWritableOwnerTransaction(); IntakeReceipt sourceReceipt = lockAndReadFreshSource(request); + validatePreparedPolicy(request, sourceReceipt, prepared.policyEvidence); + verifyStoredFreshAssociation(sourceReceipt.source(), request.canonicalTenantId()); if (!prepared.committedSource().equals(sourceReceipt)) { throw new InvalidCatalogEvidenceException( "Committed authored-world evidence changed before canonical catalog creation"); @@ -177,7 +201,8 @@ public CanonicalRealmCatalogSnapshot createInitialPublicProduction( dsl.execute("LOCK TABLE gameplay_tenant_shared_playable_state_namespace IN ROW EXCLUSIVE MODE"); requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); - String requestDigest = requestDigest(request, sourceReceipt); + String requestDigest = + completeCatalogRequestDigest(requestDigest(request, sourceReceipt), prepared.policyBytes); Record existing = findByRequest(request.targetNamespace(), request.requestId()); if (existing != null) { return requireExactRetry(existing, request, sourceReceipt, requestDigest); @@ -234,6 +259,27 @@ public CanonicalRealmCatalogSnapshot createInitialPublicProduction( .set(SOURCE_GAME_TENANT_KEY, sourceReceipt.source().sourceGameTenantKey()) .set(SOURCE_PROVENANCE_KIND, sourceReceipt.source().provenanceKind()) .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.source().evidenceDigest()) + .set( + DSL.field(DSL.name("complete_policy_set_evidence"), byte[].class), + prepared.policyEvidence instanceof HumanPolicy ? prepared.policyBytes : null) + .set( + DSL.field(DSL.name("fixture_policy_request_bytes"), byte[].class), + prepared.policyEvidence instanceof FixturePolicy ? prepared.policyBytes : null) + .set( + DSL.field(DSL.name("fixture_policy_seal_operation_id"), UUID.class), + prepared.policyEvidence instanceof FixturePolicy fixture + ? fixture.evidence().fixturePolicySeal().operationId() + : null) + .set( + DSL.field(DSL.name("fixture_policy_seal_request_digest"), String.class), + prepared.policyEvidence instanceof FixturePolicy fixture + ? fixture.evidence().fixturePolicySeal().requestDigest() + : null) + .set( + DSL.field(DSL.name("fixture_policy_seal_evidence_digest"), String.class), + prepared.policyEvidence instanceof FixturePolicy fixture + ? fixture.evidence().fixturePolicySeal().evidenceDigest() + : null) .onConflictDoNothing() .execute(); @@ -410,7 +456,21 @@ public List readVisiblePublicProductionSnapshots( } requireCommittedRead(); return dsl.selectFrom(CATALOG) - .where(TARGET_NAMESPACE.eq(targetNamespace).and(PUBLIC_PRODUCTION.isTrue())) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(PUBLIC_PRODUCTION.isTrue()) + // V23/V25 history has no policy provenance and is not current authority. + // Keep every evidence-bearing or partial candidate for strict validation. + .and( + DSL.field(DSL.name("complete_policy_set_evidence")) + .isNotNull() + .or(DSL.field(DSL.name("fixture_policy_request_bytes")).isNotNull()) + .or(DSL.field(DSL.name("fixture_policy_seal_operation_id")).isNotNull()) + .or(DSL.field(DSL.name("fixture_policy_seal_request_digest")).isNotNull()) + .or( + DSL.field(DSL.name("fixture_policy_seal_evidence_digest")) + .isNotNull()))) .orderBy(CANONICAL_TENANT_ID.asc(), REALM_ID.asc()) .fetch() .map(this::toSnapshot); @@ -654,6 +714,34 @@ private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { stateScope, characterCreationPolicy, sourceReceipt); + CreateCanonicalRealmCatalogRequest storedRequest = + new CreateCanonicalRealmCatalogRequest( + requestId, + targetNamespace, + canonicalTenantId, + sourceIntakeOperationId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + characterCreationPolicy, + null, + null); + byte[] policyBytes = record.get("complete_policy_set_evidence", byte[].class); + byte[] fixtureBytes = record.get("fixture_policy_request_bytes", byte[].class); + if (policyBytes != null && fixtureBytes == null) { + validateCompleteCatalogPolicy( + storedRequest, sourceReceipt, RealmPolicyPublishedEvidenceCodec.decode(policyBytes)); + } else if (policyBytes == null && fixtureBytes != null) { + validateRetainedFixturePolicy(record, storedRequest, sourceReceipt, fixtureBytes); + policyBytes = fixtureBytes; + } else { + throw new InvalidCatalogEvidenceException( + "Exactly one complete catalog policy provenance required"); + } + verifyStoredFreshAssociation(sourceReceipt.source(), canonicalTenantId); + expectedRequestDigest = completeCatalogRequestDigest(expectedRequestDigest, policyBytes); String persistedRequestDigest = required(record, REQUEST_DIGEST, "catalog request digest"); UUID realmId = required(record, REALM_ID, "catalog realm id"); UUID namespaceId = @@ -1112,11 +1200,26 @@ private static T required(Record record, Field field, String label) { public static final class PreparedInitialPublicProduction { private final CreateCanonicalRealmCatalogRequest request; private final IntakeReceipt committedSource; + private final PolicyEvidence policyEvidence; + private final byte[] policyBytes; + + private PreparedInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt committedSource, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + byte[] policyBytes) { + this(request, committedSource, new HumanPolicy(publishedSet), policyBytes); + } private PreparedInitialPublicProduction( - CreateCanonicalRealmCatalogRequest request, IntakeReceipt committedSource) { + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt committedSource, + PolicyEvidence policyEvidence, + byte[] policyBytes) { this.request = Objects.requireNonNull(request, "request"); this.committedSource = Objects.requireNonNull(committedSource, "committedSource"); + this.policyEvidence = Objects.requireNonNull(policyEvidence, "policyEvidence"); + this.policyBytes = policyBytes.clone(); } private CreateCanonicalRealmCatalogRequest request() { @@ -1143,4 +1246,345 @@ public InvalidCatalogEvidenceException(String message, Throwable cause) { super(message, cause); } } + + private sealed interface PolicyEvidence permits HumanPolicy, FixturePolicy {} + + private record HumanPolicy(RealmPolicyPublishedEvidence.PublishedSet publishedSet) + implements PolicyEvidence { + private HumanPolicy { + Objects.requireNonNull(publishedSet); + } + } + + private record FixturePolicy(RunOwnedInitialAdmissionLaunchEvidence evidence) + implements PolicyEvidence { + private FixturePolicy { + evidence.requireVerifiedFixture(); + } + } + + private void validatePreparedPolicy( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt source, PolicyEvidence evidence) { + switch (evidence) { + case HumanPolicy human -> + validateCompleteCatalogPolicy(request, source, human.publishedSet()); + case FixturePolicy fixture -> { + fixture.evidence().requireVerifiedFixture(); + if (!source.source().equals(fixture.evidence().sourceEvidence())) { + throw new InvalidCatalogEvidenceException("Fixture authored-source receipt changed"); + } + validateFixtureCatalogFacts( + request, source.source(), fixture.evidence().fixtureCapability()); + } + } + } + + private static void validateFixtureCatalogFacts( + CreateCanonicalRealmCatalogRequest request, + AuthoredWorldSourceEvidence source, + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { + if (!request.targetNamespace().equals(source.targetNamespace()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.realmSlug().equals(capability.realmSlug()) + || !request.realmDisplayName().equals(capability.realmDisplayName()) + || request.visible() != capability.visible() + || request.publicProduction() != capability.publicProductionRealm() + || !request.stateScope().equals(capability.stateScope()) + || !request.characterCreationPolicy().equals(capability.characterCreationPolicy()) + || !source.worldSlug().equals(capability.worldSlug()) + || !source.worldDisplayName().equals(capability.worldDisplayName()) + || !source.sourceGameTenantKey().equals(Long.toString(capability.tenantId()))) { + throw new InvalidCatalogEvidenceException( + "Catalog differs from exact sealed fixture policy/source"); + } + } + + private void validateRetainedFixturePolicy( + Record row, + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt source, + byte[] requestBytes) { + var retained = + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(requestBytes); + if (!Arrays.equals( + requestBytes, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + retained.capability(), + retained.creationEvidence(), + retained.sourceEvidence(), + retained.launchReadEvidence())) + || !source.source().equals(retained.sourceEvidence()) + || !verifyStoredFreshAssociation(source.source(), request.canonicalTenantId()) + .sourceEvidence() + .equals(retained.creationEvidence())) { + throw new InvalidCatalogEvidenceException( + "Stored fixture policy differs from exact source/creation bytes"); + } + validateFixtureCatalogFacts(request, source.source(), retained.capability()); + String digest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + retained.capability(), + retained.creationEvidence(), + retained.sourceEvidence(), + retained.launchReadEvidence()); + UUID sealOperation = required(row, "fixture_policy_seal_operation_id", UUID.class); + if (!UUID.fromString(retained.capability().operationId()).equals(sealOperation) + || !digest.equals(required(row, "fixture_policy_seal_request_digest", String.class)) + || !RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + sealOperation, digest) + .equals(required(row, "fixture_policy_seal_evidence_digest", String.class))) { + throw new InvalidCatalogEvidenceException( + "Stored fixture policy seal failed independent exact readback"); + } + } + + /** Retains the trusted fixture policy in this catalog owner; it grants no Human authority. */ + public FixtureCanonicalRealmCatalog establishVerifiedFixtureRealm( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireFixtureComposition(); + requireNoActiveOwnerTransaction(); + evidence.requireVerifiedFixture(); + if (!workloadNamespace.equals(evidence.sourceEvidence().targetNamespace())) { + throw new InvalidCatalogEvidenceException( + "Fixture source differs from configured owner namespace"); + } + CanonicalRealmCatalogSnapshot committed = + writeTransaction.execute( + status -> { + FreshTenantAssociation association = + new GameSessionFreshTenantAssociationRepository(dsl) + .associateVerifiedFixtureInOwnerTransaction(evidence); + UUID requestId = UUID.fromString(evidence.fixtureCapability().operationId()); + IntakeReceipt intake = + new GameSessionAuthoredWorldSourceRepository(dsl) + .register(requestId, evidence.sourceEvidence()); + var cap = evidence.fixtureCapability(); + var request = + new CreateCanonicalRealmCatalogRequest( + requestId, + workloadNamespace, + association.canonicalTenantId(), + intake.operationId(), + cap.realmSlug(), + cap.realmDisplayName(), + cap.visible(), + cap.publicProductionRealm(), + cap.stateScope(), + cap.characterCreationPolicy(), + null, + null); + return createInitialPublicProduction( + new PreparedInitialPublicProduction( + request, + intake, + new FixturePolicy(evidence), + evidence.fixturePolicyRequestBytes())); + }); + Objects.requireNonNull(committed, "Fixture catalog owner returned no committed result"); + return readVerifiedFixtureRealm(evidence); + } + + public FixtureCanonicalRealmCatalog readVerifiedFixtureRealm( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireFixtureComposition(); + requireNoActiveOwnerTransaction(); + evidence.requireVerifiedFixture(); + FixtureCanonicalRealmCatalog readback = + readTransaction.execute(status -> readVerifiedFixtureRealmInOwnerTransaction(evidence)); + return Objects.requireNonNull(readback, "Fixture catalog owner read returned no result"); + } + + FixtureCanonicalRealmCatalog readVerifiedFixtureRealmInOwnerTransaction( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireOwnerTransaction(); + evidence.requireVerifiedFixture(); + Record row = + findPublicForTenant(workloadNamespace, evidence.sourceEvidence().canonicalTenantId()); + if (row == null + || row.get("complete_policy_set_evidence", byte[].class) != null + || !Arrays.equals( + evidence.fixturePolicyRequestBytes(), + row.get("fixture_policy_request_bytes", byte[].class)) + || !evidence + .fixturePolicySeal() + .operationId() + .equals(row.get("fixture_policy_seal_operation_id", UUID.class)) + || !evidence + .fixturePolicySeal() + .requestDigest() + .equals(row.get("fixture_policy_seal_request_digest", String.class)) + || !evidence + .fixturePolicySeal() + .evidenceDigest() + .equals(row.get("fixture_policy_seal_evidence_digest", String.class))) { + throw new InvalidCatalogEvidenceException( + "Exact retained fixture policy is unavailable or changed"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(row); + FreshTenantAssociation association = + verifyStoredFreshAssociation(evidence.sourceEvidence(), snapshot.tenantId()); + if (!snapshot.sourceIntakeReceipt().source().equals(evidence.sourceEvidence()) + || !association.sourceEvidence().equals(evidence.creationEvidence())) { + throw new InvalidCatalogEvidenceException( + "Retained fixture catalog source or creation changed"); + } + return new FixtureCanonicalRealmCatalog(snapshot, association); + } + + public record FixtureCanonicalRealmCatalog( + CanonicalRealmCatalogSnapshot snapshot, FreshTenantAssociation association) { + public FixtureCanonicalRealmCatalog { + Objects.requireNonNull(snapshot); + Objects.requireNonNull(association); + if (!snapshot.tenantId().equals(association.canonicalTenantId())) { + throw new IllegalArgumentException("Fixture catalog differs from owner tenant association"); + } + } + } + + private void validateCompleteCatalogPolicy( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + SelectedPolicy selected = selectPolicy(sourceReceipt.source(), publishedSet); + RealmEntryPolicy policy = selected.policy(); + if (!request.realmSlug().equals(policy.realmSlug()) + || !request.realmDisplayName().equals(policy.realmDisplayName()) + || request.visible() != policy.visible() + || request.publicProduction() != policy.publicProduction() + || !request.stateScope().equals(policy.stateScope().name()) + || !request.characterCreationPolicy().equals(policy.entryPolicy().name())) { + throw new InvalidCatalogEvidenceException( + "Catalog intent differs from its complete immutable owner policy"); + } + } + + private static String completeCatalogRequestDigest(String requestDigest, byte[] policyBytes) { + return digest( + "game-session-complete-catalog-request/v1", + requestDigest, + HexFormat.of().formatHex(policyBytes)); + } + + private final String workloadNamespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + private void requireFixtureComposition() { + if (workloadNamespace == null || writeTransaction == null || readTransaction == null) { + throw new IllegalStateException( + "Explicit owner transaction composition is required for fixture realm operations"); + } + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The managed DSL, transaction owner, and required namespace are validated locally; no reference escapes, no overridable callback runs, and the type has no finalizer.") + public GameSessionCanonicalRealmCatalogRepository( + DSLContext dsl, PlatformTransactionManager transactionManager, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is missing or invalid"); + } + this.workloadNamespace = workloadNamespace; + this.writeTransaction = new TransactionTemplate(transactionManager); + this.writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.readTransaction = new TransactionTemplate(transactionManager); + this.readTransaction.setReadOnly(true); + this.readTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + this.readTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + private FreshTenantAssociation verifyStoredFreshAssociation( + AuthoredWorldSourceEvidence source, UUID canonicalTenantId) { + try { + FreshTenantAssociation association = + new GameSessionFreshTenantAssociationRepository(dsl) + .readCanonicalTenantAssociationSnapshot(source.targetNamespace(), canonicalTenantId) + .orElseThrow( + () -> + new InvalidCatalogEvidenceException( + "Fresh canonical realm requires an existing complete Game Session tenant association")); + FreshTenantCreationEvidence creation = association.sourceEvidence(); + if (!creation.targetNamespace().equals(source.targetNamespace()) + || !creation.canonicalTenantId().equals(source.canonicalTenantId()) + || creation.sourceGameRowId() != source.sourceGameRowId() + || !creation.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !creation.provenanceKind().equals(source.provenanceKind())) { + throw new InvalidCatalogEvidenceException( + "Stored fresh tenant association differs from complete source receipt or canonical claim"); + } + return association; + } catch (InvalidFreshTenantAssociationException | IllegalArgumentException invalid) { + throw new InvalidCatalogEvidenceException( + "Stored fresh tenant association contains invalid complete source evidence", invalid); + } + } + + private static SelectedPolicy selectPolicy( + AuthoredWorldSourceEvidence source, RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + GameDesignPublicationOperationBinding publicationOperation = + GameDesignPublicationOperationBinding.fromStored(publishedSet.operationBytes()); + if (!publishedSet.target().canonicalTenantId().equals(source.canonicalTenantId()) + || publishedSet.target().sourceGameRowId() != source.sourceGameRowId() + || !publishedSet.target().sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !publishedSet.target().sourceProvenanceKind().equals(source.provenanceKind()) + || !publicationOperation + .world() + .request() + .targetNamespace() + .equals(source.targetNamespace()) + || !"NEW_GAME_ROW".equals(publishedSet.target().sourceProvenanceKind())) { + throw new InvalidCatalogEvidenceException( + "Published policy target or operation namespace differs from exact fresh authored-world source identity"); + } + List publicPolicies = + publishedSet.policies().stream() + .filter( + policy -> + policy.source().policy().visible() + && policy.source().policy().publicProduction()) + .toList(); + if (publishedSet.policyCount() != publishedSet.policies().size() + || publicPolicies.size() != 1) { + throw new InvalidCatalogEvidenceException( + "Exactly one complete visible public-production policy is required"); + } + RealmPolicyPublishedEvidence.Policy selected = publicPolicies.getFirst(); + RealmEntryPolicy policy = selected.source().policy(); + if (!source.worldSlug().equals(policy.worldSlug()) + || !source.worldDisplayName().equals(policy.worldDisplayName())) { + throw new InvalidCatalogEvidenceException( + "Public-production policy must exactly match the authored world"); + } + return new SelectedPolicy(selected.policyId(), selected.policyDigest(), policy); + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new InvalidCatalogEvidenceException( + "Stored canonical realm catalog is missing required evidence: " + field); + } + return value; + } + + private static void requireNoActiveOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authenticated Game Design reads must complete before opening a Game Session owner transaction"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session canonical realm storage access requires an active owner transaction"); + } + } + + private record SelectedPolicy(UUID policyId, String policyDigest, RealmEntryPolicy policy) {} } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java index ca861044ad..15eae1aab1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepository.java @@ -5,6 +5,8 @@ import java.util.regex.Pattern; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; @@ -18,8 +20,10 @@ * *

This repository is deliberately not a Spring component and is not an Account grant or * redemption adapter. Its caller must already have independently redeemed the exact Account - * authorization and supply the resulting canonical owner UUID and immutable operator request - * identity/digest. This class has no World lifecycle, pointer, or runtime-projection dependency. + * authorization and supply the resulting original post-authorization tuple, canonical owner UUID, + * and immutable operator request identity/digest. Existing canonical selection and descriptor pins + * must retain that exact tuple under a live original owner lease before allocation. This class has + * no World lifecycle, pointer, or runtime-projection dependency. */ public final class GameSessionCanonicalStartingInstanceRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); @@ -54,8 +58,10 @@ public StartingInstance createStarting( CompleteLaunchBindingEvidence launchBinding, UUID canonicalOwnerAccountUuid, String controlPlaneRequestId, - String canonicalRequestDigest) { + String canonicalRequestDigest, + StartSessionPostAuthorizationExecutionTuple originalTuple) { requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(originalTuple, "originalTuple"); Objects.requireNonNull(tenantAssociation, "tenantAssociation"); Objects.requireNonNull(launchBinding, "launchBinding"); requireNonNil(canonicalOwnerAccountUuid, "canonicalOwnerAccountUuid"); @@ -71,10 +77,25 @@ public StartingInstance createStarting( "Operator request identity or workload namespace differs from the complete launch binding"); } requireFreshTenantTuple(tenantAssociation, descriptor); + var action = originalTuple.preAuthorizationTuple().action(); + if (!"human_operator".equals(originalTuple.issuanceKind()) + || !"StartSession".equals(originalTuple.preAuthorizationTuple().actionFamily()) + || !"game-session-service".equals(originalTuple.preAuthorizationTuple().targetOwner()) + || !workloadNamespace.equals(action.scope().targetNamespace()) + || !descriptor.canonicalTenantId().equals(action.scope().tenantId()) + || descriptor.gameTemplateId() != action.target().gameTemplateId() + || !canonicalOwnerAccountUuid.equals(action.target().ownerAccountId()) + || !controlPlaneRequestId.equals(originalTuple.controlPlaneRequestId()) + || !canonicalRequestDigest.equals(originalTuple.mutationDigest())) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Original StartSession tuple differs from the exact owner, action, or launch request"); + } // This is the same serialization key used by association capture, before any owner lookup. launchAssociationRepository.lockRequestForStartingGameInstance(controlPlaneRequestId); - requireExactPersistedSource(tenantAssociation.sourceEvidence(), launchBinding); + requireExactPersistedSource(tenantAssociation, launchBinding); + launchAssociationRepository.requireOriginalPinsBeforeStarting(originalTuple, launchBinding); + requireLiveOriginalOwner(originalTuple); Record existingAssociation = findLaunchAssociationForRequest(controlPlaneRequestId); if (existingAssociation != null) { @@ -96,7 +117,8 @@ public StartingInstance createStarting( storedInstanceUuid); CanonicalGameInstanceLaunchAssociation association = - launchAssociationRepository.capture(tenantAssociation, storedInstanceId, launchBinding); + launchAssociationRepository.capture( + tenantAssociation, storedInstanceId, launchBinding, originalTuple); requireAssociationMatches(association, storedTenantId, storedInstanceUuid); return new StartingInstance(storedInstanceId, storedInstanceUuid, association); } @@ -125,7 +147,8 @@ public StartingInstance createStarting( // V26's initially deferred owner trigger requires this association before transaction commit. CanonicalGameInstanceLaunchAssociation association = - launchAssociationRepository.capture(tenantAssociation, gameInstanceId, launchBinding); + launchAssociationRepository.capture( + tenantAssociation, gameInstanceId, launchBinding, originalTuple); Record persistedRuntime = lockRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); requireRequestOwnerAndRuntime( @@ -146,6 +169,33 @@ public StartingInstance createStarting( return new StartingInstance(gameInstanceId, gameInstanceUuid, association); } + private void requireLiveOriginalOwner(StartSessionPostAuthorizationExecutionTuple tuple) { + String referenceExpiresAt = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()) + .authorizationExpiresAt(); + Record owner = + dsl.fetchOne( + "SELECT isfinite(lease_expires_at) AND lease_expires_at > clock_timestamp() " + + "AND ?::timestamptz > clock_timestamp() AS live " + + "FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "AND canonical_tenant_id = ? AND post_authorization_execution_tuple = ? " + + "AND mutation_digest = ? AND authorization_reference_fingerprint = ? " + + "AND phase_state = 'OWNER_EXECUTION_PENDING' " + + "AND account_redemption_projection IS NOT NULL FOR UPDATE", + referenceExpiresAt, + workloadNamespace, + tuple.controlPlaneRequestId(), + tuple.preAuthorizationTuple().action().scope().tenantId(), + tuple.canonicalBytes(), + tuple.mutationDigest(), + tuple.authorizationReferenceFingerprint()); + if (owner == null || !Boolean.TRUE.equals(owner.get("live", Boolean.class))) { + throw new InvalidCanonicalStartingInstanceEvidenceException( + "Exact original StartSession owner lease or Account reference is unavailable or expired"); + } + } + private long insertStartingRuntime( long privateGameSessionTenantId, CompleteLaunchBindingEvidence launchBinding, @@ -258,7 +308,8 @@ private void requireRequestOwnerAndRuntime( } private void requireExactPersistedSource( - RuntimeTenantIdentityEvidence expected, CompleteLaunchBindingEvidence launchBinding) { + FreshGameSessionTenantAssociation association, CompleteLaunchBindingEvidence launchBinding) { + RuntimeTenantIdentityEvidence expected = association.sourceEvidence(); var descriptor = launchBinding.descriptor(); Record row = dsl.fetchOne( @@ -279,11 +330,35 @@ private void requireExactPersistedSource( + "AND binding.source_game_row_id = intake.source_game_row_id " + "AND binding.source_game_tenant_key = intake.source_game_tenant_key " + "AND binding.provenance_kind = intake.source_provenance_kind " + + "JOIN game_session_fresh_tenant_association fresh " + + "ON fresh.target_namespace = intake.target_namespace " + + "AND fresh.canonical_tenant_id = intake.canonical_tenant_id " + + "AND fresh.source_game_row_id = intake.source_game_row_id " + + "AND fresh.source_game_tenant_key = intake.source_game_tenant_key " + + "AND fresh.provenance_kind = intake.source_provenance_kind " + + "JOIN game_session_tenant_canonical_claim claim " + + "ON claim.target_namespace = fresh.target_namespace " + + "AND claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "AND claim.legacy_game_session_tenant_id = fresh.legacy_game_session_tenant_id " + + "AND claim.association_operation_id = fresh.association_operation_id " + + "AND claim.association_request_id = fresh.association_request_id " + + "AND claim.association_kind = 'FRESH_SOURCE_BOUND' " + + "AND claim.reservation_kind = 'FRESH_SOURCE_BOUND' " + + "JOIN game_session_tenant_scope_reservation reservation " + + "ON reservation.game_session_tenant_id = fresh.legacy_game_session_tenant_id " + + "AND reservation.reservation_kind = 'FRESH_SOURCE_BOUND' " + "WHERE intake.target_namespace = ? " - + "AND intake.source_registration_request_id = ? " - + "AND intake.source_operation_id = ? FOR KEY SHARE OF intake, binding", + + "AND fresh.association_request_id = ? " + + "AND fresh.association_operation_id = ? " + + "AND fresh.legacy_game_session_tenant_id = ? " + + "AND fresh.association_kind = 'FRESH_SOURCE_BOUND' " + + "AND fresh.complete_source_evidence IS NOT NULL " + + "AND fresh.complete_source_evidence ->> 'creationRequestId' = fresh.association_request_id::text " + + "AND intake.source_operation_id = ? FOR KEY SHARE OF intake, binding, fresh, claim, reservation", workloadNamespace, expected.requestId(), + association.associationOperationId(), + association.legacyGameSessionTenantId(), descriptor.authoredWorldSourceOperationId()); if (row == null) { throw new InvalidCanonicalStartingInstanceEvidenceException( @@ -314,7 +389,6 @@ private void requireExactPersistedSource( if (!"NEW_GAME_ROW".equals(persisted.provenanceKind()) || !expected.targetNamespace().equals(persisted.targetNamespace()) - || !expected.requestId().equals(persisted.registrationRequestId()) || !expected.canonicalTenantId().equals(persisted.canonicalTenantId()) || expected.sourceGameRowId() != persisted.sourceGameRowId() || !expected.sourceGameTenantKey().equals(persisted.sourceGameTenantKey()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java index 5a63133283..e00bd95fdc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java @@ -1,20 +1,36 @@ package net.firedevops.firemud.gamesession.repository; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; import java.sql.Connection; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import org.jooq.DSLContext; import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; /** * Game Session's owner for immutable fresh canonical-tenant to private tenant-key association. @@ -24,7 +40,7 @@ */ public class GameSessionFreshTenantAssociationRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); - private static final String FRESH_KIND = "FRESH_SOURCE_BOUND"; + private static final int MAX_TENANT_ID_ALLOCATION_ATTEMPTS = 64; private final DSLContext dsl; @@ -35,76 +51,50 @@ public class GameSessionFreshTenantAssociationRepository { + " remains non-final for transaction proxying.") public GameSessionFreshTenantAssociationRepository(DSLContext dsl) { this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.gameDesignClient = null; + this.workloadNamespace = null; + this.writeTransaction = null; + this.readTransaction = null; } - /** - * Persists the fresh source-bound tenant mapping or returns its exact durable replay. - * - *

The association operation ID is the caller's stable mutation identity. The expected receipt - * is re-read, digest-validated, and compared with its immutable tenant-source binding under this - * same writable READ COMMITTED transaction before any private tenant ID is allocated. - */ + /** Creates the existing owner association only from both exact committed source receipts. */ @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) public FreshGameSessionTenantAssociation associateFresh( - UUID associationOperationId, String targetNamespace, IntakeReceipt expectedSourceReceipt) { + UUID associationOperationId, + String targetNamespace, + IntakeReceipt expectedSourceReceipt, + FreshTenantCreationEvidence creationEvidence) { requireWritableReadCommittedOwnerTransaction(); requireNonNil(associationOperationId, "associationOperationId"); - if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { - throw new IllegalArgumentException("Target namespace must be one canonical DNS label"); - } Objects.requireNonNull(expectedSourceReceipt, "expectedSourceReceipt"); - if (!targetNamespace.equals(expectedSourceReceipt.source().targetNamespace())) { - throw new FreshTenantAssociationConflictException( - "Source receipt namespace differs from the requested association namespace"); + Objects.requireNonNull(creationEvidence, "creationEvidence"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(creationEvidence.targetNamespace())) { + throw new InvalidFreshTenantSourceException("Exact configured source namespace is required"); } - - lockAssociationOperation(associationOperationId); - IntakeReceipt persistedSource = + IntakeReceipt committed = readPersistedSourceReceipt(targetNamespace, expectedSourceReceipt.operationId()); - if (!persistedSource.equals(expectedSourceReceipt)) { + AuthoredWorldSourceEvidence authored = committed.source(); + if (!committed.equals(expectedSourceReceipt) + || !creationEvidence.canonicalTenantId().equals(authored.canonicalTenantId()) + || creationEvidence.sourceGameRowId() != authored.sourceGameRowId() + || !creationEvidence.sourceGameTenantKey().equals(authored.sourceGameTenantKey()) + || !creationEvidence.provenanceKind().equals(authored.provenanceKind())) { throw new InvalidFreshTenantSourceException( - "Persisted authored-world source receipt differs from the requested exact receipt"); - } - RuntimeTenantIdentityEvidence runtimeSource = - requireFreshSource(targetNamespace, persistedSource.source()); - - Record existingAssociation = findAssociationByOperation(associationOperationId); - if (existingAssociation != null) { - return requireExactAssociation( - existingAssociation, associationOperationId, targetNamespace, runtimeSource); - } - - if (findClaimByOperation(associationOperationId) != null) { - throw new FreshTenantAssociationConflictException( - "Association operation ID is already owned by another tenant claim"); + "Complete creation and authored-source receipts differ"); } - if (findClaimByCanonicalTenant(targetNamespace, runtimeSource.canonicalTenantId()) != null) { - throw new FreshTenantAssociationConflictException( - "Canonical tenant already has a Game Session tenant association"); - } - if (findClaimByAssociationRequest( - targetNamespace, persistedSource.source().registrationRequestId()) - != null) { - throw new FreshTenantAssociationConflictException( - "Source registration request is already owned by another tenant association"); - } - - long privateTenantId = allocateFreshPrivateTenantId(); - insertCanonicalClaim( - targetNamespace, - runtimeSource.canonicalTenantId(), - privateTenantId, - associationOperationId, - persistedSource.source().registrationRequestId()); - insertFreshAssociation( - associationOperationId, targetNamespace, privateTenantId, persistedSource.source()); - - Record committedAssociation = findAssociationByOperation(associationOperationId); - if (committedAssociation == null) { - throw new IllegalStateException("Committed fresh tenant association is missing"); - } - return requireExactAssociation( - committedAssociation, associationOperationId, targetNamespace, runtimeSource); + FreshTenantAssociation complete = commitAssociation(creationEvidence, associationOperationId); + return new FreshGameSessionTenantAssociation( + complete.associationOperationId(), + complete.gameSessionTenantId(), + new RuntimeTenantIdentityEvidence( + creationEvidence.schemaVersion(), + creationEvidence.targetNamespace(), + creationEvidence.creationRequestId(), + creationEvidence.canonicalTenantId(), + creationEvidence.sourceGameRowId(), + creationEvidence.sourceGameTenantKey(), + creationEvidence.provenanceKind())); } private void lockAssociationOperation(UUID associationOperationId) { @@ -223,31 +213,6 @@ private void requireExactTenantSourceBinding(Record row, AuthoredWorldSourceEvid } } - private RuntimeTenantIdentityEvidence requireFreshSource( - String targetNamespace, AuthoredWorldSourceEvidence source) { - if (!targetNamespace.equals(source.targetNamespace())) { - throw new InvalidFreshTenantSourceException( - "Authored-world source namespace differs from the association namespace"); - } - if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { - throw new InvalidFreshTenantSourceException( - "Fresh tenant association requires NEW_GAME_ROW source provenance"); - } - try { - return new RuntimeTenantIdentityEvidence( - source.schemaVersion(), - source.targetNamespace(), - source.registrationRequestId(), - source.canonicalTenantId(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind()); - } catch (IllegalArgumentException exception) { - throw new InvalidFreshTenantSourceException( - "Authored-world source cannot establish a fresh runtime tenant identity", exception); - } - } - private Record findAssociationByOperation(UUID associationOperationId) { return dsl.fetchOne( "SELECT * FROM game_session_fresh_tenant_association " @@ -262,125 +227,6 @@ private Record findClaimByOperation(UUID associationOperationId) { associationOperationId); } - private Record findClaimByCanonicalTenant(String namespace, UUID canonicalTenantId) { - return dsl.fetchOne( - "SELECT * FROM game_session_tenant_canonical_claim " - + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR UPDATE", - namespace, - canonicalTenantId); - } - - private Record findClaimByAssociationRequest(String namespace, UUID associationRequestId) { - return dsl.fetchOne( - "SELECT * FROM game_session_tenant_canonical_claim " - + "WHERE target_namespace = ? AND association_request_id = ? FOR UPDATE", - namespace, - associationRequestId); - } - - private long allocateFreshPrivateTenantId() { - Record reservation = - dsl.fetchOne( - "INSERT INTO game_session_tenant_scope_reservation (reservation_kind) " - + "VALUES ('FRESH_SOURCE_BOUND') RETURNING game_session_tenant_id"); - if (reservation == null || reservation.get("game_session_tenant_id", Long.class) == null) { - throw new IllegalStateException("Game Session tenant ID reservation returned no identity"); - } - long privateTenantId = reservation.get("game_session_tenant_id", Long.class); - if (privateTenantId <= 0) { - throw new IllegalStateException("Game Session tenant ID reservation was not positive"); - } - return privateTenantId; - } - - private void insertCanonicalClaim( - String namespace, - UUID canonicalTenantId, - long privateTenantId, - UUID associationOperationId, - UUID associationRequestId) { - int inserted = - dsl.execute( - "INSERT INTO game_session_tenant_canonical_claim " - + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, " - + "association_kind, reservation_kind, association_operation_id, " - + "association_request_id) " - + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", - namespace, - canonicalTenantId, - privateTenantId, - associationOperationId, - associationRequestId); - if (inserted != 1) { - throw new IllegalStateException("Game Session canonical tenant claim was not persisted"); - } - } - - private void insertFreshAssociation( - UUID associationOperationId, - String namespace, - long privateTenantId, - AuthoredWorldSourceEvidence source) { - int inserted = - dsl.execute( - "INSERT INTO game_session_fresh_tenant_association " - + "(association_operation_id, target_namespace, association_request_id, " - + "source_schema_version, source_target_namespace, source_request_id, " - + "source_canonical_tenant_id, canonical_tenant_id, " - + "legacy_game_session_tenant_id, source_game_row_id, source_game_tenant_key, " - + "provenance_kind, association_kind) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', " - + "'FRESH_SOURCE_BOUND')", - associationOperationId, - namespace, - source.registrationRequestId(), - source.schemaVersion(), - namespace, - source.registrationRequestId(), - source.canonicalTenantId(), - source.canonicalTenantId(), - privateTenantId, - source.sourceGameRowId(), - source.sourceGameTenantKey()); - if (inserted != 1) { - throw new IllegalStateException("Game Session fresh tenant association was not persisted"); - } - } - - private FreshGameSessionTenantAssociation requireExactAssociation( - Record association, - UUID expectedOperationId, - String expectedNamespace, - RuntimeTenantIdentityEvidence expectedSource) { - UUID associationOperationId = required(association.get("association_operation_id", UUID.class)); - long privateTenantId = required(association.get("legacy_game_session_tenant_id", Long.class)); - if (!expectedOperationId.equals(associationOperationId) - || !expectedNamespace.equals(association.get("target_namespace", String.class)) - || !expectedSource.requestId().equals(association.get("association_request_id", UUID.class)) - || !Integer.valueOf(expectedSource.schemaVersion()) - .equals(association.get("source_schema_version", Integer.class)) - || !expectedNamespace.equals(association.get("source_target_namespace", String.class)) - || !expectedSource.requestId().equals(association.get("source_request_id", UUID.class)) - || !expectedSource - .canonicalTenantId() - .equals(association.get("source_canonical_tenant_id", UUID.class)) - || !expectedSource - .canonicalTenantId() - .equals(association.get("canonical_tenant_id", UUID.class)) - || !Objects.equals( - expectedSource.sourceGameRowId(), association.get("source_game_row_id", Long.class)) - || !expectedSource - .sourceGameTenantKey() - .equals(association.get("source_game_tenant_key", String.class)) - || !expectedSource.provenanceKind().equals(association.get("provenance_kind", String.class)) - || !FRESH_KIND.equals(association.get("association_kind", String.class))) { - throw new FreshTenantAssociationConflictException( - "Association operation ID is already bound to different source or namespace evidence"); - } - return new FreshGameSessionTenantAssociation( - associationOperationId, privateTenantId, expectedSource); - } - private void requireWritableReadCommittedOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { @@ -434,4 +280,568 @@ public FreshTenantAssociationConflictException(String message) { super(message); } } + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Set EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + private static final String ASSOCIATION_SELECT = + "SELECT fresh.target_namespace, fresh.association_request_id, " + + "fresh.source_schema_version, fresh.source_target_namespace, " + + "fresh.source_request_id, fresh.source_canonical_tenant_id, " + + "fresh.canonical_tenant_id, fresh.legacy_game_session_tenant_id, " + + "fresh.source_game_row_id, fresh.source_game_tenant_key, fresh.provenance_kind, " + + "fresh.association_kind, fresh.association_operation_id, " + + "fresh.complete_source_evidence::text AS complete_source_evidence, " + + "claim.target_namespace AS claim_namespace, " + + "claim.canonical_tenant_id AS claim_canonical_tenant_id, " + + "claim.legacy_game_session_tenant_id AS claim_tenant_id, " + + "claim.association_kind AS claim_kind, " + + "claim.reservation_kind AS claim_reservation_kind, " + + "claim.association_operation_id AS claim_operation_id, " + + "claim.association_request_id AS claim_request_id, " + + "reservation.reservation_kind AS reservation_kind " + + "FROM game_session_fresh_tenant_association fresh " + + "LEFT JOIN game_session_tenant_canonical_claim claim " + + "ON claim.target_namespace = fresh.target_namespace " + + "AND claim.canonical_tenant_id = fresh.canonical_tenant_id " + + "LEFT JOIN game_session_tenant_scope_reservation reservation " + + "ON reservation.game_session_tenant_id = fresh.legacy_game_session_tenant_id "; + + private final GameDesignFreshTenantCreationClient gameDesignClient; + private final String workloadNamespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + private void requireExplicitOwnerComposition() { + if (workloadNamespace == null || writeTransaction == null || readTransaction == null) { + throw new IllegalStateException( + "Explicit owner transaction composition is required for fresh tenant reads"); + } + } + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "The injected DSLContext is a shared jOOQ boundary retained for this repository's owner-scoped SQL. " + + "Constructor validation fails before this escapes; it acquires no cleanup-sensitive " + + "resource, registers no finalizer, and invokes no overridable callback.") + public GameSessionFreshTenantAssociationRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + GameDesignFreshTenantCreationClient gameDesignClient, + String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is missing or invalid"); + } + this.workloadNamespace = workloadNamespace; + this.writeTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + this.writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.readTransaction = new TransactionTemplate(transactionManager); + this.readTransaction.setReadOnly(true); + } + + /** + * Resolves the exact authenticated Game Design receipt outside SQL, atomically claims a new Game + * Session numeric tenant ID and association, then independently reads the committed row. Exact + * retries return the original allocation; a changed source receipt or incomplete legacy + * association fails closed. + */ + public FreshTenantAssociation associateFreshTenant( + UUID creationRequestId, String expectedRequestDigest) { + requireNoActiveOwnerTransaction(); + requireExactSelector(creationRequestId, expectedRequestDigest); + if (gameDesignClient == null || writeTransaction == null || readTransaction == null) { + throw new IllegalStateException( + "Explicit authenticated fresh-creation client composition is required"); + } + + FreshTenantCreationEvidence sourceEvidence = + Objects.requireNonNull( + gameDesignClient.resolveCreation(creationRequestId, expectedRequestDigest), + "Authenticated Game Design fresh-tenant evidence is required"); + requireExactSource(sourceEvidence, creationRequestId, expectedRequestDigest); + + FreshTenantAssociation committed = + writeTransaction.execute(status -> commitAssociation(sourceEvidence, null)); + if (committed == null) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association transaction returned no result"); + } + + FreshTenantAssociation independentReadback = + readTransaction.execute( + status -> + readByCanonicalTenantIdInTransaction( + sourceEvidence.targetNamespace(), sourceEvidence.canonicalTenantId()) + .orElse(null)); + if (independentReadback == null + || !sourceEvidence.equals(independentReadback.sourceEvidence()) + || !committed.equals(independentReadback)) { + throw new InvalidFreshTenantAssociationException( + "Committed Game Session fresh tenant association failed independent exact readback"); + } + return independentReadback; + } + + /** Reads only complete, internally consistent stored evidence; it never calls Game Design. */ + public Optional readByCanonicalTenantId(UUID canonicalTenantId) { + requireNoActiveOwnerTransaction(); + requireExplicitOwnerComposition(); + if (canonicalTenantId == null || isNil(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID must be nonnil"); + } + Optional result = + readTransaction.execute( + status -> readByCanonicalTenantIdInTransaction(workloadNamespace, canonicalTenantId)); + return Objects.requireNonNull(result, "Game Session read transaction returned no result"); + } + + FreshTenantAssociation associateVerifiedFixtureInOwnerTransaction( + net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireWritableReadCommittedOwnerTransaction(); + evidence.requireVerifiedFixture(); + return commitAssociation(evidence.creationEvidence(), null); + } + + private FreshTenantAssociation commitAssociation( + FreshTenantCreationEvidence sourceEvidence, UUID requestedOperationId) { + requireOwnerTransaction(); + if (requestedOperationId != null) { + lockAssociationOperation(requestedOperationId); + } + lockSourceIdentity(sourceEvidence); + + Optional prior = + readByRequestIdInTransaction( + sourceEvidence.targetNamespace(), sourceEvidence.creationRequestId()); + if (prior.isPresent()) { + requireExactSource(sourceEvidence, prior.orElseThrow().sourceEvidence()); + if (requestedOperationId != null + && !requestedOperationId.equals(prior.orElseThrow().associationOperationId())) { + throw new InvalidFreshTenantAssociationException( + "Association operation differs from its immutable original"); + } + return prior.orElseThrow(); + } + + rejectOrphanOrRetainedClaim(sourceEvidence); + if (requestedOperationId != null + && (findAssociationByOperation(requestedOperationId) != null + || findClaimByOperation(requestedOperationId) != null)) { + throw new FreshTenantAssociationConflictException( + "Association operation ID is already bound to different source or namespace evidence"); + } + long tenantId = allocateFreshTenantId(); + UUID associationOperationId = + requestedOperationId == null + ? newAssociationOperationId(sourceEvidence.operationId()) + : requestedOperationId; + if (associationOperationId.equals(sourceEvidence.operationId())) { + throw new InvalidFreshTenantAssociationException( + "Owner operation cannot reuse the Game Design operation identity"); + } + + int claimInsertCount = + dsl.execute( + "INSERT INTO game_session_tenant_canonical_claim" + + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, reservation_kind, association_operation_id," + + " association_request_id) VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND'," + + " 'FRESH_SOURCE_BOUND', ?, ?)", + sourceEvidence.targetNamespace(), + sourceEvidence.canonicalTenantId(), + tenantId, + associationOperationId, + sourceEvidence.creationRequestId()); + if (claimInsertCount != 1) { + throw new InvalidFreshTenantAssociationException( + "Game Session canonical tenant claim insert did not affect exactly one row"); + } + + int associationInsertCount = + dsl.execute( + "INSERT INTO game_session_fresh_tenant_association" + + " (association_operation_id, target_namespace, association_request_id," + + " source_schema_version, source_target_namespace, source_request_id," + + " source_canonical_tenant_id, canonical_tenant_id," + + " legacy_game_session_tenant_id, source_game_row_id," + + " source_game_tenant_key, provenance_kind, association_kind," + + " complete_source_evidence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?::jsonb)", + associationOperationId, + sourceEvidence.targetNamespace(), + sourceEvidence.creationRequestId(), + sourceEvidence.schemaVersion(), + sourceEvidence.targetNamespace(), + sourceEvidence.creationRequestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.canonicalTenantId(), + tenantId, + sourceEvidence.sourceGameRowId(), + sourceEvidence.sourceGameTenantKey(), + sourceEvidence.provenanceKind(), + serializeEvidence(sourceEvidence)); + if (associationInsertCount != 1) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association insert did not affect exactly one row"); + } + + FreshTenantAssociation readback = + readByCanonicalTenantIdInTransaction( + sourceEvidence.targetNamespace(), sourceEvidence.canonicalTenantId()) + .orElseThrow( + () -> + new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association did not read back in its owner transaction")); + requireExactSource(sourceEvidence, readback.sourceEvidence()); + return readback; + } + + private Optional readByCanonicalTenantIdInTransaction( + String namespace, UUID canonicalTenantId) { + requireOwnerTransaction(); + return readCanonicalTenantAssociationSnapshot(namespace, canonicalTenantId); + } + + /** One complete owner association/claim snapshot under the caller's established read boundary. */ + Optional readCanonicalTenantAssociationSnapshot( + String namespace, UUID canonicalTenantId) { + if (canonicalTenantId == null || isNil(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID must be nonnil"); + } + Record row = + dsl.fetchOne( + ASSOCIATION_SELECT + + "WHERE fresh.target_namespace = ? AND fresh.canonical_tenant_id = ?", + namespace, + canonicalTenantId); + if (row == null) { + rejectClaimWithoutAssociation(namespace, canonicalTenantId, null); + return Optional.empty(); + } + return Optional.of(toAssociation(row)); + } + + private Optional readByRequestIdInTransaction( + String namespace, UUID requestId) { + requireOwnerTransaction(); + Record row = + dsl.fetchOne( + ASSOCIATION_SELECT + + "WHERE fresh.target_namespace = ? AND fresh.association_request_id = ?", + namespace, + requestId); + if (row == null) { + return Optional.empty(); + } + return Optional.of(toAssociation(row)); + } + + private FreshTenantAssociation toAssociation(Record row) { + try { + String namespace = required(row, "target_namespace", String.class); + UUID canonicalTenantId = required(row, "canonical_tenant_id", UUID.class); + UUID requestId = required(row, "association_request_id", UUID.class); + UUID associationOperationId = required(row, "association_operation_id", UUID.class); + long tenantId = required(row, "legacy_game_session_tenant_id", Long.class); + FreshTenantCreationEvidence sourceEvidence = + parseEvidence(required(row, "complete_source_evidence", String.class)); + + if (workloadNamespace != null && !workloadNamespace.equals(namespace) + || !namespace.equals(required(row, "source_target_namespace", String.class)) + || !requestId.equals(required(row, "source_request_id", UUID.class)) + || !canonicalTenantId.equals(required(row, "source_canonical_tenant_id", UUID.class)) + || required(row, "source_schema_version", Integer.class) != sourceEvidence.schemaVersion() + || required(row, "source_game_row_id", Long.class) != sourceEvidence.sourceGameRowId() + || !required(row, "source_game_tenant_key", String.class) + .equals(sourceEvidence.sourceGameTenantKey()) + || !required(row, "provenance_kind", String.class).equals(sourceEvidence.provenanceKind()) + || !"FRESH_SOURCE_BOUND".equals(required(row, "association_kind", String.class)) + || !sourceEvidence.targetNamespace().equals(namespace) + || !sourceEvidence.creationRequestId().equals(requestId) + || !sourceEvidence.canonicalTenantId().equals(canonicalTenantId) + || isNil(associationOperationId) + || associationOperationId.equals(sourceEvidence.operationId()) + || !"FRESH_SOURCE_BOUND".equals(required(row, "claim_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(required(row, "claim_reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(required(row, "reservation_kind", String.class)) + || !namespace.equals(required(row, "claim_namespace", String.class)) + || !canonicalTenantId.equals(required(row, "claim_canonical_tenant_id", UUID.class)) + || tenantId != required(row, "claim_tenant_id", Long.class) + || !associationOperationId.equals(required(row, "claim_operation_id", UUID.class)) + || !requestId.equals(required(row, "claim_request_id", UUID.class))) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association differs from its complete source receipt or canonical claim"); + } + return new FreshTenantAssociation( + namespace, canonicalTenantId, tenantId, associationOperationId, sourceEvidence); + } catch (IllegalArgumentException exception) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association contains invalid complete source evidence", + exception); + } + } + + private void rejectOrphanOrRetainedClaim(FreshTenantCreationEvidence evidence) { + rejectClaimWithoutAssociation( + evidence.targetNamespace(), evidence.canonicalTenantId(), evidence.creationRequestId()); + } + + private void rejectClaimWithoutAssociation( + String namespace, UUID canonicalTenantId, UUID requestId) { + if (requestId != null + && readByCanonicalTenantIdInTransaction(namespace, canonicalTenantId).isPresent()) { + throw new FreshTenantAssociationConflictException( + "canonical tenant is already bound to a different complete fresh association"); + } + Record claim = + dsl.fetchOne( + "SELECT target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, association_request_id FROM game_session_tenant_canonical_claim" + + " WHERE target_namespace = ? AND (canonical_tenant_id = ? OR association_request_id = ?)", + namespace, + canonicalTenantId, + requestId); + if (claim != null) { + throw new InvalidFreshTenantAssociationException( + "Game Session canonical tenant claim exists without its exact fresh association; retained or partial identity cannot be adopted"); + } + } + + private long allocateFreshTenantId() { + for (int attempt = 0; attempt < MAX_TENANT_ID_ALLOCATION_ATTEMPTS; attempt++) { + Record reservation = + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation (reservation_kind)" + + " VALUES ('FRESH_SOURCE_BOUND')" + + " ON CONFLICT (game_session_tenant_id) DO NOTHING" + + " RETURNING game_session_tenant_id, reservation_kind"); + if (reservation == null) { + continue; + } + if (!"FRESH_SOURCE_BOUND".equals(required(reservation, "reservation_kind", String.class))) { + throw new InvalidFreshTenantAssociationException( + "Game Session numeric tenant reservation did not allocate a fresh source-bound key"); + } + Long tenantId = required(reservation, "game_session_tenant_id", Long.class); + if (tenantId <= 0) { + throw new InvalidFreshTenantAssociationException( + "Game Session numeric tenant reservation is not positive"); + } + return tenantId; + } + throw new InvalidFreshTenantAssociationException( + "Game Session numeric tenant reservation exhausted its bounded allocation attempts"); + } + + private void lockSourceIdentity(FreshTenantCreationEvidence evidence) { + List lockKeys = + new ArrayList<>( + List.of( + "fresh-tenant-canonical:" + + evidence.targetNamespace() + + ":" + + evidence.canonicalTenantId(), + "fresh-tenant-request:" + + evidence.targetNamespace() + + ":" + + evidence.creationRequestId())); + lockKeys.sort(String::compareTo); + for (String key : lockKeys) { + dsl.fetch("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", key); + } + } + + private static UUID newAssociationOperationId(UUID sourceOperationId) { + UUID operationId; + do { + operationId = UUID.randomUUID(); + } while (operationId.equals(sourceOperationId) || isNil(operationId)); + return operationId; + } + + private static String serializeEvidence(FreshTenantCreationEvidence evidence) { + ObjectNode json = JSON.createObjectNode(); + json.put("schemaVersion", evidence.schemaVersion()); + json.put("targetNamespace", evidence.targetNamespace()); + json.put("creationRequestId", evidence.creationRequestId().toString()); + json.put("operationId", evidence.operationId().toString()); + json.put("requestDigest", evidence.requestDigest()); + json.put("canonicalTenantId", evidence.canonicalTenantId().toString()); + json.put("sourceGameRowId", evidence.sourceGameRowId()); + json.put("sourceGameTenantKey", evidence.sourceGameTenantKey()); + json.put("provenanceKind", evidence.provenanceKind()); + json.put("evidenceDigest", evidence.evidenceDigest()); + try { + return JSON.writeValueAsString(json); + } catch (JsonProcessingException exception) { + throw new InvalidFreshTenantAssociationException( + "Complete Game Design source evidence could not be serialized", exception); + } + } + + private static FreshTenantCreationEvidence parseEvidence(String serializedEvidence) { + try { + JsonNode json = JSON.readTree(serializedEvidence); + if (json == null || !json.isObject() || json.size() != EVIDENCE_FIELDS.size()) { + throw new IllegalArgumentException( + "Complete source evidence must be one closed JSON object"); + } + Set fields = new HashSet<>(); + json.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(EVIDENCE_FIELDS)) { + throw new IllegalArgumentException( + "Complete source evidence has an unknown or missing field"); + } + return new FreshTenantCreationEvidence( + requiredInt(json, "schemaVersion"), + requiredText(json, "targetNamespace"), + parseUuid(requiredText(json, "creationRequestId")), + parseUuid(requiredText(json, "operationId")), + requiredText(json, "requestDigest"), + parseUuid(requiredText(json, "canonicalTenantId")), + requiredLong(json, "sourceGameRowId"), + requiredText(json, "sourceGameTenantKey"), + requiredText(json, "provenanceKind"), + requiredText(json, "evidenceDigest")); + } catch (IOException | IllegalArgumentException exception) { + throw new InvalidFreshTenantAssociationException( + "Stored Game Session complete source evidence is malformed or has an invalid digest", + exception); + } + } + + private static String requiredText(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Complete source evidence field must be text: " + field); + } + return value.textValue(); + } + + private static int requiredInt(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw new IllegalArgumentException( + "Complete source evidence field must be an integer: " + field); + } + return value.intValue(); + } + + private static long requiredLong(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw new IllegalArgumentException( + "Complete source evidence field must be an integer: " + field); + } + return value.longValue(); + } + + private static UUID parseUuid(String value) { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || isNil(parsed)) { + throw new IllegalArgumentException( + "Complete source evidence UUID must be canonical and nonnil"); + } + return parsed; + } + + private static void requireExactSelector(UUID requestId, String expectedDigest) { + if (requestId == null || isNil(requestId)) { + throw new IllegalArgumentException("Canonical nonnil creation request ID is required"); + } + if (!GameTenantCreationDigest.isDigest(expectedDigest)) { + throw new IllegalArgumentException("Canonical expected request digest is required"); + } + } + + private void requireExactSource( + FreshTenantCreationEvidence evidence, UUID requestId, String expectedDigest) { + if (evidence == null + || !workloadNamespace.equals(evidence.targetNamespace()) + || !requestId.equals(evidence.creationRequestId()) + || !expectedDigest.equals(evidence.requestDigest())) { + throw new InvalidFreshTenantAssociationException( + "Authenticated Game Design receipt differs from the exact Game Session request"); + } + } + + private static void requireExactSource( + FreshTenantCreationEvidence expected, FreshTenantCreationEvidence actual) { + if (!expected.equals(actual)) { + throw new InvalidFreshTenantAssociationException( + "Game Session association retry differs from the complete original Game Design receipt"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association is missing required stored evidence: " + field); + } + return value; + } + + private static void requireNoActiveOwnerTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Design fresh tenant evidence must be resolved before opening a Game Session transaction"); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Game Session fresh tenant association storage access requires an active owner transaction"); + } + } + + private static boolean isNil(UUID value) { + return value != null && new UUID(0L, 0L).equals(value); + } + + /** Exact immutable Game Session allocation and its complete Game Design owner receipt. */ + public record FreshTenantAssociation( + String targetNamespace, + UUID canonicalTenantId, + long gameSessionTenantId, + UUID associationOperationId, + FreshTenantCreationEvidence sourceEvidence) { + public FreshTenantAssociation { + Objects.requireNonNull(targetNamespace); + Objects.requireNonNull(canonicalTenantId); + Objects.requireNonNull(associationOperationId); + Objects.requireNonNull(sourceEvidence); + if (gameSessionTenantId <= 0 + || isNil(canonicalTenantId) + || isNil(associationOperationId) + || associationOperationId.equals(sourceEvidence.operationId())) { + throw new IllegalArgumentException("Stored fresh tenant association identity is invalid"); + } + } + } + + /** Stored association, canonical claim, or source receipt is incomplete or contradictory. */ + public static final class InvalidFreshTenantAssociationException extends IllegalStateException { + public InvalidFreshTenantAssociationException(String message) { + super(message); + } + + public InvalidFreshTenantAssociationException(String message, Throwable cause) { + super(message, cause); + } + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java index 398ca8e8a4..d04f1a2e8b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java @@ -15,11 +15,12 @@ public final class ProtectedGameSessionLoginGrpcInterceptor implements ServerInt Set.of( "game_session.v1.GameSessionService/Ping", "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", + "game_session.v1.GameSessionControlPlaneService/GetRunOwnedFixtureLaunchAssociation", "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof", + "game_session.v1.CanonicalInitialAdmissionOwnerProofReadService/GetCanonicalInitialAdmissionOwnerProof", "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java index 5e47274f8c..a0b7018a60 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.gamesession.service; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -27,10 +26,6 @@ public final class CanonicalPlayerRouteReadService { private final CanonicalInitialAdmissionRepository admissionRepository; private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = - "Injected repository collaborators are retained only for this service's read composition") public CanonicalPlayerRouteReadService( String targetNamespace, GameSessionCanonicalRealmCatalogRepository catalogRepository, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java index b95243f6f1..1ca0914f19 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparation.java @@ -1,18 +1,14 @@ package net.firedevops.firemud.gamesession.service.impl; -import java.util.Arrays; import java.util.Objects; -import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.IntentState; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; /** * Inactive orchestration seam for the durable-intent, World-acquire, exact-attach sequence. @@ -22,26 +18,18 @@ * current lifecycle, or admission. */ public final class CanonicalInitialAdmissionHoldPreparation { - private final CanonicalInitialAdmissionIntentRepository intentRepository; - private final WorldCanonicalInitialAdmissionHoldClient worldClient; - private final TransactionTemplate ownerTransaction; public CanonicalInitialAdmissionHoldPreparation( CanonicalInitialAdmissionIntentRepository intentRepository, WorldCanonicalInitialAdmissionHoldClient worldClient, PlatformTransactionManager transactionManager) { - this.intentRepository = Objects.requireNonNull(intentRepository, "intentRepository"); - this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); + Objects.requireNonNull(intentRepository, "intentRepository"); + Objects.requireNonNull(worldClient, "worldClient"); Objects.requireNonNull(transactionManager, "transactionManager"); - this.ownerTransaction = new TransactionTemplate(transactionManager); - this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - this.ownerTransaction.setReadOnly(false); } /** - * Persists the immutable request before acquiring the World hold, then attaches only the exact - * World-issued identity in a second owner transaction. + * Denies incomplete Human admission before intent reservation or remote World hold acquisition. */ public CanonicalInitialAdmissionIntentSnapshot prepare( Request exactHoldRequest, @@ -49,32 +37,7 @@ public CanonicalInitialAdmissionIntentSnapshot prepare( requireNoAmbientTransaction(); Objects.requireNonNull(exactHoldRequest, "exactHoldRequest"); Objects.requireNonNull(exactLifecycleRequest, "exactLifecycleRequest"); - - CanonicalInitialAdmissionIntentSnapshot reserved = - ownerTransaction.execute( - status -> intentRepository.reserve(exactHoldRequest, exactLifecycleRequest)); - requireSnapshotMatches(reserved, exactHoldRequest, exactLifecycleRequest); - - // Replays retain the exact immutable historical snapshot. They do not check current World - // state and therefore cannot authorize admission or alter a terminal outcome. - if (reserved.state() != IntentState.PENDING_HOLD) { - return reserved; - } - - // TransactionTemplate returns only after commit; this network call is outside owner SQL. - HoldIdentity acquired = worldClient.acquire(exactHoldRequest, exactLifecycleRequest); - requireExactHoldIdentity(acquired, exactHoldRequest); - - CanonicalInitialAdmissionIntentSnapshot attached = - ownerTransaction.execute(status -> intentRepository.attach(exactHoldRequest, acquired)); - requireSnapshotMatches(attached, exactHoldRequest, exactLifecycleRequest); - if (attached.state() != IntentState.HOLD_ATTACHED - || attached.holdIdentity() == null - || !Arrays.equals(attached.holdIdentity().canonicalBytes(), acquired.canonicalBytes())) { - throw new IllegalStateException( - "Attached initial-admission intent did not retain the exact World hold identity"); - } - return attached; + throw CanonicalInitialAdmissionRepository.unavailableHumanAdmissionProtection(); } private static void requireNoAmbientTransaction() { @@ -84,29 +47,4 @@ private static void requireNoAmbientTransaction() { "Initial-admission hold preparation cannot enter from an ambient transaction"); } } - - private static void requireSnapshotMatches( - CanonicalInitialAdmissionIntentSnapshot snapshot, - Request holdRequest, - WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { - if (snapshot == null - || !Arrays.equals( - snapshot.holdRequest().canonicalRequestBytes(), holdRequest.canonicalRequestBytes()) - || !Arrays.equals( - snapshot.lifecycleRequest().canonicalBytes(), lifecycleRequest.canonicalBytes())) { - throw new IllegalStateException( - "Durable initial-admission intent readback changed the exact request tuple"); - } - } - - private static void requireExactHoldIdentity(HoldIdentity identity, Request request) { - if (identity == null - || !Arrays.equals(identity.canonicalRequestBytes(), request.canonicalRequestBytes()) - || !Arrays.equals( - identity.request().canonicalRequestBytes(), request.canonicalRequestBytes()) - || !identity.holdBindingDigest().equals(request.holdBindingDigest())) { - throw new IllegalStateException( - "World initial-admission hold identity did not echo the exact retained request"); - } - } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java index 421f2ea4d5..86e4582ed5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java @@ -3,27 +3,20 @@ import java.util.Objects; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; -import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; /** - * Durable owner operation. Reservation and terminal mutation use short owner transactions; remote - * World proof and owner readbacks run between them outside SQL. + * Canonical Human mutation entry remains denied until Account terminal protection is available. + * Explicit owner reads preserve their existing read-only boundary. */ public final class DatabaseCanonicalInitialAdmissionService implements CanonicalInitialAdmissionService { private final CanonicalInitialAdmissionRepository repository; - private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; - private final CanonicalInitialAdmissionWorldVerifier worldVerifier; - private final TransactionTemplate ownerWriteTransaction; public DatabaseCanonicalInitialAdmissionService( CanonicalInitialAdmissionRepository repository, @@ -31,46 +24,16 @@ public DatabaseCanonicalInitialAdmissionService( CanonicalInitialAdmissionWorldVerifier worldVerifier, PlatformTransactionManager transactionManager) { this.repository = Objects.requireNonNull(repository, "repository"); - this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); - this.worldVerifier = Objects.requireNonNull(worldVerifier, "worldVerifier"); - this.ownerWriteTransaction = - new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); - this.ownerWriteTransaction.setPropagationBehavior( - TransactionDefinition.PROPAGATION_REQUIRES_NEW); - this.ownerWriteTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - this.ownerWriteTransaction.setReadOnly(false); + Objects.requireNonNull(pointerRepository, "pointerRepository"); + Objects.requireNonNull(worldVerifier, "worldVerifier"); + Objects.requireNonNull(transactionManager, "transactionManager"); } @Override public CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request) { requireNoAmbientTransaction(); Objects.requireNonNull(request, "request"); - ownerWriteTransaction.executeWithoutResult(status -> repository.reserve(request)); - CanonicalInitialAdmissionOwnerProof beforeRemote = - requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); - if (beforeRemote.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { - return beforeRemote; - } - - PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); - // This owner call is intentionally outside the repository transaction and can be retried by - // the stable durable request identity after an unavailable or ambiguous response. - CanonicalInitialAdmissionWorldProof worldProof = worldVerifier.verify(request); - if (worldProof == null) { - throw new IllegalStateException("World initial-admission verifier returned no owner proof"); - } - worldProof.requireMatches(request); - ownerWriteTransaction.executeWithoutResult( - status -> repository.commit(request, worldProof, preparedOrigin)); - - CanonicalInitialAdmissionOwnerProof result = - requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); - if (result.outcome() == CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { - throw new CanonicalInitialAdmissionRepository - .CanonicalInitialAdmissionReconciliationRequiredException( - "Initial-admission owner transaction did not produce an exact terminal result readback"); - } - return result; + throw CanonicalInitialAdmissionRepository.unavailableHumanAdmissionProtection(); } @Override @@ -78,16 +41,7 @@ public CanonicalInitialAdmissionOwnerProof abort( CanonicalInitialAdmissionRequest request, String reason) { requireNoAmbientTransaction(); Objects.requireNonNull(request, "request"); - ownerWriteTransaction.executeWithoutResult(status -> repository.reserve(request)); - CanonicalInitialAdmissionOwnerProof beforeAbort = - requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); - if (beforeAbort.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { - return beforeAbort; - } - PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); - ownerWriteTransaction.executeWithoutResult( - status -> repository.abort(request, preparedOrigin, reason)); - return requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + throw CanonicalInitialAdmissionRepository.unavailableHumanAdmissionProtection(); } @Override @@ -103,18 +57,6 @@ private static void requireNoAmbientTransaction() { } } - private PreparedExpectedClosed prepareExpectedClosed(CanonicalInitialAdmissionRequest request) { - if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { - return null; - } - return pointerRepository.prepareExpectedClosedForRealm( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.expectedPriorPointerVersion(), - request.expectedCatalogRevision()); - } - private CanonicalInitialAdmissionOwnerProof requireRead( String targetNamespace, String requestId) { return repository diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index bfe78ed281..9dda03ccb7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -13,10 +14,15 @@ import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; @@ -45,6 +51,8 @@ import net.firedevops.firemud.gamesession.v1.GetRemoteFollowupResponse; import net.firedevops.firemud.gamesession.v1.GetRemoteFollowupResultRequest; import net.firedevops.firemud.gamesession.v1.GetRemoteFollowupResultResponse; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse; import net.firedevops.firemud.gamesession.v1.GetRuntimeOwnershipStatusRequest; import net.firedevops.firemud.gamesession.v1.GetRuntimeOwnershipStatusResponse; import net.firedevops.firemud.gamesession.v1.InitialAdmissionBindOwnerProofOutcome; @@ -90,6 +98,7 @@ import org.springframework.dao.QueryTimeoutException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.support.TransactionSynchronizationManager; @GrpcService @SuppressFBWarnings( @@ -112,6 +121,9 @@ public final class GameSessionControlPlaneGrpcService private final MeterRegistry meterRegistry; private InitialAdmissionBindOwnerProofReader initialAdmissionBindOwnerProofReader; private InitialAdmissionBindOwnerReadWorkloadGuard initialAdmissionBindOwnerReadWorkloadGuard; + private RunOwnedCanonicalLaunchPreparationOwner runOwnedLaunchPreparationOwner; + private String fixtureReadWorkloadNamespace; + private boolean fixtureLaunchReadEnabled; private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); @@ -145,6 +157,16 @@ public void configureInitialAdmissionBindOwnerReadBoundary( new InitialAdmissionBindOwnerReadWorkloadGuard(workloadNamespace); } + @Autowired(required = false) + public void configureRunOwnedFixtureLaunchAssociationReadBoundary( + RunOwnedCanonicalLaunchPreparationOwner fixtureOwner, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean fixtureEnabled, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.runOwnedLaunchPreparationOwner = fixtureOwner; + this.fixtureLaunchReadEnabled = fixtureEnabled; + this.fixtureReadWorkloadNamespace = workloadNamespace; + } + private long parseTenantId(String tenantId) { return ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_id"); } @@ -285,6 +307,126 @@ public void getInitialAdmissionBindProof( responseObserver.onCompleted(); } + /** + * Fixed, default-off read of the exact verified fixture source and its immutable GS owner row. + */ + @Override + @Timed(value = "gamesessionGrpc.controlPlane.getRunOwnedFixtureLaunchAssociation") + public void getRunOwnedFixtureLaunchAssociation( + GetRunOwnedFixtureLaunchAssociationRequest request, + StreamObserver responseObserver) { + Objects.requireNonNull(responseObserver, "responseObserver"); + try { + requireWorldFixtureLaunchAssociationReadCaller(); + if (!fixtureLaunchReadEnabled || runOwnedLaunchPreparationOwner == null) { + throw new IllegalStateException("Fixed fixture owner read is disabled"); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Fixture launch owner read cannot run inside an ambient transaction"); + } + if (request == null) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture launch owner selector is invalid") + .asRuntimeException()); + return; + } + + // Authentication and the fixed default-off boundary precede strict wire decoding. + RunOwnedInitialAdmissionLaunchEvidence evidence = + runOwnedLaunchPreparationOwner.loadFixedVerifiedEvidenceForWorldPeer(); + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest selector; + try { + selector = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request); + } catch (IllegalArgumentException malformedSelector) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture launch owner selector is invalid") + .asRuntimeException()); + return; + } + if (!fixtureReadWorkloadNamespace.equals(selector.targetNamespace()) + || !evidence.sourceEvidence().targetNamespace().equals(selector.targetNamespace()) + || !evidence + .fixtureCapability() + .operationId() + .equals(selector.fixtureOperationId().toString()) + || !evidence + .fixturePolicySeal() + .evidenceDigest() + .equals(selector.expectedFixturePolicyEvidenceDigest())) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture launch owner selector is invalid") + .asRuntimeException()); + return; + } + + var launch = runOwnedLaunchPreparationOwner.readFixedFixtureLaunch(evidence); + var catalog = launch.catalog().snapshot(); + var result = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + selector, + launch.catalog().association().gameSessionTenantId(), + launch.gameInstanceId(), + catalog.tenantId(), + launch.gameInstanceUuid(), + UUID.fromString(evidence.publishedReleaseBundle().getCanonicalVersionId()), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.catalogRevision(), + launch.status(), + launch.rowVersion(), + evidence.fixturePolicyRequestBytes(), + evidence.fixturePolicySeal()); + responseObserver.onNext( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(result)); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException unauthorized) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Fixture launch owner read is not authorized") + .asRuntimeException()); + } catch (IllegalArgumentException invalidOwnerState) { + logger.warn("GetRunOwnedFixtureLaunchAssociation rejected; category=INVALID_OWNER_STATE"); + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact fixed fixture launch owner read is unavailable") + .asRuntimeException()); + } catch (IllegalStateException unavailable) { + logger.warn("GetRunOwnedFixtureLaunchAssociation rejected; category=OWNER_READ_UNAVAILABLE"); + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact fixed fixture launch owner read is unavailable") + .asRuntimeException()); + } catch (RuntimeException failure) { + logger.error("GetRunOwnedFixtureLaunchAssociation failed", failure); + responseObserver.onError( + Status.INTERNAL.withDescription("Fixture launch owner read failed").asRuntimeException()); + } + } + + private void requireWorldFixtureLaunchAssociationReadCaller() { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (!GameSessionControlPlaneServiceGrpc.getGetRunOwnedFixtureLaunchAssociationMethod() + .getFullMethodName() + .equals( + "game_session.v1.GameSessionControlPlaneService/GetRunOwnedFixtureLaunchAssociation") + || fixtureReadWorkloadNamespace == null + || !GrpcPeerIdentity.isValidNamespace(fixtureReadWorkloadNamespace) + || peerIdentity == null + || !"world-management-service".equals(peerIdentity.service()) + || !fixtureReadWorkloadNamespace.equals(peerIdentity.namespace()) + || !("spiffe://firemud/ns/" + fixtureReadWorkloadNamespace + "/sa/world-management-service") + .equals(peerIdentity.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Fixture launch read requires the exact authenticated World Management workload peer"); + } + } + private GetInitialAdmissionBindProofResponse.Builder echoInitialAdmissionBindTuple( GetInitialAdmissionBindProofRequest request) { return GetInitialAdmissionBindProofResponse.newBuilder() diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 9f724ecca8..c9807bb544 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -132,6 +132,7 @@ firemud: force-internal-service-outbound: true public-methods: - game_session.v1.GameSessionService/Ping + - game_session.v1.GameSessionControlPlaneService/GetRunOwnedFixtureLaunchAssociation - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead - game_session.v1.GameSessionService/AuthorizeStartSession diff --git a/services/game-session-service/src/main/resources/db/migration/V1003__fresh_tenant_complete_creation_evidence.sql b/services/game-session-service/src/main/resources/db/migration/V1003__fresh_tenant_complete_creation_evidence.sql new file mode 100644 index 0000000000..610e03e803 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1003__fresh_tenant_complete_creation_evidence.sql @@ -0,0 +1,71 @@ +-- Preserve the complete immutable Game Design receipt on new Game Session associations. +-- Historical V25 rows remain nullable and are not reconstructed from their partial columns. +ALTER TABLE game_session_fresh_tenant_association + ADD COLUMN complete_source_evidence JSONB; + +-- [jooq ignore start] +CREATE FUNCTION validate_game_session_fresh_tenant_complete_source_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + evidence JSONB; +BEGIN + evidence := NEW.complete_source_evidence; + IF evidence IS NULL THEN + RAISE EXCEPTION 'Fresh Game Session tenant association requires complete source evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + IF jsonb_typeof(evidence) IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'Fresh Game Session tenant source evidence must be an object' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + IF (SELECT COUNT(*) FROM jsonb_object_keys(evidence)) <> 10 + OR NOT (evidence ?& ARRAY[ + 'schemaVersion', 'targetNamespace', 'creationRequestId', 'operationId', + 'requestDigest', 'canonicalTenantId', 'sourceGameRowId', + 'sourceGameTenantKey', 'provenanceKind', 'evidenceDigest' + ]) THEN + RAISE EXCEPTION 'Fresh Game Session tenant source evidence has an incomplete or open shape' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + + IF jsonb_typeof(evidence -> 'schemaVersion') IS DISTINCT FROM 'number' + OR evidence ->> 'schemaVersion' IS DISTINCT FROM NEW.source_schema_version::TEXT + OR jsonb_typeof(evidence -> 'targetNamespace') IS DISTINCT FROM 'string' + OR evidence ->> 'targetNamespace' IS DISTINCT FROM NEW.source_target_namespace + OR NEW.source_target_namespace IS DISTINCT FROM NEW.target_namespace + OR jsonb_typeof(evidence -> 'creationRequestId') IS DISTINCT FROM 'string' + OR evidence ->> 'creationRequestId' IS DISTINCT FROM NEW.source_request_id::TEXT + OR NEW.source_request_id IS DISTINCT FROM NEW.association_request_id + OR jsonb_typeof(evidence -> 'operationId') IS DISTINCT FROM 'string' + OR (evidence ->> 'operationId') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR evidence ->> 'operationId' = '00000000-0000-0000-0000-000000000000' + OR jsonb_typeof(evidence -> 'requestDigest') IS DISTINCT FROM 'string' + OR (evidence ->> 'requestDigest') !~ '^sha256:[0-9a-f]{64}$' + OR jsonb_typeof(evidence -> 'canonicalTenantId') IS DISTINCT FROM 'string' + OR evidence ->> 'canonicalTenantId' IS DISTINCT FROM NEW.source_canonical_tenant_id::TEXT + OR NEW.source_canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR jsonb_typeof(evidence -> 'sourceGameRowId') IS DISTINCT FROM 'number' + OR evidence ->> 'sourceGameRowId' IS DISTINCT FROM NEW.source_game_row_id::TEXT + OR jsonb_typeof(evidence -> 'sourceGameTenantKey') IS DISTINCT FROM 'string' + OR evidence ->> 'sourceGameTenantKey' IS DISTINCT FROM NEW.source_game_tenant_key + OR jsonb_typeof(evidence -> 'provenanceKind') IS DISTINCT FROM 'string' + OR evidence ->> 'provenanceKind' IS DISTINCT FROM NEW.provenance_kind + OR jsonb_typeof(evidence -> 'evidenceDigest') IS DISTINCT FROM 'string' + OR (evidence ->> 'evidenceDigest') !~ '^sha256:[0-9a-f]{64}$' THEN + RAISE EXCEPTION 'Fresh Game Session tenant source evidence differs from its immutable receipt columns' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_fresh_tenant_complete_source_evidence'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_fresh_tenant_complete_source_evidence_guard + BEFORE INSERT ON game_session_fresh_tenant_association + FOR EACH ROW EXECUTE FUNCTION validate_game_session_fresh_tenant_complete_source_evidence(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1004__canonical_catalog_complete_policy_evidence.sql b/services/game-session-service/src/main/resources/db/migration/V1004__canonical_catalog_complete_policy_evidence.sql new file mode 100644 index 0000000000..23e4dd0fa4 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1004__canonical_catalog_complete_policy_evidence.sql @@ -0,0 +1,30 @@ +-- Preserve the complete immutable Game Design publication policy set that authorized a fresh +-- public-production realm. Historical V23 catalog rows remain readable as historical catalog +-- state but are deliberately not reconstructed or adopted as complete published evidence. +ALTER TABLE game_session_canonical_realm_catalog + ADD COLUMN complete_policy_set_evidence BYTEA; + +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT chk_gs_canonical_realm_catalog_complete_policy_evidence + CHECK (complete_policy_set_evidence IS NULL OR octet_length(complete_policy_set_evidence) > 0); + +-- [jooq ignore start] +CREATE FUNCTION require_game_session_canonical_realm_complete_policy_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.complete_policy_set_evidence IS NULL + OR octet_length(NEW.complete_policy_set_evidence) = 0 THEN + RAISE EXCEPTION 'New canonical realm catalog row requires complete published policy evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_canonical_realm_catalog_complete_policy_evidence'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_realm_requires_complete_policy_evidence + BEFORE INSERT ON game_session_canonical_realm_catalog + FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_realm_complete_policy_evidence(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1005__canonical_launch_exact_catalog_identity.sql b/services/game-session-service/src/main/resources/db/migration/V1005__canonical_launch_exact_catalog_identity.sql new file mode 100644 index 0000000000..368bdf1847 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1005__canonical_launch_exact_catalog_identity.sql @@ -0,0 +1,68 @@ +-- Keep the complete original operator tuple and exact source-backed catalog identity with each +-- newly created canonical launch. Retained V26 rows remain unqualified and are not backfilled. +ALTER TABLE game_session_canonical_instance_launch + ADD COLUMN original_start_session_tuple BYTEA, + ADD COLUMN catalog_creation_request_id UUID, + ADD COLUMN catalog_revision BIGINT, + ADD COLUMN catalog_source_intake_operation_id UUID, + ADD COLUMN catalog_source_intake_request_id UUID, + ADD CONSTRAINT chk_gs_canonical_instance_launch_original_tuple + CHECK (original_start_session_tuple IS NULL + OR octet_length(original_start_session_tuple) BETWEEN 1 AND 262144), + ADD CONSTRAINT chk_gs_canonical_instance_launch_catalog_identity + CHECK ((original_start_session_tuple IS NULL + AND catalog_creation_request_id IS NULL + AND catalog_revision IS NULL + AND catalog_source_intake_operation_id IS NULL + AND catalog_source_intake_request_id IS NULL) + OR (original_start_session_tuple IS NOT NULL + AND catalog_creation_request_id IS NOT NULL + AND catalog_revision IS NOT NULL + AND catalog_revision > 0 + AND catalog_source_intake_operation_id IS NOT NULL + AND catalog_source_intake_request_id IS NOT NULL + AND catalog_source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID)); +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT uq_gs_canonical_realm_catalog_exact_launch_key + UNIQUE (target_namespace, canonical_tenant_id, realm_id, creation_request_id, + catalog_revision, source_intake_operation_id, source_intake_request_id); + +ALTER TABLE game_session_canonical_instance_launch + ADD CONSTRAINT fk_gs_canonical_instance_launch_exact_catalog + FOREIGN KEY (target_namespace, canonical_tenant_id, canonical_realm_id, + catalog_creation_request_id, catalog_revision, + catalog_source_intake_operation_id, catalog_source_intake_request_id) + REFERENCES game_session_canonical_realm_catalog + (target_namespace, canonical_tenant_id, realm_id, creation_request_id, + catalog_revision, source_intake_operation_id, source_intake_request_id); + +-- Historical rows are intentionally permitted to retain all five nullable fields. Every new +-- launch, however, must be source-backed and revision-qualified at insertion time. +-- [jooq ignore start] +CREATE FUNCTION require_complete_canonical_launch_catalog_identity() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.original_start_session_tuple IS NULL + OR octet_length(NEW.original_start_session_tuple) NOT BETWEEN 1 AND 262144 + OR NEW.catalog_creation_request_id IS NULL + OR NEW.catalog_revision IS NULL + OR NEW.catalog_revision <= 0 + OR NEW.catalog_source_intake_operation_id IS NULL + OR NEW.catalog_source_intake_request_id IS NULL + OR NEW.catalog_source_intake_operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_source_intake_request_id = '00000000-0000-0000-0000-000000000000'::UUID THEN + RAISE EXCEPTION 'New canonical instance launch requires the complete original tuple and exact catalog identity' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_canonical_instance_launch_catalog_identity'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_instance_launch_complete_catalog_identity + BEFORE INSERT ON game_session_canonical_instance_launch + FOR EACH ROW EXECUTE FUNCTION require_complete_canonical_launch_catalog_identity(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1006__canonical_initial_admission_terminal_protection.sql b/services/game-session-service/src/main/resources/db/migration/V1006__canonical_initial_admission_terminal_protection.sql new file mode 100644 index 0000000000..ef093cb726 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1006__canonical_initial_admission_terminal_protection.sql @@ -0,0 +1,559 @@ +-- Retain complete Account source-protection evidence on the existing V28 terminal owner row. +-- Historical V28 rows remain nullable and are not backfilled or adopted as original attempts. +-- V35's original-attempt relation is intentionally absent from the jOOQ DDL simulator. +-- Keep only its cross-relation constraints out of simulation; all V28 columns stay visible. +-- [jooq ignore start] +ALTER TABLE game_session_start_session_operator_attempt + ADD CONSTRAINT uq_gs_start_session_operator_namespace_attempt + UNIQUE (target_namespace, owner_attempt_id); +-- [jooq ignore stop] + +ALTER TABLE game_session_canonical_initial_admission_intent + ADD COLUMN catalog_source_intake_operation_id UUID, + ADD COLUMN catalog_source_intake_request_id UUID, + ADD COLUMN original_start_session_tuple BYTEA, + ADD CONSTRAINT chk_gs_initial_admission_intent_v44_launch_evidence + CHECK ((catalog_source_intake_operation_id IS NULL + AND catalog_source_intake_request_id IS NULL + AND original_start_session_tuple IS NULL) + OR (catalog_source_intake_operation_id IS NOT NULL + AND catalog_source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_source_intake_request_id IS NOT NULL + AND catalog_source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_start_session_tuple IS NOT NULL + AND octet_length(original_start_session_tuple) BETWEEN 1 AND 262144)); + +-- V28's procedural owner-ledger creation is also absent from simulated metadata. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_initial_admission_attempt + ADD COLUMN account_protection_evidence_version INTEGER, + ADD COLUMN account_protection_id UUID, + ADD COLUMN account_protection_fence BIGINT, + ADD COLUMN original_owner_attempt_id UUID, + ADD COLUMN original_owner_mutation_id UUID, + ADD COLUMN original_owner_fence BIGINT, + ADD COLUMN account_protection_evidence_bytes BYTEA, + ADD CONSTRAINT chk_gs_initial_admission_account_protection_evidence_complete + CHECK ( + (account_protection_evidence_version IS NULL + AND account_protection_id IS NULL + AND account_protection_fence IS NULL + AND original_owner_attempt_id IS NULL + AND original_owner_mutation_id IS NULL + AND original_owner_fence IS NULL + AND account_protection_evidence_bytes IS NULL) + OR (account_protection_evidence_version = 1 + AND account_protection_id IS NOT NULL + AND account_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_protection_fence > 0 + AND original_owner_attempt_id IS NOT NULL + AND original_owner_mutation_id IS NOT NULL + AND original_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_owner_fence > 0 + AND account_protection_evidence_bytes IS NOT NULL + AND octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 8388608)), + ADD CONSTRAINT chk_gs_initial_admission_terminal_requires_protection + CHECK (status = 'PENDING' + OR account_protection_evidence_version IS NULL + OR account_protection_evidence_version = 1); + +CREATE UNIQUE INDEX uq_gs_initial_admission_protected_original_attempt + ON game_session_canonical_initial_admission_attempt (target_namespace, original_owner_attempt_id) + WHERE original_owner_attempt_id IS NOT NULL; +CREATE UNIQUE INDEX uq_gs_initial_admission_account_protection + ON game_session_canonical_initial_admission_attempt (target_namespace, account_protection_id) + WHERE account_protection_id IS NOT NULL; + +ALTER TABLE game_session_canonical_initial_admission_attempt + ADD CONSTRAINT fk_gs_initial_admission_original_owner + FOREIGN KEY (target_namespace, original_owner_attempt_id) + REFERENCES game_session_start_session_operator_attempt (target_namespace, owner_attempt_id); + +CREATE FUNCTION require_game_session_canonical_initial_admission_account_terminal_evidence() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + selected_intent game_session_canonical_initial_admission_intent%ROWTYPE; + selected_launch game_session_canonical_instance_launch%ROWTYPE; + selected_catalog game_session_canonical_realm_catalog%ROWTYPE; + selected_original game_session_start_session_operator_attempt%ROWTYPE; + evidence_json JSONB; + evidence_request_bytes BYTEA; + evidence_request JSONB; + evidence_tuple_bytes BYTEA; + evidence_projection_bytes BYTEA; + evidence_hold_bytes BYTEA; + hold_json JSONB; + hold_request_json JSONB; + expected_request_digest TEXT; + digest_bytes BYTEA; + domain_bytes BYTEA; + empty_bytes BYTEA := ''::BYTEA; + field_bytes BYTEA; + terminal_at_text TEXT; +BEGIN + IF TG_TABLE_NAME = 'game_session_canonical_initial_admission_intent' THEN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Canonical initial-admission intents are durable survivor evidence' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PENDING_HOLD' + OR NEW.hold_identity_bytes IS NOT NULL + OR NEW.terminal_at IS NOT NULL THEN + RAISE EXCEPTION 'New canonical initial-admission intents must begin before World hold acquisition' + USING ERRCODE = '23514'; + END IF; + SELECT * INTO selected_launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = NEW.control_plane_request_id; + SELECT * INTO selected_catalog + FROM game_session_canonical_realm_catalog + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND realm_id = NEW.realm_id; + BEGIN + hold_request_json := convert_from(NEW.canonical_hold_request_bytes, 'UTF8')::JSONB; + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'New initial-admission intent request bytes are not structurally readable' + USING ERRCODE = '23514'; + END; + IF hold_request_json ->> 'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json -> 'request') IS DISTINCT FROM 'object' THEN + RAISE EXCEPTION 'New initial-admission intent request has an unsupported schema or shape' + USING ERRCODE = '23514'; + END IF; + digest_bytes := ''::BYTEA; + domain_bytes := convert_to('game-session-canonical-initial-admission/v1', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'targetNamespace', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'canonicalTenantId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'worldSlug', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'realmId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'playableStateNamespaceId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'playableStateScope', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'canonicalGameInstanceId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'canonicalVersionId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'activeLifecycleEpoch', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'expectedCatalogRevision', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'initialAdmissionOrigin', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(hold_request_json -> 'request' ->> 'expectedPriorPointerVersion', ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(hold_request_json -> 'request' ->> 'initialAdmissionRequestId', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + expected_request_digest := encode(sha256(digest_bytes), 'hex'); + IF NEW.original_start_session_tuple IS NULL + OR octet_length(NEW.original_start_session_tuple) NOT BETWEEN 1 AND 262144 + OR selected_launch.target_namespace IS NULL + OR selected_catalog.target_namespace IS NULL + OR selected_launch.original_start_session_tuple IS DISTINCT FROM NEW.original_start_session_tuple + OR selected_launch.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR selected_launch.canonical_realm_id IS DISTINCT FROM NEW.realm_id + OR selected_launch.world_slug IS DISTINCT FROM NEW.world_slug + OR selected_launch.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR selected_launch.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR selected_launch.game_instance_uuid IS DISTINCT FROM NEW.canonical_game_instance_id + OR selected_launch.game_session_tenant_id IS DISTINCT FROM NEW.game_session_tenant_id + OR selected_launch.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR selected_launch.version_id IS DISTINCT FROM NEW.runtime_version_id + OR selected_launch.tenant_association_operation_id IS DISTINCT FROM NEW.tenant_association_operation_id + OR selected_launch.launch_descriptor_id IS DISTINCT FROM NEW.launch_descriptor_id + OR selected_launch.captured_starting_row_version IS DISTINCT FROM NEW.captured_starting_row_version + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + IS DISTINCT FROM NEW.descriptor_request_digest + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + IS DISTINCT FROM NEW.descriptor_result_digest + OR selected_launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + IS DISTINCT FROM NEW.release_attestation_digest + OR selected_launch.catalog_creation_request_id IS DISTINCT FROM NEW.catalog_creation_request_id + OR selected_launch.catalog_revision IS DISTINCT FROM NEW.catalog_revision + OR selected_launch.catalog_source_intake_operation_id IS DISTINCT FROM NEW.catalog_source_intake_operation_id + OR selected_launch.catalog_source_intake_request_id IS DISTINCT FROM NEW.catalog_source_intake_request_id + OR selected_catalog.world_slug IS DISTINCT FROM NEW.world_slug + OR selected_catalog.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR selected_catalog.catalog_revision IS DISTINCT FROM NEW.catalog_revision + OR selected_catalog.creation_request_id IS DISTINCT FROM NEW.catalog_creation_request_id + OR selected_catalog.source_intake_operation_id IS DISTINCT FROM NEW.catalog_source_intake_operation_id + OR selected_catalog.source_intake_request_id IS DISTINCT FROM NEW.catalog_source_intake_request_id + OR selected_catalog.request_digest IS DISTINCT FROM NEW.catalog_request_digest + OR selected_catalog.receipt_digest IS DISTINCT FROM NEW.catalog_receipt_digest + OR selected_catalog.visible IS DISTINCT FROM TRUE + OR selected_catalog.public_production IS DISTINCT FROM TRUE + OR selected_catalog.state_scope IS DISTINCT FROM 'SHARED' + OR hold_request_json -> 'request' ->> 'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR hold_request_json -> 'request' ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR hold_request_json -> 'request' ->> 'worldSlug' IS DISTINCT FROM NEW.world_slug + OR hold_request_json -> 'request' ->> 'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR hold_request_json -> 'request' ->> 'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR hold_request_json -> 'request' ->> 'canonicalVersionId' + IS DISTINCT FROM (NEW.canonical_version_id)::TEXT + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.request_digest + OR hold_request_json -> 'request' ->> 'expectedCatalogRevision' IS DISTINCT FROM NEW.catalog_revision::TEXT + OR (hold_request_json -> 'request' ->> 'initialAdmissionOrigin' + IS DISTINCT FROM 'NO_PRIOR_POINTER' + AND hold_request_json -> 'request' ->> 'initialAdmissionOrigin' + IS DISTINCT FROM 'EXPECT_CLOSED') + OR (hold_request_json -> 'request' ->> 'initialAdmissionOrigin' = 'NO_PRIOR_POINTER' + AND hold_request_json -> 'request' ->> 'expectedPriorPointerVersion' IS NOT NULL) + OR (hold_request_json -> 'request' ->> 'initialAdmissionOrigin' = 'EXPECT_CLOSED' + AND hold_request_json -> 'request' ->> 'expectedPriorPointerVersion' IS DISTINCT FROM '1') + OR hold_request_json -> 'request' ->> 'activeLifecycleEpoch' IS NULL + OR hold_request_json -> 'request' ->> 'activeLifecycleEpoch' !~ '^[1-9][0-9]{0,18}$' + OR NEW.request_digest <> expected_request_digest + THEN + RAISE EXCEPTION 'New initial-admission intent must retain the exact V43 launch tuple and catalog binding' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF (to_jsonb(NEW) - 'state' - 'updated_at' - 'terminal_at' - 'hold_identity_bytes') + IS DISTINCT FROM + (to_jsonb(OLD) - 'state' - 'updated_at' - 'terminal_at' - 'hold_identity_bytes') THEN + RAISE EXCEPTION 'Canonical initial-admission intent identity is immutable' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'PENDING_HOLD' + AND NEW.state = 'HOLD_ATTACHED' + AND OLD.hold_identity_bytes IS NULL + AND NEW.hold_identity_bytes IS NOT NULL + AND NEW.terminal_at IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'HOLD_ATTACHED' + AND NEW.state = 'TERMINAL' + AND OLD.hold_identity_bytes IS NOT NULL + AND NEW.hold_identity_bytes = OLD.hold_identity_bytes + AND NEW.terminal_at IS NOT NULL + AND EXISTS ( + SELECT 1 FROM game_session_canonical_initial_admission_attempt attempt + WHERE attempt.target_namespace = NEW.target_namespace + AND attempt.initial_admission_request_id = NEW.initial_admission_request_id + AND attempt.status IN ('COMMITTED', 'ABORTED') + AND attempt.account_protection_evidence_version = 1 + AND attempt.account_protection_evidence_bytes IS NOT NULL + AND attempt.terminal_at = NEW.terminal_at) + THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Canonical initial-admission intent permits only one exact hold attach and terminal transition' + USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Canonical initial-admission attempts cannot be deleted' + USING ERRCODE = '23514'; + END IF; + + IF TG_OP = 'INSERT' AND NEW.status <> 'PENDING' THEN + RAISE EXCEPTION 'New canonical initial-admission attempts must begin PENDING' + USING ERRCODE = '23514'; + END IF; + + IF NEW.status = 'PENDING' THEN + IF NEW.account_protection_evidence_version IS NOT NULL + OR NEW.account_protection_id IS NOT NULL + OR NEW.account_protection_fence IS NOT NULL + OR NEW.original_owner_attempt_id IS NOT NULL + OR NEW.original_owner_mutation_id IS NOT NULL + OR NEW.original_owner_fence IS NOT NULL + OR NEW.account_protection_evidence_bytes IS NOT NULL THEN + RAISE EXCEPTION 'PENDING initial-admission attempts cannot carry terminal Account protection' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.status NOT IN ('COMMITTED', 'ABORTED') + OR NEW.account_protection_evidence_version IS DISTINCT FROM 1 + OR NEW.account_protection_id IS NULL + OR NEW.account_protection_fence IS NULL + OR NEW.account_protection_fence <= 0 + OR NEW.original_owner_attempt_id IS NULL + OR NEW.original_owner_mutation_id IS NULL + OR NEW.original_owner_fence IS NULL + OR NEW.original_owner_fence <= 0 + OR NEW.account_protection_evidence_bytes IS NULL + OR octet_length(NEW.account_protection_evidence_bytes) NOT BETWEEN 1 AND 8388608 + THEN + RAISE EXCEPTION 'New canonical initial-admission terminal requires complete retained Account protection evidence' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_initial_admission_terminal_requires_protection'; + END IF; + + IF TG_OP = 'UPDATE' + AND (OLD.status <> 'PENDING' + OR OLD.account_protection_evidence_version IS NOT NULL + OR OLD.account_protection_id IS NOT NULL + OR OLD.account_protection_fence IS NOT NULL + OR OLD.original_owner_attempt_id IS NOT NULL + OR OLD.original_owner_mutation_id IS NOT NULL + OR OLD.original_owner_fence IS NOT NULL + OR OLD.account_protection_evidence_bytes IS NOT NULL) + THEN + RAISE EXCEPTION 'Terminal Account protection evidence is immutable' + USING ERRCODE = '23514'; + END IF; + + SELECT * INTO selected_intent + FROM game_session_canonical_initial_admission_intent + WHERE target_namespace = NEW.target_namespace + AND initial_admission_request_id = NEW.initial_admission_request_id; + SELECT * INTO selected_launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = selected_intent.control_plane_request_id; + SELECT * INTO selected_catalog + FROM game_session_canonical_realm_catalog + WHERE target_namespace = NEW.target_namespace + AND canonical_tenant_id = NEW.canonical_tenant_id + AND realm_id = NEW.realm_id; + SELECT * INTO selected_original + FROM game_session_start_session_operator_attempt + WHERE target_namespace = NEW.target_namespace + AND control_plane_request_id = selected_intent.control_plane_request_id + AND owner_attempt_id = NEW.original_owner_attempt_id; + + IF selected_intent.target_namespace IS NULL + OR selected_intent.state <> 'HOLD_ATTACHED' + OR selected_intent.terminal_at IS NOT NULL + OR selected_intent.hold_identity_bytes IS NULL + OR selected_launch.target_namespace IS NULL + OR selected_catalog.target_namespace IS NULL + OR selected_original.target_namespace IS NULL + OR selected_original.phase_state <> 'OWNER_EXECUTION_PENDING' + OR selected_intent.request_digest <> NEW.request_digest + OR selected_intent.canonical_tenant_id <> NEW.canonical_tenant_id + OR selected_intent.world_slug <> NEW.world_slug + OR selected_intent.realm_id <> NEW.realm_id + OR selected_intent.playable_state_namespace_id <> NEW.playable_state_namespace_id + OR selected_intent.playable_state_scope <> NEW.playable_state_scope + OR selected_intent.canonical_game_instance_id <> NEW.canonical_game_instance_id + OR selected_intent.canonical_version_id <> NEW.canonical_version_id + OR selected_intent.game_session_tenant_id <> NEW.game_session_tenant_id + OR selected_intent.game_instance_id <> NEW.game_instance_id + OR selected_intent.runtime_version_id <> NEW.runtime_version_id + OR selected_intent.catalog_revision <> NEW.expected_catalog_revision + OR selected_intent.control_plane_request_id <> selected_original.control_plane_request_id + OR selected_launch.original_start_session_tuple <> selected_original.post_authorization_execution_tuple + OR selected_launch.original_start_session_tuple IS NULL + OR selected_intent.original_start_session_tuple IS DISTINCT FROM selected_launch.original_start_session_tuple + OR selected_intent.launch_descriptor_id <> selected_launch.launch_descriptor_id + OR selected_intent.captured_starting_row_version <> selected_launch.captured_starting_row_version + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + IS DISTINCT FROM selected_intent.descriptor_request_digest + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + IS DISTINCT FROM selected_intent.descriptor_result_digest + OR selected_launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + IS DISTINCT FROM selected_intent.release_attestation_digest + OR selected_intent.tenant_association_operation_id <> selected_launch.tenant_association_operation_id + OR selected_intent.catalog_source_intake_operation_id <> selected_launch.catalog_source_intake_operation_id + OR selected_intent.catalog_source_intake_request_id <> selected_launch.catalog_source_intake_request_id + OR selected_original.owner_mutation_id <> NEW.original_owner_mutation_id + OR selected_original.owner_fence <> NEW.original_owner_fence + OR selected_original.lease_expires_at <= clock_timestamp() + OR selected_original.canonical_tenant_id <> NEW.canonical_tenant_id + OR selected_catalog.creation_request_id <> selected_intent.catalog_creation_request_id + OR selected_catalog.catalog_revision <> selected_intent.catalog_revision + OR selected_catalog.source_intake_operation_id <> selected_intent.catalog_source_intake_operation_id + OR selected_catalog.source_intake_request_id <> selected_intent.catalog_source_intake_request_id + OR selected_catalog.request_digest <> selected_intent.catalog_request_digest + OR selected_catalog.receipt_digest <> selected_intent.catalog_receipt_digest + OR selected_launch.catalog_creation_request_id <> selected_catalog.creation_request_id + OR selected_launch.catalog_revision <> selected_catalog.catalog_revision + OR selected_launch.catalog_source_intake_operation_id <> selected_catalog.source_intake_operation_id + OR selected_launch.catalog_source_intake_request_id <> selected_catalog.source_intake_request_id + OR selected_launch.playable_state_scope <> selected_catalog.state_scope + OR selected_launch.public_production IS NOT TRUE + OR selected_catalog.visible IS NOT TRUE + OR selected_catalog.public_production IS NOT TRUE + OR selected_catalog.state_scope <> 'SHARED' + THEN + RAISE EXCEPTION 'Terminal Account protection is not linked to the exact V28 intent, V43 launch/catalog, and V35 original owner' + USING ERRCODE = '23514'; + END IF; + + BEGIN + evidence_json := convert_from(NEW.account_protection_evidence_bytes, 'UTF8')::JSONB; + evidence_request_bytes := decode(evidence_json ->> 'requestBytesBase64', 'base64'); + evidence_request := convert_from(evidence_request_bytes, 'UTF8')::JSONB; + evidence_tuple_bytes := decode(evidence_request ->> 'originalPostAuthorizationTupleBytesBase64', 'base64'); + evidence_projection_bytes := decode(evidence_request ->> 'accountRedemptionProjectionBytesBase64', 'base64'); + evidence_hold_bytes := decode(evidence_request ->> 'worldAdmissionHoldIdentityBytesBase64', 'base64'); + hold_json := convert_from(evidence_hold_bytes, 'UTF8')::JSONB; + hold_request_json := convert_from(decode(hold_json ->> 'requestBytesBase64', 'base64'), 'UTF8')::JSONB; + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Terminal Account protection evidence bytes are not structurally readable' + USING ERRCODE = '23514'; + END; + + IF evidence_json ->> 'schema' IS DISTINCT FROM 'account-start-session-admission-protection-evidence/v1' + OR jsonb_typeof(evidence_json -> 'sourceEvidenceVector') IS DISTINCT FROM 'array' + OR jsonb_array_length(evidence_json -> 'sourceEvidenceVector') < 1 + OR evidence_request ->> 'schema' IS DISTINCT FROM 'account-start-session-admission-protection-request/v1' + OR evidence_json ->> 'accountProtectionId' IS DISTINCT FROM NEW.account_protection_id::TEXT + OR evidence_json ->> 'accountProtectionFence' IS DISTINCT FROM NEW.account_protection_fence::TEXT + OR evidence_request ->> 'gameSessionOwnerAttemptId' IS DISTINCT FROM NEW.original_owner_attempt_id::TEXT + OR evidence_request ->> 'gameSessionOwnerMutationId' IS DISTINCT FROM NEW.original_owner_mutation_id::TEXT + OR evidence_request ->> 'gameSessionOwnerFence' IS DISTINCT FROM NEW.original_owner_fence::TEXT + OR evidence_request ->> 'originalLeaseExpiresAt' IS DISTINCT FROM + to_char(selected_original.lease_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') + OR evidence_tuple_bytes IS DISTINCT FROM selected_original.post_authorization_execution_tuple + OR evidence_tuple_bytes IS DISTINCT FROM selected_launch.original_start_session_tuple + OR evidence_projection_bytes IS DISTINCT FROM selected_original.account_redemption_projection + OR selected_original.account_redemption_projection IS NULL + OR evidence_hold_bytes IS DISTINCT FROM selected_intent.hold_identity_bytes + OR hold_json ->> 'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' + OR hold_json ->> 'holdId' IS DISTINCT FROM NEW.hold_id::TEXT + OR hold_json ->> 'holdFence' IS DISTINCT FROM NEW.hold_fence::TEXT + OR hold_json ->> 'holdBindingDigest' IS DISTINCT FROM NEW.hold_binding_digest + OR hold_request_json ->> 'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-request/v1' + OR jsonb_typeof(hold_request_json -> 'request') IS DISTINCT FROM 'object' + OR hold_request_json -> 'request' ->> 'targetNamespace' IS DISTINCT FROM NEW.target_namespace + OR hold_request_json -> 'request' ->> 'canonicalTenantId' IS DISTINCT FROM NEW.canonical_tenant_id::TEXT + OR hold_request_json -> 'request' ->> 'worldSlug' IS DISTINCT FROM NEW.world_slug + OR hold_request_json -> 'request' ->> 'realmId' IS DISTINCT FROM NEW.realm_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateNamespaceId' IS DISTINCT FROM NEW.playable_state_namespace_id::TEXT + OR hold_request_json -> 'request' ->> 'playableStateScope' IS DISTINCT FROM NEW.playable_state_scope + OR hold_request_json -> 'request' ->> 'canonicalGameInstanceId' IS DISTINCT FROM NEW.canonical_game_instance_id::TEXT + OR hold_request_json -> 'request' ->> 'canonicalVersionId' IS DISTINCT FROM NEW.canonical_version_id::TEXT + OR hold_request_json -> 'request' ->> 'activeLifecycleEpoch' IS DISTINCT FROM NEW.active_lifecycle_epoch::TEXT + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestId' IS DISTINCT FROM NEW.initial_admission_request_id + OR hold_request_json -> 'request' ->> 'initialAdmissionRequestDigest' IS DISTINCT FROM NEW.request_digest + OR hold_request_json -> 'request' ->> 'initialAdmissionOrigin' IS DISTINCT FROM NEW.origin_kind + OR hold_request_json -> 'request' ->> 'expectedCatalogRevision' IS DISTINCT FROM NEW.expected_catalog_revision::TEXT + OR COALESCE(hold_request_json -> 'request' ->> 'expectedPriorPointerVersion', '') + IS DISTINCT FROM COALESCE(NEW.expected_prior_pointer_version::TEXT, '') + OR decode(hold_json ->> 'requestBytesBase64', 'base64') IS DISTINCT FROM selected_intent.canonical_hold_request_bytes + THEN + RAISE EXCEPTION 'Full Account protection evidence differs from its exact tuple, projection, lease, V35 owner, or World hold' + USING ERRCODE = '23514'; + END IF; + + -- Re-derive the established CanonicalInitialAdmissionRequest digest from the exact V28 fields + -- using the same int32 big-endian UTF-8 byte-length framing as ADR0047 and the Java owner. + digest_bytes := ''::BYTEA; + domain_bytes := convert_to('game-session-canonical-initial-admission/v1', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.target_namespace, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.canonical_tenant_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.world_slug, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.realm_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.playable_state_namespace_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.playable_state_scope, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.canonical_game_instance_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.canonical_version_id::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.active_lifecycle_epoch::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.expected_catalog_revision::TEXT, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.origin_kind, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.expected_prior_pointer_version::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.initial_admission_request_id, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + expected_request_digest := encode(sha256(digest_bytes), 'hex'); + IF NEW.request_digest <> expected_request_digest THEN + RAISE EXCEPTION 'Canonical initial-admission request digest does not bind the exact V28 fields' + USING ERRCODE = '23514'; + END IF; + + IF NEW.status = 'COMMITTED' THEN + IF NEW.pointer_id IS NULL OR NEW.pointer_version IS NULL OR NEW.audit_event_id IS NULL + OR NEW.abort_reason IS NOT NULL OR NEW.abort_proof_digest IS NOT NULL THEN + RAISE EXCEPTION 'COMMITTED initial-admission terminal fields are incomplete or mixed' + USING ERRCODE = '23514'; + END IF; + terminal_at_text := to_char(NEW.terminal_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'); + ELSE + IF NEW.pointer_id IS NOT NULL OR NEW.pointer_version IS NOT NULL OR NEW.audit_event_id IS NOT NULL + OR NEW.abort_reason IS NULL OR NEW.commit_proof_digest IS NOT NULL THEN + RAISE EXCEPTION 'ABORTED initial-admission terminal fields are incomplete or mixed' + USING ERRCODE = '23514'; + END IF; + terminal_at_text := to_char(NEW.terminal_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'); + END IF; + + digest_bytes := ''::BYTEA; + domain_bytes := convert_to('game-session-canonical-initial-admission-terminal/v1', 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + digest_bytes := digest_bytes || int4send(octet_length(NEW.account_protection_evidence_bytes)) + || NEW.account_protection_evidence_bytes; + domain_bytes := convert_to(NEW.request_digest, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(NEW.status, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.pointer_id::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.pointer_version::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.audit_event_id::TEXT, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(terminal_at_text, 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + domain_bytes := convert_to(COALESCE(NEW.abort_reason, ''), 'UTF8'); + digest_bytes := digest_bytes || int4send(octet_length(domain_bytes)) || domain_bytes; + IF NEW.status = 'COMMITTED' THEN + NEW.commit_proof_digest := 'sha256:' || encode(sha256(digest_bytes), 'hex'); + ELSE + NEW.abort_proof_digest := 'sha256:' || encode(sha256(digest_bytes), 'hex'); + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER game_session_canonical_initial_admission_v44_terminal_evidence +BEFORE INSERT OR UPDATE ON game_session_canonical_initial_admission_attempt +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_account_terminal_evidence(); + +CREATE TRIGGER game_session_canonical_initial_admission_intent_v44_immutable +BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_initial_admission_intent +FOR EACH ROW EXECUTE FUNCTION require_game_session_canonical_initial_admission_account_terminal_evidence(); + +CREATE FUNCTION reject_game_session_canonical_initial_admission_protection_truncate() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM game_session_canonical_initial_admission_attempt + WHERE account_protection_evidence_bytes IS NOT NULL) + OR EXISTS (SELECT 1 FROM game_session_canonical_initial_admission_intent + WHERE hold_identity_bytes IS NOT NULL) THEN + RAISE EXCEPTION 'Canonical initial-admission Account protection evidence cannot be truncated' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER game_session_canonical_initial_admission_protection_no_truncate +BEFORE TRUNCATE ON game_session_canonical_initial_admission_attempt +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_initial_admission_protection_truncate(); +CREATE TRIGGER game_session_canonical_initial_admission_intent_no_truncate +BEFORE TRUNCATE ON game_session_canonical_initial_admission_intent +FOR EACH STATEMENT EXECUTE FUNCTION reject_game_session_canonical_initial_admission_protection_truncate(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1010__canonical_run_owned_fixture_launch_provenance.sql b/services/game-session-service/src/main/resources/db/migration/V1010__canonical_run_owned_fixture_launch_provenance.sql new file mode 100644 index 0000000000..794d7980ee --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1010__canonical_run_owned_fixture_launch_provenance.sql @@ -0,0 +1,140 @@ +-- Two exact typed provenances in the existing owners. Never backfill retained rows. +ALTER TABLE game_session_canonical_realm_catalog + ADD COLUMN fixture_policy_request_bytes BYTEA, + ADD COLUMN fixture_policy_seal_operation_id UUID, + ADD COLUMN fixture_policy_seal_request_digest VARCHAR(71), + ADD COLUMN fixture_policy_seal_evidence_digest VARCHAR(71); + +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT chk_gs_catalog_fixture_provenance CHECK ( + (fixture_policy_request_bytes IS NULL AND fixture_policy_seal_operation_id IS NULL + AND fixture_policy_seal_request_digest IS NULL AND fixture_policy_seal_evidence_digest IS NULL) + OR (complete_policy_set_evidence IS NULL AND fixture_policy_request_bytes IS NOT NULL + AND octet_length(fixture_policy_request_bytes) > 0 + AND fixture_policy_seal_operation_id IS NOT NULL + AND fixture_policy_seal_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fixture_policy_seal_request_digest IS NOT NULL + AND fixture_policy_seal_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND fixture_policy_seal_evidence_digest IS NOT NULL + AND fixture_policy_seal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND visible AND public_production AND state_scope = 'SHARED' + AND character_creation_policy = 'ALLOW_NEW')); + +ALTER TABLE game_session_canonical_instance_launch + ADD COLUMN fixture_policy_request_bytes BYTEA, + ADD COLUMN fixture_policy_seal_operation_id UUID, + ADD COLUMN fixture_policy_seal_request_digest VARCHAR(71), + ADD COLUMN fixture_policy_seal_evidence_digest VARCHAR(71); + +ALTER TABLE game_session_canonical_instance_launch + DROP CONSTRAINT chk_gs_canonical_instance_launch_catalog_identity; + +ALTER TABLE game_session_canonical_instance_launch + DROP CONSTRAINT chk_gs_canonical_instance_launch_binding; + +-- PostgreSQL JSONB checks are proved natively; H2 cannot execute these operators. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_instance_launch + ADD CONSTRAINT chk_gs_launch_fixture_provenance CHECK ( + (fixture_policy_request_bytes IS NULL AND fixture_policy_seal_operation_id IS NULL + AND fixture_policy_seal_request_digest IS NULL AND fixture_policy_seal_evidence_digest IS NULL) + OR (original_start_session_tuple IS NULL AND fixture_policy_request_bytes IS NOT NULL + AND octet_length(fixture_policy_request_bytes) > 0 + AND fixture_policy_seal_operation_id IS NOT NULL + AND fixture_policy_seal_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fixture_policy_seal_request_digest IS NOT NULL + AND fixture_policy_seal_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND fixture_policy_seal_evidence_digest IS NOT NULL + AND fixture_policy_seal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND complete_launch_binding_evidence -> 'releaseAttestation' IS NULL)); +-- [jooq ignore stop] + +ALTER TABLE game_session_canonical_instance_launch + ADD CONSTRAINT chk_gs_canonical_instance_launch_catalog_identity CHECK ( + (original_start_session_tuple IS NULL AND fixture_policy_request_bytes IS NULL + AND catalog_creation_request_id IS NULL AND catalog_revision IS NULL + AND catalog_source_intake_operation_id IS NULL AND catalog_source_intake_request_id IS NULL) + OR ((original_start_session_tuple IS NOT NULL AND fixture_policy_request_bytes IS NULL + OR original_start_session_tuple IS NULL AND fixture_policy_request_bytes IS NOT NULL) + AND catalog_creation_request_id IS NOT NULL AND catalog_revision IS NOT NULL AND catalog_revision > 0 + AND catalog_source_intake_operation_id IS NOT NULL AND catalog_source_intake_request_id IS NOT NULL + AND catalog_source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID)); + +-- PostgreSQL JSONB checks are proved natively; H2 cannot execute these operators. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_instance_launch + ADD CONSTRAINT chk_gs_canonical_instance_launch_binding CHECK ( + char_length(launch_descriptor_id) BETWEEN 1 AND 128 + AND launch_descriptor_id !~ '^[[:space:]]*$' + AND char_length(generation_config_revision) BETWEEN 1 AND 128 + AND generation_config_revision !~ '^[[:space:]]*$' + AND jsonb_typeof(complete_launch_binding_evidence) = 'object' + AND jsonb_typeof(complete_launch_binding_evidence -> 'descriptor') = 'object' + AND ((fixture_policy_request_bytes IS NULL + AND jsonb_typeof(complete_launch_binding_evidence -> 'releaseAttestation') = 'object') + OR (fixture_policy_request_bytes IS NOT NULL + AND jsonb_typeof(complete_launch_binding_evidence -> 'fixturePolicySeal') = 'object'))); +-- [jooq ignore stop] + +-- The published V26 immutable-update/delete/truncate guards remain unchanged. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_game_session_canonical_realm_complete_policy_evidence() +RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF (NEW.complete_policy_set_evidence IS NOT NULL + AND octet_length(NEW.complete_policy_set_evidence) > 0 + AND NEW.fixture_policy_request_bytes IS NULL) + OR (NEW.complete_policy_set_evidence IS NULL AND NEW.fixture_policy_request_bytes IS NOT NULL + AND octet_length(NEW.fixture_policy_request_bytes) > 0 + AND NEW.fixture_policy_seal_operation_id IS NOT NULL + AND NEW.fixture_policy_seal_request_digest IS NOT NULL + AND NEW.fixture_policy_seal_evidence_digest IS NOT NULL) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'New canonical realm requires exactly one complete Human or verified fixture policy provenance' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_canonical_realm_catalog_complete_policy_evidence'; +END; +$$; + +CREATE OR REPLACE FUNCTION require_complete_canonical_launch_catalog_identity() +RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE catalog_row game_session_canonical_realm_catalog%ROWTYPE; +BEGIN + IF NEW.catalog_creation_request_id IS NULL OR NEW.catalog_revision IS NULL OR NEW.catalog_revision <= 0 + OR NEW.catalog_source_intake_operation_id IS NULL OR NEW.catalog_source_intake_request_id IS NULL + OR NEW.catalog_source_intake_operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_source_intake_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NOT ((NEW.original_start_session_tuple IS NOT NULL AND NEW.fixture_policy_request_bytes IS NULL + AND octet_length(NEW.original_start_session_tuple) BETWEEN 1 AND 262144) + OR (NEW.original_start_session_tuple IS NULL AND NEW.fixture_policy_request_bytes IS NOT NULL + AND octet_length(NEW.fixture_policy_request_bytes) > 0)) THEN + RAISE EXCEPTION 'New canonical launch requires exactly one complete Human or verified fixture provenance and exact catalog identity' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_canonical_instance_launch_catalog_identity'; + END IF; + SELECT * INTO catalog_row FROM game_session_canonical_realm_catalog + WHERE target_namespace = NEW.target_namespace AND realm_id = NEW.canonical_realm_id; + IF NOT FOUND OR (NEW.fixture_policy_request_bytes IS NULL AND catalog_row.fixture_policy_request_bytes IS NOT NULL) + OR (NEW.fixture_policy_request_bytes IS NOT NULL AND ( + catalog_row.complete_policy_set_evidence IS NOT NULL + OR catalog_row.fixture_policy_request_bytes IS DISTINCT FROM NEW.fixture_policy_request_bytes + OR catalog_row.fixture_policy_seal_operation_id IS DISTINCT FROM NEW.fixture_policy_seal_operation_id + OR catalog_row.fixture_policy_seal_request_digest IS DISTINCT FROM NEW.fixture_policy_seal_request_digest + OR catalog_row.fixture_policy_seal_evidence_digest IS DISTINCT FROM NEW.fixture_policy_seal_evidence_digest + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'schema' + IS DISTINCT FROM 'firemud.run-owned-fixture-policy-seal.v1' + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'ownerService' + IS DISTINCT FROM 'game-design-service' + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'operationId' + IS DISTINCT FROM NEW.fixture_policy_seal_operation_id::text + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'requestDigest' + IS DISTINCT FROM NEW.fixture_policy_seal_request_digest + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'evidenceDigest' + IS DISTINCT FROM NEW.fixture_policy_seal_evidence_digest)) THEN + RAISE EXCEPTION 'Launch provenance differs from the exact retained canonical catalog owner' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_launch_fixture_provenance'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1011.1__canonical_human_launch_policy_provenance.sql b/services/game-session-service/src/main/resources/db/migration/V1011.1__canonical_human_launch_policy_provenance.sql new file mode 100644 index 0000000000..571db484af --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1011.1__canonical_human_launch_policy_provenance.sql @@ -0,0 +1,98 @@ +-- Tighten new Human launch provenance after V1011 without changing retained owner rows. +-- V1010/V1011 remain immutable. Historical all-NULL catalogs are not adopted as Human +-- publication evidence; existing launch/catalog bytes and xmin are preserved unchanged. +-- PostgreSQL-only lock and trigger preflight are outside the jOOQ DDL simulator. +-- [jooq ignore start] +LOCK TABLE game_session_canonical_realm_catalog, + game_session_canonical_instance_launch IN ACCESS EXCLUSIVE MODE; + +DO $$ +DECLARE + launch_relation OID := 'game_session_canonical_instance_launch'::REGCLASS; + launch_function OID := 'require_complete_canonical_launch_catalog_identity()'::REGPROCEDURE; +BEGIN + -- Require V1011's renamed trigger and the unchanged V1010 function body. + IF NOT EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgrelid = launch_relation + AND tgname = 'gs_canonical_instance_launch_complete_catalog_identity' + AND tgfoid = launch_function + AND tgtype = 7 -- BEFORE INSERT, FOR EACH ROW + AND tgenabled = 'O' + AND NOT tgisinternal + AND tgnargs = 0 + AND tgattr = ''::INT2VECTOR + AND tgqual IS NULL + AND tgconstraint = 0 + AND NOT tgdeferrable + AND NOT tginitdeferred) + OR EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgrelid = launch_relation + AND tgname = 'game_session_canonical_instance_launch_complete_catalog_identit') + OR (SELECT count(*) FROM pg_trigger + WHERE tgrelid = launch_relation AND tgfoid = launch_function) <> 1 + OR NOT EXISTS ( + SELECT 1 FROM pg_proc function_row + JOIN pg_class relation_row ON relation_row.oid = launch_relation + JOIN pg_language language_row ON language_row.oid = function_row.prolang + WHERE function_row.oid = launch_function + AND function_row.pronamespace = relation_row.relnamespace + AND function_row.prorettype = 'trigger'::REGTYPE + AND function_row.prokind = 'f' + AND function_row.pronargs = 0 + AND NOT function_row.prosecdef + AND language_row.lanname = 'plpgsql' + -- Exact prosrc installed by V1010__canonical_run_owned_fixture_launch_provenance.sql. + AND md5(function_row.prosrc) = 'd6c8f6e518b45a073c00b5b045b02d5c') THEN + RAISE EXCEPTION 'Canonical launch guard differs from the exact V1011 trigger and V1010 function' + USING ERRCODE = '23514'; + END IF; + +END; +$$; + +CREATE OR REPLACE FUNCTION require_complete_canonical_launch_catalog_identity() +RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE catalog_row game_session_canonical_realm_catalog%ROWTYPE; +BEGIN + IF NEW.catalog_creation_request_id IS NULL OR NEW.catalog_revision IS NULL OR NEW.catalog_revision <= 0 + OR NEW.catalog_source_intake_operation_id IS NULL OR NEW.catalog_source_intake_request_id IS NULL + OR NEW.catalog_source_intake_operation_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NEW.catalog_source_intake_request_id = '00000000-0000-0000-0000-000000000000'::UUID + OR NOT ((NEW.original_start_session_tuple IS NOT NULL AND NEW.fixture_policy_request_bytes IS NULL + AND octet_length(NEW.original_start_session_tuple) BETWEEN 1 AND 262144) + OR (NEW.original_start_session_tuple IS NULL AND NEW.fixture_policy_request_bytes IS NOT NULL + AND octet_length(NEW.fixture_policy_request_bytes) > 0)) THEN + RAISE EXCEPTION 'New canonical launch requires exactly one complete Human or verified fixture provenance and exact catalog identity' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_canonical_instance_launch_catalog_identity'; + END IF; + SELECT * INTO catalog_row FROM game_session_canonical_realm_catalog + WHERE target_namespace = NEW.target_namespace AND realm_id = NEW.canonical_realm_id; + IF NOT FOUND OR (NEW.fixture_policy_request_bytes IS NULL AND ( + catalog_row.complete_policy_set_evidence IS NULL + OR octet_length(catalog_row.complete_policy_set_evidence) = 0 + OR catalog_row.fixture_policy_request_bytes IS NOT NULL)) + OR (NEW.fixture_policy_request_bytes IS NOT NULL AND ( + catalog_row.complete_policy_set_evidence IS NOT NULL + OR catalog_row.fixture_policy_request_bytes IS DISTINCT FROM NEW.fixture_policy_request_bytes + OR catalog_row.fixture_policy_seal_operation_id IS DISTINCT FROM NEW.fixture_policy_seal_operation_id + OR catalog_row.fixture_policy_seal_request_digest IS DISTINCT FROM NEW.fixture_policy_seal_request_digest + OR catalog_row.fixture_policy_seal_evidence_digest IS DISTINCT FROM NEW.fixture_policy_seal_evidence_digest + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'schema' + IS DISTINCT FROM 'firemud.run-owned-fixture-policy-seal.v1' + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'ownerService' + IS DISTINCT FROM 'game-design-service' + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'operationId' + IS DISTINCT FROM NEW.fixture_policy_seal_operation_id::text + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'requestDigest' + IS DISTINCT FROM NEW.fixture_policy_seal_request_digest + OR NEW.complete_launch_binding_evidence -> 'fixturePolicySeal' ->> 'evidenceDigest' + IS DISTINCT FROM NEW.fixture_policy_seal_evidence_digest)) THEN + RAISE EXCEPTION 'Launch provenance differs from the exact retained canonical catalog owner' + USING ERRCODE = '23514', CONSTRAINT = 'chk_gs_launch_fixture_provenance'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1011__canonical_launch_and_terminal_protection_history_safe_guards.sql b/services/game-session-service/src/main/resources/db/migration/V1011__canonical_launch_and_terminal_protection_history_safe_guards.sql new file mode 100644 index 0000000000..d5907a09ba --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1011__canonical_launch_and_terminal_protection_history_safe_guards.sql @@ -0,0 +1,140 @@ +-- Preserve the published V1005/V1006 bytes and tighten their guards in a forward migration. +-- Flyway executes this migration in one PostgreSQL transaction. No retained row is rewritten, +-- backfilled, or adopted; legitimate historical all-NULL terminal protection stays readable. +-- Locks and catalog/data preflight require PostgreSQL and are outside the jOOQ DDL simulator. +-- [jooq ignore start] +LOCK TABLE game_session_canonical_instance_launch, + game_session_canonical_initial_admission_attempt IN ACCESS EXCLUSIVE MODE; + +DO $$ +DECLARE + launch_relation OID := 'game_session_canonical_instance_launch'::REGCLASS; + attempt_relation OID := 'game_session_canonical_initial_admission_attempt'::REGCLASS; + launch_function OID := 'require_complete_canonical_launch_catalog_identity()'::REGPROCEDURE; +BEGIN + -- V1005's 64-byte identifier was truncated by PostgreSQL to this exact 63-byte name. + -- V1010 replaced the function in place. Require that exact current binding and body, + -- not the obsolete Human-only V1005 body, before changing any guard object. + IF NOT EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgrelid = launch_relation + AND tgname = 'game_session_canonical_instance_launch_complete_catalog_identit' + AND tgfoid = launch_function + AND tgtype = 7 -- BEFORE INSERT, FOR EACH ROW + AND tgenabled = 'O' + AND NOT tgisinternal + AND tgnargs = 0 + AND tgattr = ''::INT2VECTOR + AND tgqual IS NULL + AND tgconstraint = 0 + AND NOT tgdeferrable + AND NOT tginitdeferred) + OR EXISTS ( + SELECT 1 FROM pg_trigger + WHERE tgrelid = launch_relation + AND tgname = 'gs_canonical_instance_launch_complete_catalog_identity') + OR (SELECT count(*) FROM pg_trigger + WHERE tgrelid = launch_relation AND tgfoid = launch_function) <> 1 + OR NOT EXISTS ( + SELECT 1 FROM pg_proc function_row + JOIN pg_class relation_row ON relation_row.oid = launch_relation + JOIN pg_language language_row ON language_row.oid = function_row.prolang + WHERE function_row.oid = launch_function + AND function_row.pronamespace = relation_row.relnamespace + AND function_row.prorettype = 'trigger'::REGTYPE + AND function_row.prokind = 'f' + AND function_row.pronargs = 0 + AND NOT function_row.prosecdef + AND language_row.lanname = 'plpgsql' + -- Exact prosrc installed by V1010__canonical_run_owned_fixture_launch_provenance.sql. + AND md5(function_row.prosrc) = 'd6c8f6e518b45a073c00b5b045b02d5c') THEN + RAISE EXCEPTION 'Canonical launch guard differs from the original V1005 trigger and current V1010 function' + USING ERRCODE = '23514'; + END IF; + + IF (SELECT count(*) FROM pg_constraint + WHERE conrelid = attempt_relation + AND conname IN ('chk_gs_initial_admission_account_protection_evidence_complete', + 'chk_gs_initial_admission_terminal_requires_protection') + AND contype = 'c' AND convalidated) <> 2 THEN + RAISE EXCEPTION 'Canonical initial-admission original protection constraints are missing or unexpected' + USING ERRCODE = '23514'; + END IF; + + -- IS NOT TRUE rejects SQL UNKNOWN as well as FALSE: original V1006 could admit a + -- partial tuple with a NULL version or fence if its procedural guard was bypassed. + -- Such retained conflicts require owner adjudication, never implicit repair here. + IF EXISTS ( + SELECT 1 FROM game_session_canonical_initial_admission_attempt + WHERE ((account_protection_evidence_version IS NULL + AND account_protection_id IS NULL + AND account_protection_fence IS NULL + AND original_owner_attempt_id IS NULL + AND original_owner_mutation_id IS NULL + AND original_owner_fence IS NULL + AND account_protection_evidence_bytes IS NULL) + OR (account_protection_evidence_version IS NOT NULL + AND account_protection_evidence_version = 1 + AND account_protection_id IS NOT NULL + AND account_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_protection_fence IS NOT NULL + AND account_protection_fence > 0 + AND original_owner_attempt_id IS NOT NULL + AND original_owner_mutation_id IS NOT NULL + AND original_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_owner_fence IS NOT NULL + AND original_owner_fence > 0 + AND account_protection_evidence_bytes IS NOT NULL + AND octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 8388608)) + IS NOT TRUE + OR (status = 'PENDING' AND account_protection_evidence_version IS NOT NULL)) THEN + RAISE EXCEPTION 'Retained canonical initial-admission protection evidence is malformed or partial' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_initial_admission_account_protection_evidence_complete'; + END IF; +END; +$$; +-- [jooq ignore stop] + +-- V28's procedural attempt-table creation is absent from simulated metadata, as in V1006. +-- These declarative guards are executed and proved against PostgreSQL. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_initial_admission_attempt + DROP CONSTRAINT chk_gs_initial_admission_account_protection_evidence_complete, + DROP CONSTRAINT chk_gs_initial_admission_terminal_requires_protection, + ADD CONSTRAINT chk_gs_initial_admission_account_protection_evidence_complete + CHECK ( + (account_protection_evidence_version IS NULL + AND account_protection_id IS NULL + AND account_protection_fence IS NULL + AND original_owner_attempt_id IS NULL + AND original_owner_mutation_id IS NULL + AND original_owner_fence IS NULL + AND account_protection_evidence_bytes IS NULL) + OR (account_protection_evidence_version IS NOT NULL + AND account_protection_evidence_version = 1 + AND account_protection_id IS NOT NULL + AND account_protection_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_protection_fence IS NOT NULL + AND account_protection_fence > 0 + AND original_owner_attempt_id IS NOT NULL + AND original_owner_mutation_id IS NOT NULL + AND original_owner_mutation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND original_owner_fence IS NOT NULL + AND original_owner_fence > 0 + AND account_protection_evidence_bytes IS NOT NULL + AND octet_length(account_protection_evidence_bytes) BETWEEN 1 AND 8388608)), + -- Enforce fresh terminal writes without validating/reclassifying immutable history. + ADD CONSTRAINT chk_gs_initial_admission_terminal_requires_protection + CHECK (status = 'PENDING' + OR (account_protection_evidence_version IS NOT NULL + AND account_protection_evidence_version = 1)) NOT VALID; +-- [jooq ignore stop] + +-- The simulator omits trigger objects. Rename in place to preserve its OID, binding, +-- enabled/event identity and the Human-or-fixture-aware V1010 function unchanged. +-- [jooq ignore start] +ALTER TRIGGER game_session_canonical_instance_launch_complete_catalog_identit + ON game_session_canonical_instance_launch + RENAME TO gs_canonical_instance_launch_complete_catalog_identity; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java new file mode 100644 index 0000000000..8e1462fdfd --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java @@ -0,0 +1,462 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveFreshTenantCreationResponse; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +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; + +/** Physical mTLS proof for exact Game Design fresh-tenant evidence reads. */ +class GameDesignFreshTenantCreationClientMtlsIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WRONG_WORKLOAD_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String WRONG_NAMESPACE_URI = + "spiffe://firemud/ns/other/sa/game-design-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + private static final UUID CREATION_REQUEST_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID OPERATION_ID = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + + @TempDir static Path temporaryDirectory; + + private static TestPki pki; + private Server server; + private GameDesignFreshTenantCreationClient client; + private AtomicInteger rpcStarts; + private AtomicInteger applicationCalls; + private AtomicReference receivedPeer; + private AtomicReference receivedRequest; + + @BeforeAll + static void createLocalTestCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @AfterEach + void stopTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void readsClosedBoundEvidenceFromExactSameNamespaceGameDesignPeer() throws Exception { + FreshTenantCreationEvidence expected = evidence(); + startServer(pki.gameDesignServer(), expected); + client = newClient(server); + client.init(); + + FreshTenantCreationEvidence result = + client.resolveCreation(CREATION_REQUEST_ID, expected.requestDigest()); + + assertThat(result).isEqualTo(expected); + assertThat(rpcStarts).hasValue(1); + assertThat(applicationCalls).hasValue(1); + assertThat(receivedPeer.get()) + .isNotNull() + .extracting(GrpcPeerIdentity::uri) + .isEqualTo(GAME_SESSION_URI); + assertThat(receivedRequest.get()) + .isEqualTo( + ResolveFreshTenantCreationRequest.newBuilder() + .setCreationRequestId(CREATION_REQUEST_ID.toString()) + .setExpectedRequestDigest(expected.requestDigest()) + .build()); + } + + @Test + void wrongWorkloadAndNamespacePeersReceiveNoResolveRpc() throws Exception { + FreshTenantCreationEvidence expected = evidence(); + for (TestIdentity wrongServer : + List.of(pki.wrongWorkloadServer(), pki.wrongNamespaceServer())) { + startServer(wrongServer, expected); + client = newClient(server); + client.init(); + + assertThatThrownBy( + () -> client.resolveCreation(CREATION_REQUEST_ID, expected.requestDigest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(rpcStarts).hasValue(0); + assertThat(applicationCalls).hasValue(0); + assertThat(receivedRequest.get()).isNull(); + stopTransport(); + } + } + + private void startServer(TestIdentity identity, FreshTenantCreationEvidence expected) + throws Exception { + rpcStarts = new AtomicInteger(); + applicationCalls = new AtomicInteger(); + receivedPeer = new AtomicReference<>(); + receivedRequest = new AtomicReference<>(); + var service = + new TenantIdentityServiceGrpc.TenantIdentityServiceImplBase() { + @Override + public void resolveFreshTenantCreation( + ResolveFreshTenantCreationRequest request, + StreamObserver observer) { + applicationCalls.incrementAndGet(); + receivedPeer.set(GrpcPeerIdentity.current()); + receivedRequest.set(request); + observer.onNext(response(expected)); + observer.onCompleted(); + } + }; + ServerInterceptor countRpcStarts = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countRpcStarts, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GameDesignFreshTenantCreationClient newClient(Server target) throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + target.getPort()); + return new GameDesignFreshTenantCreationClient( + endpoints, pki.clientProperties(temporaryDirectory), new GrpcChannelFactory(), NAMESPACE); + } + + private static FreshTenantCreationEvidence evidence() { + String requestDigest = + GameTenantCreationDigest.requestDigest( + NAMESPACE, CREATION_REQUEST_ID, "42", "Test game", "mTLS fixture"); + return new FreshTenantCreationEvidence( + 1, + NAMESPACE, + CREATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + 42L, + "42", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, + CREATION_REQUEST_ID, + OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + 42L, + "42", + "NEW_GAME_ROW")); + } + + private static ResolveFreshTenantCreationResponse response(FreshTenantCreationEvidence evidence) { + return ResolveFreshTenantCreationResponse.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setCreationRequestId(evidence.creationRequestId().toString()) + .setOperationId(evidence.operationId().toString()) + .setRequestDigest(evidence.requestDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setSourceGameRowId(evidence.sourceGameRowId()) + .setSourceGameTenantKey(evidence.sourceGameTenantKey()) + .setProvenanceKind(evidence.provenanceKind()) + .setEvidenceDigest(evidence.evidenceDigest()) + .build(); + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + TestIdentity gameDesignServer, + TestIdentity wrongWorkloadServer, + TestIdentity wrongNamespaceServer, + TestIdentity gameSessionClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("fresh-tenant-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD fresh-tenant test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("fresh-tenant-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + return new TestPki( + caCertificate, + issueIdentity(directory, caStore, caFile, "design-server", DESIGN_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-workload-server", WRONG_WORKLOAD_URI, true), + issueIdentity( + directory, caStore, caFile, "wrong-namespace-server", WRONG_NAMESPACE_URI, true), + issueIdentity( + directory, caStore, caFile, "game-session-client", GAME_SESSION_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path clientCertificate = + writePem( + directory.resolve("game-session-client.crt"), + "CERTIFICATE", + gameSessionClient.certificate().getEncoded()); + Path clientPrivateKey = + writePem( + directory.resolve("game-session-client.key"), + "PRIVATE KEY", + gameSessionClient.privateKey().getEncoded()); + Path trustCa = + writePem( + directory.resolve("fresh-tenant-client-trust-ca.crt"), + "CERTIFICATE", + caCertificate.getEncoded()); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(clientCertificate.toString()); + properties.setPrivateKey(clientPrivateKey.toString()); + properties.setCaCert(trustCa.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (server ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + List command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + throw new IllegalStateException("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("keytool failed: " + output); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + 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 08f582ae5f..b3084a7252 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 @@ -181,7 +181,8 @@ void preparesFirstBindingOnlyBehindVerifiedDispositionAndRetainsNoPriorShape() { void persistsFirstBindingAccountIndexReadbackWithoutPriorObligation() { TestSchema testSchema = newTestSchema("gs_binding_first_projection_"); try { - LeaseBoundFirstBinding fixture = prepareLeaseBoundFirstBinding(testSchema.dsl()); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); assertThat(fixture.evidence().expectedPrior()).isNull(); String member = CanonicalGameplayAccountIndexMember.of(fixture.evidence().candidate()).value(); @@ -214,7 +215,8 @@ void persistsFirstBindingAccountIndexReadbackWithoutPriorObligation() { void readsLeaseBoundAdmissionDecisionInReadOnlyTransaction() { TestSchema testSchema = newTestSchema("gs_binding_readonly_decision_"); try { - LeaseBoundFirstBinding fixture = prepareLeaseBoundFirstBinding(testSchema.dsl()); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); var decision = fixture.repository().readAdmissionDecision(TRANSITION_ID, fixture.leaseEvidence()); @@ -232,7 +234,8 @@ void readsLeaseBoundAdmissionDecisionInReadOnlyTransaction() { void persistsLeaseBoundAdmissionTerminalTimestampAsPostgresTimestamptz() { TestSchema testSchema = newTestSchema("gs_binding_terminal_timestamp_"); try { - LeaseBoundFirstBinding fixture = prepareLeaseBoundFirstBinding(testSchema.dsl()); + LeaseBoundFirstBinding fixture = + prepareLeaseBoundFirstBinding(testSchema.dataSource(), testSchema.dsl()); var decision = fixture.repository().readAdmissionDecision(TRANSITION_ID, fixture.leaseEvidence()); @@ -264,7 +267,7 @@ void leaseBoundDecisionAndRuntimeMutationAcquireLocksInOneOrder() throws Excepti CountDownLatch allowRuntimeMutation = new CountDownLatch(1); try { PreparedLeaseBoundFirstBinding fixture = - prepareLeaseBoundFirstBindingDecision(testSchema.dsl()); + prepareLeaseBoundFirstBindingDecision(testSchema.dataSource(), testSchema.dsl()); CanonicalPlayableTarget target = fixture.runtimeTarget().playableTarget(); long initialRowVersion = Objects.requireNonNull( @@ -527,8 +530,21 @@ private static CanonicalGameplayBindingTransitionRequest request(String sessionI null); } - private static LeaseBoundFirstBinding prepareLeaseBoundFirstBinding(DSLContext dsl) { - PreparedLeaseBoundFirstBinding prepared = prepareLeaseBoundFirstBindingDecision(dsl); + private static CanonicalGameplayBindingTransitionRequest request( + String sessionId, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget) { + return new CanonicalGameplayBindingTransitionRequest( + TRANSITION_ID, + ACCOUNT_INDEX_FENCE, + identity(sessionId, runtimeTarget), + reservation(RESERVATION_FENCE), + null, + null); + } + + private static LeaseBoundFirstBinding prepareLeaseBoundFirstBinding( + DriverManagerDataSource dataSource, DSLContext dsl) { + PreparedLeaseBoundFirstBinding prepared = + prepareLeaseBoundFirstBindingDecision(dataSource, dsl); prepared.repository().markProvisional(prepared.evidence(), prepared.decision()); return new LeaseBoundFirstBinding( prepared.repository(), @@ -537,16 +553,15 @@ private static LeaseBoundFirstBinding prepareLeaseBoundFirstBinding(DSLContext d } private static PreparedLeaseBoundFirstBinding prepareLeaseBoundFirstBindingDecision( - DSLContext dsl) { + DriverManagerDataSource dataSource, DSLContext dsl) { var runtimeTarget = - CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( - dsl, TENANT_ID, 1L, RUNTIME_GAME_INSTANCE_ID, INSTANCE_ID, NAMESPACE_ID); + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, TENANT_ID); // This synthetic disposition opens the repository branch for proof; it is not real migration // or bootstrap authorization. seedSyntheticVerifiedLegacyDisposition(dsl); CanonicalGameplayBindingInventoryRepository repository = new CanonicalGameplayBindingInventoryRepository(dsl); - CanonicalGameplayBindingTransitionRequest request = request(candidateSession(1)); + CanonicalGameplayBindingTransitionRequest request = request(candidateSession(1), runtimeTarget); repository.prepare(request); CanonicalGameplayBindingProvisionalCasEvidence preparedEvidence = repository.readProvisionalCasEvidence(TRANSITION_ID); @@ -679,7 +694,7 @@ private static TestSchema newTestSchema(String prefix, String applicationName) { .locations(MIGRATION_LOCATION) .load() .migrate(); - return new TestSchema(schema, dslForSchema(dataSource, schema)); + return new TestSchema(schema, dataSource, dslForSchema(dataSource, schema)); } private static void awaitLatch(CountDownLatch latch) { @@ -729,7 +744,7 @@ private record PreparedLeaseBoundFirstBinding( CanonicalGameplayAdmissionDecision decision, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget) {} - private record TestSchema(String schema, DSLContext dsl) {} + private record TestSchema(String schema, DriverManagerDataSource dataSource, DSLContext dsl) {} private static CanonicalGameplayBindingTransitionRequest transferRequest( String candidateSessionId, CanonicalGameplayBindingIdentity prior) { @@ -743,14 +758,33 @@ private static CanonicalGameplayBindingTransitionRequest transferRequest( } static CanonicalGameplayBindingIdentity identity(String sessionId) { + return identity(sessionId, TENANT_ID, NAMESPACE_ID, INSTANCE_ID, RUNTIME_GAME_INSTANCE_ID); + } + + private static CanonicalGameplayBindingIdentity identity( + String sessionId, CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget runtimeTarget) { + return identity( + sessionId, + runtimeTarget.canonicalTenantId(), + runtimeTarget.playableStateNamespaceId(), + runtimeTarget.gameInstanceUuid(), + runtimeTarget.gameInstanceId()); + } + + private static CanonicalGameplayBindingIdentity identity( + String sessionId, + UUID canonicalTenantId, + UUID playableStateNamespaceId, + UUID gameInstanceUuid, + long runtimeGameInstanceId) { return new CanonicalGameplayBindingIdentity( ACCOUNT_ID, - TENANT_ID, - NAMESPACE_ID, + canonicalTenantId, + playableStateNamespaceId, CHARACTER_ID, "SHARED", - INSTANCE_ID, - RUNTIME_GAME_INSTANCE_ID, + gameInstanceUuid, + runtimeGameInstanceId, sessionId, REGION_ID, BigInteger.valueOf(12), diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index a071511286..3b764958f8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -1,275 +1,289 @@ package net.firedevops.firemud.gamesession.repository; +import integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanPublicationOwnerTestFixtures; import java.time.Instant; import java.util.UUID; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import javax.sql.DataSource; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.StartingInstance; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import org.jooq.DSLContext; +import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; -/** Shared PostgreSQL fixtures for lease-bound binding tests that require a real launch target. */ +/** + * Shared PostgreSQL fixtures for lease-bound binding tests that require a current launch target. + * The source, policy, catalog, pin, and Starting records are written by their actual GS owners; + * upstream producer inputs remain controlled test evidence and do not establish Account admission. + */ public final class CanonicalGameplayBindingRuntimeTestFixtures { private static final String SHA256 = "sha256:" + "a".repeat(64); private static final String RAW_SHA256 = "a".repeat(64); + private static final long GAME_TEMPLATE_ID = 1L; + private static final long VERSION_ID = 1L; + private static final long RELEASE_BUNDLE_ID = 1L; + private static final long VERSION_STATE_EPOCH = 2L; + private static final String RUNTIME_FLAGS_JSON = "{}"; private CanonicalGameplayBindingRuntimeTestFixtures() {} - public static RuntimeTarget seedRunningLaunch(DSLContext dsl) { - return seedRunningLaunch(dsl, UUID.randomUUID(), 1L, 23L, UUID.randomUUID()); + public static RuntimeTarget seedRunningLaunch(DataSource dataSource) { + return seedRunningLaunch(dataSource, UUID.randomUUID()); } /** - * Seeds a fully linked fresh tenant, catalog, launch, and RUNNING runtime for the supplied - * candidate identity. All deferred constraints and normal owner triggers remain enabled. + * Creates the source-bound catalog and runtime using current Game Session owners. The source, + * publication, original tuple, and Account projection are explicitly controlled upstream test + * inputs; this path proves neither a live producer nor initial-admission terminal authority. */ - public static RuntimeTarget seedRunningLaunch( - DSLContext dsl, - UUID canonicalTenantId, - long gameSessionTenantId, - long gameInstanceId, - UUID gameInstanceUuid) { - return seedRunningLaunch( - dsl, - canonicalTenantId, - gameSessionTenantId, - gameInstanceId, - gameInstanceUuid, - UUID.randomUUID()); - } - - public static RuntimeTarget seedRunningLaunch( - DSLContext dsl, - UUID canonicalTenantId, - long gameSessionTenantId, - long gameInstanceId, - UUID gameInstanceUuid, - UUID playableStateNamespaceId) { - if (gameSessionTenantId <= 0 || gameInstanceId <= 0) { - throw new IllegalArgumentException("Runtime identifiers must be positive"); - } - if (canonicalTenantId == null - || gameInstanceUuid == null - || playableStateNamespaceId == null - || new UUID(0L, 0L).equals(canonicalTenantId) - || new UUID(0L, 0L).equals(gameInstanceUuid) - || new UUID(0L, 0L).equals(playableStateNamespaceId)) { - throw new IllegalArgumentException("Canonical runtime identities must be non-nil"); + public static RuntimeTarget seedRunningLaunch(DataSource dataSource, UUID canonicalTenantId) { + if (canonicalTenantId == null || new UUID(0L, 0L).equals(canonicalTenantId)) { + throw new IllegalArgumentException("Canonical tenant UUID must be non-nil"); } - RuntimeTarget target = - RuntimeTarget.create( + String token = UUID.randomUUID().toString().replace("-", ""); + String shortToken = token.substring(0, 10); + String targetNamespace = "fixture-" + shortToken; + String tenantSlug = "tenant-" + shortToken; + String worldSlug = "world-" + shortToken; + String worldDisplayName = "Fixture World " + shortToken; + String sourceGameTenantKey = "gds-source-" + shortToken; + long sourceGameRowId = + Math.floorMod(UUID.randomUUID().getLeastSignificantBits(), Long.MAX_VALUE - 1L) + 1L; + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, canonicalTenantId, - gameSessionTenantId, - gameInstanceId, - gameInstanceUuid, - playableStateNamespaceId); - dsl.transaction( - configuration -> { - DSLContext tx = DSL.using(configuration); - seedSourceAndCatalog(tx, target); - seedFreshTenantAssociation(tx, target); - seedStartingRuntimeAndLaunch(tx, target); - tx.execute( - "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - }); - return target; - } + tenantSlug, + worldSlug, + worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); - private static void seedSourceAndCatalog(DSLContext tx, RuntimeTarget target) { - tx.execute( - "INSERT INTO game_session_authored_world_tenant_source_binding" - + " (target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id," - + " source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW')", - target.targetNamespace(), - target.canonicalTenantId(), - target.tenantSlug(), - target.sourceGameRowId(), - target.sourceGameTenantKey()); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + String controlPlaneRequestId = "launch-" + token; + UUID ownerAccountUuid = UUID.randomUUID(); - tx.execute( - "INSERT INTO game_session_authored_world_source_intake" - + " (operation_id, schema_version, target_namespace, intake_request_id, request_digest," - + " source_schema_version, source_registration_request_id, source_operation_id," - + " source_request_digest, canonical_tenant_id, tenant_slug, world_slug," - + " world_display_name, source_game_row_id, source_game_tenant_key," - + " source_provenance_kind, source_evidence_digest, receipt_digest)" - + " VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?, ?)", - target.sourceIntakeOperationId(), - target.targetNamespace(), - target.sourceIntakeRequestId(), - SHA256, - target.sourceRegistrationRequestId(), - target.sourceOperationId(), - SHA256, - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.worldDisplayName(), - target.sourceGameRowId(), - target.sourceGameTenantKey(), - SHA256, - SHA256); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + IntakeReceipt sourceReceipt = + java.util.Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(UUID.randomUUID(), sourceEvidence)), + "registered authored-world source receipt"); - tx.execute( - "INSERT INTO gameplay_tenant_shared_playable_state_namespace" - + " (tenant_id, playable_state_namespace_id, canonical_tenant_id, target_namespace," - + " source_intake_operation_id, source_intake_schema_version, source_intake_request_id," - + " source_intake_request_digest, source_intake_receipt_digest, source_schema_version," - + " source_registration_request_id, source_operation_id, source_request_digest," - + " source_game_row_id, source_game_tenant_key, source_provenance_kind," - + " source_evidence_digest)" - + " VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)", - target.playableStateNamespaceId(), - target.canonicalTenantId(), - target.targetNamespace(), - target.sourceIntakeOperationId(), - target.sourceIntakeRequestId(), - SHA256, - SHA256, - target.sourceRegistrationRequestId(), - target.sourceOperationId(), - SHA256, - target.sourceGameRowId(), - target.sourceGameTenantKey(), - SHA256); + FreshTenantCreationEvidence creationEvidence = + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(sourceEvidence); + FreshGameSessionTenantAssociation tenantAssociation = + java.util.Objects.requireNonNull( + transactions.execute( + status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), targetNamespace, sourceReceipt, creationEvidence)), + "fresh source-bound Game Session tenant association"); - tx.execute( - "INSERT INTO game_session_canonical_realm_catalog" - + " (target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id," - + " realm_slug, realm_display_name, visible, public_production, state_scope," - + " playable_state_namespace_id, character_creation_policy, catalog_revision," - + " creation_request_id, request_digest, receipt_digest, source_intake_operation_id," - + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," - + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," - + " source_operation_id, source_request_digest, source_world_display_name," - + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, 'PLAYER_CHOICE', 1, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)", - target.targetNamespace(), - target.canonicalTenantId(), - target.tenantSlug(), - target.worldSlug(), - target.realmId(), - target.realmSlug(), - target.realmDisplayName(), - target.playableStateNamespaceId(), - target.catalogCreationRequestId(), - SHA256, - SHA256, - target.sourceIntakeOperationId(), - target.sourceIntakeRequestId(), - SHA256, - SHA256, - target.sourceRegistrationRequestId(), - target.sourceOperationId(), - SHA256, - target.worldDisplayName(), - target.sourceGameRowId(), - target.sourceGameTenantKey(), - SHA256); - } + UUID catalogRequestId = UUID.randomUUID(); + UUID canonicalVersionId = UUID.randomUUID(); + String publishRequestId = "publication-" + token; + String bundleRef = "published-release-" + shortToken; + String generationConfigRevision = "generation-" + shortToken; + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + catalogRequestId, + targetNamespace, + canonicalTenantId, + sourceReceipt.operationId(), + "main-realm", + "Main Realm", + true, + true, + "SHARED", + "PRESEEDED_ONLY", + null, + null); + var publishedSet = + CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + catalogRequest, + sourceEvidence, + canonicalVersionId, + VERSION_ID, + publishRequestId, + bundleRef, + generationConfigRevision, + VERSION_STATE_EPOCH); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + var preparedCatalog = + catalogRepository.prepareInitialPublicProduction(catalogRequest, publishedSet); + CanonicalRealmCatalogSnapshot catalog = + java.util.Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog)), + "created public-production canonical catalog"); - private static void seedFreshTenantAssociation(DSLContext tx, RuntimeTarget target) { - tx.execute( - "INSERT INTO game_session_tenant_scope_reservation" - + " (game_session_tenant_id, reservation_kind) VALUES (?, 'FRESH_SOURCE_BOUND')", - target.gameSessionTenantId()); - tx.execute( - "INSERT INTO game_session_tenant_canonical_claim" - + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," - + " association_kind, reservation_kind, association_operation_id, association_request_id)" - + " VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", - target.targetNamespace(), - target.canonicalTenantId(), - target.gameSessionTenantId(), - target.tenantAssociationOperationId(), - target.tenantAssociationRequestId()); - tx.execute( - "INSERT INTO game_session_fresh_tenant_association" - + " (association_operation_id, target_namespace, association_request_id," - + " source_schema_version, source_target_namespace, source_request_id," - + " source_canonical_tenant_id, canonical_tenant_id, legacy_game_session_tenant_id," - + " source_game_row_id, source_game_tenant_key, provenance_kind, association_kind)" - + " VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND')", - target.tenantAssociationOperationId(), - target.targetNamespace(), - target.tenantAssociationRequestId(), - target.targetNamespace(), - target.tenantAssociationRequestId(), - target.canonicalTenantId(), - target.canonicalTenantId(), - target.gameSessionTenantId(), - target.sourceGameRowId(), - target.sourceGameTenantKey()); - } + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + GAME_TEMPLATE_ID, + false, + null, + false, + null, + false, + null, + true, + RUNTIME_FLAGS_JSON); + String launchDescriptorId = "descriptor-" + shortToken; + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + launchDescriptorId, + VERSION_ID, + false, + null, + RUNTIME_FLAGS_JSON, + generationConfigRevision, + VERSION_STATE_EPOCH, + RELEASE_BUNDLE_ID, + bundleRef, + false, + null); + CompleteLaunchBindingEvidence binding = + CanonicalHumanPublicationOwnerTestFixtures.completeBinding(descriptor, publishedSet); + var originalTuple = + CanonicalHumanPublicationOwnerTestFixtures.tuple( + targetNamespace, + canonicalTenantId, + ownerAccountUuid, + GAME_TEMPLATE_ID, + controlPlaneRequestId); + CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( + dsl, transactions, originalTuple, sourceEvidence, publishedSet, binding); - private static void seedStartingRuntimeAndLaunch(DSLContext tx, RuntimeTarget target) { - tx.execute( - "INSERT INTO game_instances" - + " (id, tenant_id, runtime_version, owner_account_id, status, row_version," - + " game_instance_uuid, game_template_id, launch_descriptor_id, version_id," - + " release_bundle_id, generation_config_revision, version_state_epoch," - + " run_owned_start_request_id, run_owned_start_request_digest," - + " run_owned_start_published_release_bundle_ref, run_owned_start_preparing_epoch," - + " run_owned_start_active_epoch)" - + " VALUES (?, ?, 'fixture-runtime', 99, 'STARTING', 1, ?, 1, ?, 1, 1, ?, 1, ?, ?, ?, 1, 2)", - target.gameInstanceId(), - target.gameSessionTenantId(), - target.gameInstanceUuid(), - target.launchDescriptorId(), - target.generationConfigRevision(), - target.controlPlaneRequestId(), - RAW_SHA256, - target.publishedReleaseBundleRef()); + GameSessionCanonicalStartingInstanceRepository startingRepository = + new GameSessionCanonicalStartingInstanceRepository(dsl, targetNamespace); + StartingInstance startingInstance = + java.util.Objects.requireNonNull( + transactions.execute( + status -> + startingRepository.createStarting( + tenantAssociation, + binding, + ownerAccountUuid, + controlPlaneRequestId, + originalTuple.mutationDigest(), + originalTuple)), + "created canonical STARTING instance"); + int consumerInputRows = + java.util.Objects.requireNonNull( + transactions.execute( + status -> + dsl.execute( + // Controlled upstream World epoch inputs support only this downstream + // guard-consumer proof; they are not World ACTIVE, Human terminal, Account + // protection, or admission evidence. + "UPDATE game_instances SET status = 'RUNNING'," + + " row_version = row_version + 1, run_owned_start_preparing_epoch = 1," + + " run_owned_start_active_epoch = 2 WHERE tenant_id = ? AND id = ?", + tenantAssociation.legacyGameSessionTenantId(), + startingInstance.gameInstanceId())), + "controlled runtime consumer input row count"); + if (consumerInputRows != 1) { + throw new IllegalStateException( + "Created canonical STARTING test row did not receive controlled consumer inputs"); + } - tx.execute( - "INSERT INTO game_session_canonical_instance_launch" - + " (target_namespace, control_plane_request_id, game_session_tenant_id," - + " canonical_tenant_id, tenant_association_operation_id, tenant_association_request_id," - + " tenant_source_schema_version, tenant_source_target_namespace, tenant_source_request_id," - + " tenant_source_canonical_tenant_id, tenant_source_game_row_id," - + " tenant_source_game_tenant_key, tenant_source_provenance_kind, tenant_association_kind," - + " game_instance_id, game_instance_uuid, canonical_realm_id, world_slug," - + " playable_state_namespace_id, playable_state_scope, public_production," - + " captured_starting_row_version, game_template_id, launch_descriptor_id, version_id," - + " release_bundle_id, generation_config_revision, version_state_epoch," - + " complete_launch_binding_evidence)" - + " VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND'," - + " ?, ?, ?, ?, ?, 'SHARED', TRUE, 1, 1, ?, 1, 1, ?, 1," - + " jsonb_build_object('descriptor', jsonb_build_object('targetNamespace', ?," - + " 'controlPlaneRequestId', ?, 'canonicalTenantId', ?, 'worldSlug', ?," - + " 'gameTemplateId', '1', 'launchDescriptorId', ?, 'versionId', '1'," - + " 'releaseBundleId', '1', 'generationConfigRevision', ?, 'versionStateEpoch', '1'," - + " 'publishedReleaseBundleRef', ?), 'releaseAttestation'," - + " jsonb_build_object('canonicalVersionId', ?)))", - target.targetNamespace(), - target.controlPlaneRequestId(), - target.gameSessionTenantId(), - target.canonicalTenantId(), - target.tenantAssociationOperationId(), - target.tenantAssociationRequestId(), - target.targetNamespace(), - target.tenantAssociationRequestId(), - target.canonicalTenantId(), - target.sourceGameRowId(), - target.sourceGameTenantKey(), - target.gameInstanceId(), - target.gameInstanceUuid(), - target.realmId(), - target.worldSlug(), - target.playableStateNamespaceId(), - target.launchDescriptorId(), - target.generationConfigRevision(), - target.targetNamespace(), - target.controlPlaneRequestId(), - target.canonicalTenantId().toString(), - target.worldSlug(), - target.launchDescriptorId(), - target.generationConfigRevision(), - target.publishedReleaseBundleRef(), - target.canonicalVersionId().toString()); + return new RuntimeTarget( + targetNamespace, + tenantSlug, + canonicalTenantId, + worldSlug, + worldDisplayName, + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + tenantAssociation.legacyGameSessionTenantId(), + startingInstance.gameInstanceId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + startingInstance.gameInstanceUuid(), + canonicalVersionId, + VERSION_ID, + catalog.catalogRevision(), + 1L, + RAW_SHA256, + 2L, + "initial-" + shortToken, + RAW_SHA256, + UUID.randomUUID(), + UUID.randomUUID(), + SHA256, + 1L, + SHA256, + Instant.now(), + catalog.characterCreationPolicy(), + sourceEvidence.sourceGameRowId(), + sourceEvidence.sourceGameTenantKey(), + sourceReceipt.operationId(), + sourceReceipt.intakeRequestId(), + sourceEvidence.registrationRequestId(), + sourceEvidence.operationId(), + tenantAssociation.associationOperationId(), + creationEvidence.creationRequestId(), + catalog.creationRequestId(), + launchDescriptorId, + generationConfigRevision, + controlPlaneRequestId, + bundleRef); } public record RuntimeTarget( @@ -314,6 +328,11 @@ public record RuntimeTarget( String generationConfigRevision, String controlPlaneRequestId, String publishedReleaseBundleRef) { + /** + * The downstream binding tests use this carrier for selector equality only. Its admission + * fields are placeholders required by the current value type and do not come from an admission + * owner or establish a terminal Human proof. + */ public CanonicalPlayableTarget playableTarget() { return new CanonicalPlayableTarget( targetNamespace, @@ -337,14 +356,16 @@ public CanonicalPlayableTarget playableTarget() { activeWorldEpoch, initialAdmissionRequestId, initialAdmissionRequestDigest, - OriginKind.NO_PRIOR_POINTER, + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind + .NO_PRIOR_POINTER, null, holdId, holdFence, holdBindingDigest, auditEventId, ownerProofDigest, - Outcome.COMMITTED, + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome + .COMMITTED, false, ownerProofTerminalAt, characterCreationPolicy); @@ -353,58 +374,5 @@ public CanonicalPlayableTarget playableTarget() { public CanonicalPlayableTarget admissionTarget() { return playableTarget(); } - - private static RuntimeTarget create( - UUID canonicalTenantId, - long gameSessionTenantId, - long gameInstanceId, - UUID gameInstanceUuid, - UUID playableStateNamespaceId) { - String token = UUID.randomUUID().toString().replace("-", ""); - String shortToken = token.substring(0, 10); - Instant terminalAt = Instant.now(); - return new RuntimeTarget( - "fixture-" + shortToken, - "tenant-" + shortToken, - canonicalTenantId, - "world-" + shortToken, - "Fixture World " + shortToken, - UUID.randomUUID(), - "main", - "Main Realm", - gameSessionTenantId, - gameInstanceId, - playableStateNamespaceId, - "SHARED", - gameInstanceUuid, - UUID.randomUUID(), - 1L, - 1L, - 1L, - RAW_SHA256, - 2L, - "initial-" + shortToken, - RAW_SHA256, - UUID.randomUUID(), - UUID.randomUUID(), - SHA256, - 1L, - SHA256, - terminalAt, - "PLAYER_CHOICE", - gameInstanceId + 50_000L, - "source-" + shortToken, - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - "descriptor-" + shortToken, - "generation-" + shortToken, - "launch-" + token, - "published-release-" + shortToken); - } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java index 0491d686bf..9e029c8d3a 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 @@ -107,7 +107,7 @@ void exactLeaseBoundCandidatePinsRuntimeAndRejectsTerminalTransition() { migrate(schema, dataSource); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = - CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); markProvisional(dsl, target, candidateRef); @@ -226,7 +226,7 @@ void stoppedRuntimeCannotAcquireLeaseBoundBindingFence() { migrate(schema, dataSource); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = - CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); byte[] candidateRef = seedCandidateAndPreparedTransition(dsl, target, CandidateMismatch.NONE); assertThat( dsl.execute( @@ -260,7 +260,7 @@ void mismatchedCandidateTenantRuntimeOrCanonicalInstanceCannotAcquireFence() { migrate(schema, dataSource); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = - CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); for (CandidateMismatch mismatch : CandidateMismatch.values()) { if (mismatch == CandidateMismatch.NONE) { @@ -303,10 +303,10 @@ void launchPreparationMustReferenceTheFullImmutableCatalogIdentity() { migrate(schema, dataSource); DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target = - CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource); CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget otherSourceIntakeOwner = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( - dsl, UUID.randomUUID(), 2L, 24L, UUID.randomUUID()); + dataSource, UUID.randomUUID()); assertThat( insertLaunchPreparation( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java index efc760bdd8..8d5d608469 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java @@ -4,16 +4,31 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; +import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.IntentState; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; 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.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -24,8 +39,6 @@ class CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest { private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); - private static final String RAW_SHA256 = "a".repeat(64); - private static final String SHA256 = "sha256:" + RAW_SHA256; @Container static PostgreSQLContainer postgres = @@ -37,76 +50,176 @@ void intentLedgerAcceptsAttemptWidthAndRejectsAnIdentityBeyond128Characters() { DriverManagerDataSource dataSource = dataSource(schema); try { migrate(schema, dataSource); - DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = + new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var schemaReadback = dsl.fetchOne("SELECT current_schema() AS actual_schema"); assertThat(schemaReadback.get("actual_schema", String.class)).isEqualTo(schema); - CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget length121 = + RuntimeTarget length121 = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( - dsl, UUID.randomUUID(), 2L, 24L, UUID.randomUUID()); - CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget length128 = + dataSource, UUID.randomUUID()); + RuntimeTarget length128 = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( - dsl, UUID.randomUUID(), 3L, 25L, UUID.randomUUID()); - CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget length129 = - CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( - dsl, UUID.randomUUID(), 4L, 26L, UUID.randomUUID()); + dataSource, UUID.randomUUID()); + + // Controlled upstream owner inputs support only this pre-hold consumer proof. + ReservedIntent intent121 = reserveIntent(dsl, transactions, length121, "r".repeat(121)); + ReservedIntent intent128 = reserveIntent(dsl, transactions, length128, "r".repeat(128)); + assertPendingIntent(dsl, intent121); + assertPendingIntent(dsl, intent128); - assertThat(insertIntent(dsl, length121, "r".repeat(121))).isEqualTo(1); - assertThat(insertIntent(dsl, length128, "r".repeat(128))).isEqualTo(1); - assertThatThrownBy(() -> insertIntent(dsl, length129, "r".repeat(129))) + Record originalIntent = readIntent(dsl, intent128); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_initial_admission_intent " + + "SET initial_admission_request_id = ? " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + "r".repeat(129), + length128.targetNamespace(), + intent128.request().initialAdmissionRequestId())) .isInstanceOfSatisfying( DataAccessException.class, exception -> assertThat(exception.sqlState()).isEqualTo("22001")); + + Record intentAfterRejectedUpdate = readIntent(dsl, intent128); + assertThat(intentAfterRejectedUpdate.get("canonical_hold_request_bytes", byte[].class)) + .containsExactly(originalIntent.get("canonical_hold_request_bytes", byte[].class)); + assertThat(intentAfterRejectedUpdate.get("canonical_lifecycle_request_bytes", byte[].class)) + .containsExactly(originalIntent.get("canonical_lifecycle_request_bytes", byte[].class)); + assertThat(intentAfterRejectedUpdate.get("original_start_session_tuple", byte[].class)) + .containsExactly(originalIntent.get("original_start_session_tuple", byte[].class)); + assertThat(intentAfterRejectedUpdate.get("state", String.class)).isEqualTo("PENDING_HOLD"); + assertThat(intentAfterRejectedUpdate.get("xmin", String.class)) + .isEqualTo(originalIntent.get("xmin", String.class)); } finally { dropSchema(schema); } } - private static int insertIntent( - DSLContext dsl, - CanonicalGameplayBindingRuntimeTestFixtures.RuntimeTarget target, - String requestId) { - return dsl.execute( - "INSERT INTO game_session_canonical_initial_admission_intent" - + " (target_namespace, initial_admission_request_id, request_digest," - + " canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id," - + " playable_state_scope, catalog_visible, catalog_public_production," - + " catalog_revision, catalog_creation_request_id, catalog_request_digest," - + " catalog_receipt_digest, tenant_association_operation_id, game_session_tenant_id," - + " canonical_game_instance_id, game_instance_id, canonical_version_id," - + " runtime_version_id, control_plane_request_id, launch_descriptor_id," - + " captured_starting_row_version, current_row_version, descriptor_request_digest," - + " descriptor_result_digest, release_attestation_digest, canonical_hold_request_bytes," - + " canonical_lifecycle_request_bytes, hold_identity_bytes, state, created_at," - + " updated_at, terminal_at)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," - + " 0, 1, ?, ?, ?, decode('01', 'hex'), decode('02', 'hex'), NULL, 'PENDING_HOLD'," - + " now(), now(), NULL)", + private static ReservedIntent reserveIntent( + DSLContext dsl, TransactionTemplate transactions, RuntimeTarget target, String requestId) { + var catalogRepository = new GameSessionCanonicalRealmCatalogRepository(dsl); + var launchRepository = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, target.targetNamespace()); + CanonicalInitialAdmissionLaunchTarget launchTarget = + launchRepository + .readForInitialAdmission( + target.targetNamespace(), + target.canonicalTenantId(), + target.realmId(), + target.gameInstanceUuid()) + .orElseThrow(); + var intentRepository = + new CanonicalInitialAdmissionIntentRepository(dsl, catalogRepository, launchRepository); + WorldCanonicalInitialAdmissionHold.Request request = holdRequest(target, requestId); + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest = + lifecycleRequest(target, launchTarget, UUID.randomUUID()); + CanonicalInitialAdmissionIntentSnapshot snapshot = + Objects.requireNonNull( + transactions.execute(status -> intentRepository.reserve(request, lifecycleRequest)), + "reserved canonical initial-admission intent"); + return new ReservedIntent(target, request, lifecycleRequest, snapshot); + } + + private static WorldCanonicalInitialAdmissionHold.Request holdRequest( + RuntimeTarget target, String requestId) { + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + target.realmId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.gameInstanceUuid(), + target.canonicalVersionId(), + target.activeWorldEpoch(), + target.catalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId); + return new WorldCanonicalInitialAdmissionHold.Request( target.targetNamespace(), - requestId, - RAW_SHA256, target.canonicalTenantId(), target.worldSlug(), target.realmId(), target.playableStateNamespaceId(), target.playableStateScope(), - target.catalogRevision(), - target.catalogCreationRequestId(), - SHA256, - SHA256, - target.tenantAssociationOperationId(), - target.gameSessionTenantId(), target.gameInstanceUuid(), - target.gameInstanceId(), target.canonicalVersionId(), - target.runtimeVersionId(), - target.controlPlaneRequestId(), - target.launchDescriptorId(), - SHA256, - SHA256, - SHA256); + target.activeWorldEpoch(), + requestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + target.catalogRevision(), + null); } + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( + RuntimeTarget target, + CanonicalInitialAdmissionLaunchTarget launchTarget, + UUID readRequestId) { + var association = launchTarget.association(); + var binding = association.launchBindingEvidence(); + return new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + readRequestId, + target.targetNamespace(), + target.canonicalTenantId(), + target.worldSlug(), + association.gameInstanceUuid(), + target.playableStateNamespaceId(), + target.playableStateScope(), + true, + association.controlPlaneRequestId(), + launchTarget.canonicalVersionId(), + binding.descriptor().requestDigest(), + binding.descriptor().resultDigest(), + binding.releaseAttestation().evidenceDigest()); + } + + private static void assertPendingIntent(DSLContext dsl, ReservedIntent reserved) { + assertThat(reserved.snapshot().state()).isEqualTo(IntentState.PENDING_HOLD); + assertThat(reserved.snapshot().holdIdentity()).isNull(); + assertThat(reserved.snapshot().holdRequest().canonicalRequestBytes()) + .containsExactly(reserved.request().canonicalRequestBytes()); + assertThat(reserved.snapshot().lifecycleRequest().canonicalBytes()) + .containsExactly(reserved.lifecycleRequest().canonicalBytes()); + Record intent = readIntent(dsl, reserved); + Record launch = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT original_start_session_tuple FROM game_session_canonical_instance_launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + reserved.target().targetNamespace(), + reserved.snapshot().sourceBinding().controlPlaneRequestId()), + "actual canonical launch owner row"); + assertThat(intent.get("original_start_session_tuple", byte[].class)) + .containsExactly(launch.get("original_start_session_tuple", byte[].class)); + } + + private static Record readIntent(DSLContext dsl, ReservedIntent reserved) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT canonical_hold_request_bytes, canonical_lifecycle_request_bytes, " + + "original_start_session_tuple, state, xmin::text AS xmin " + + "FROM game_session_canonical_initial_admission_intent " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + reserved.target().targetNamespace(), + reserved.request().initialAdmissionRequestId()), + "retained canonical initial-admission intent row"); + } + + private record ReservedIntent( + RuntimeTarget target, + WorldCanonicalInitialAdmissionHold.Request request, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + CanonicalInitialAdmissionIntentSnapshot snapshot) {} + private static void migrate(String schema, DriverManagerDataSource dataSource) { Flyway.configure() .dataSource(dataSource) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java new file mode 100644 index 0000000000..d1284bc81d --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java @@ -0,0 +1,1064 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.Comparator; +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.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +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.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; +import tools.jackson.databind.json.JsonMapper; + +/** + * Controlled upstream evidence for local GS owner tests, using current closed Common contracts. + * Account, World and GD producer/transport authority is stipulated; GS owners and SQL remain real. + */ +public final class CanonicalHumanPublicationOwnerTestFixtures { + private static final tools.jackson.databind.ObjectMapper JSON = JsonMapper.builder().build(); + + private CanonicalHumanPublicationOwnerTestFixtures() {} + + public static String historicalDigest(String... fields) { + try { + var hash = java.security.MessageDigest.getInstance("SHA-256"); + for (String value : fields) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + hash.update(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + java.util.HexFormat.of().formatHex(hash.digest()); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + + private static UUID id(String value) { + return UUID.nameUUIDFromBytes(("TEST_ONLY:" + value).getBytes(StandardCharsets.UTF_8)); + } + + public static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID request = + UUID.nameUUIDFromBytes( + ("test-creation-request:" + source.targetNamespace() + ":" + source.canonicalTenantId()) + .getBytes(StandardCharsets.UTF_8)); + UUID operation = + UUID.nameUUIDFromBytes( + ("test-creation-operation:" + + source.targetNamespace() + + ":" + + source.canonicalTenantId()) + .getBytes(StandardCharsets.UTF_8)); + String digest = + GameTenantCreationDigest.requestDigest( + source.targetNamespace(), + request, + source.sourceGameTenantKey(), + source.worldDisplayName(), + null); + return new FreshTenantCreationEvidence( + 1, + source.targetNamespace(), + request, + operation, + digest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + request, + operation, + digest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + } + + public static RealmPolicyPublishedEvidence.PublishedSet publishedSet( + CreateCanonicalRealmCatalogRequest request, + AuthoredWorldSourceEvidence source, + UUID canonicalVersionId, + long versionRowId, + String publishRequestId, + String bundleRef, + String generationConfigRevision, + long publicationVersionStateEpoch) { + try { + TargetProof target = + new TargetProof( + source.canonicalTenantId(), + canonicalVersionId, + versionRowId, + source.sourceGameTenantKey(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + var seed = new WorldSeed(target, source.targetNamespace()).build(); + var original = DraftAuthorizationFenceBinding.fromStored(seed.originalAccountBindingBytes()); + var draft = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var appliedEpochs = + draft.affectedUnits().stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + String vector = + new String( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString( + List.of( + Map.of( + "owner", + "WORLD_MANAGEMENT", + "status", + "APPLIED", + "commitId", + draft.commitId().toString(), + "bindingDigest", + draft.digest(), + "resultIdentity", + "TEST_ONLY-world-applied", + "resultBytesBase64", + Base64.getEncoder().encodeToString(seed.appliedResultBytes()), + "appliedEpochs", + appliedEpochs)))), + StandardCharsets.UTF_8); + var intent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + source.canonicalTenantId(), + canonicalVersionId, + publishRequestId, + Long.toString(publicationVersionStateEpoch - 1), + "TEST_ONLY complete Human owner input", + draft.requestId(), + draft.commitId(), + draft.digest()); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + intent, + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + vector, + OffsetDateTime.parse("2026-10-14T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("publication-operation:" + publishRequestId + ":" + canonicalVersionId), + id("publication-fence:" + publishRequestId + ":" + canonicalVersionId), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selected), + java.util.Arrays.stream(SourceKind.values()) + .map( + kind -> + new SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> original.actorAccountId().toString(); + case TENANT -> source.canonicalTenantId().toString(); + case MEMBERSHIP -> + original.actorAccountId() + "/" + source.canonicalTenantId(); + default -> "TEST_ONLY-" + kind; + }, + "1", + "1", + null, + null, + ("TEST_ONLY-" + kind).getBytes(StandardCharsets.UTF_8))) + .toList()); + String workflow = + PublicationDigestRequestBinding.full( + source.canonicalTenantId().toString(), + Long.toString(versionRowId), + publishRequestId) + .derivedWorkflowIdentity(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + source.targetNamespace(), + source.canonicalTenantId(), + canonicalVersionId, + seed.request().intakeRequestId(), + id("world-publication-fence:" + publishRequestId + ":" + canonicalVersionId), + publishRequestId, + selected.digest().substring(7), + publicationVersionStateEpoch - 1, + workflow, + draft.commitId().toString(), + seed.request().contentDigest(), + 3, + seed.request().worldAffectedTuples()), + seed.selectorReceiptBytes(), + seed.originalAccountBindingBytes(), + seed.appliedResultBytes()); + var operation = + new GameDesignPublicationOperationBinding( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); + String policyJson = + RealmPolicySource.canonical( + Map.of( + "schemaVersion", + 1, + "worldSlug", + source.worldSlug(), + "worldDisplayName", + source.worldDisplayName(), + "realmSlug", + request.realmSlug(), + "realmDisplayName", + request.realmDisplayName(), + "visible", + request.visible(), + "publicProduction", + request.publicProduction(), + "stateScope", + request.stateScope(), + "entryPolicy", + request.characterCreationPolicy())); + var policySource = + new RealmPolicySource.Policy( + draft.commitId(), + id("policy-revision:" + request.requestId()), + "TEST_ONLY-policy", + RealmEntryPolicy.parse(policyJson, JSON)); + var capture = new RealmPolicySnapshot(draft, "1", List.of(policySource)); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(versionRowId), + null, + draft.commitId().toString(), + "WORLD_MANAGEMENT".equals(owner) + ? world.request().contentDigest() + : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + source.canonicalTenantId(), + canonicalVersionId, + bundleRef, + 1, + "v2", + workflow, + "sha256:" + "b".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of(), + generationConfigRevision, + world); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + publicationVersionStateEpoch); + UUID policyId = id("policy-identity:" + request.requestId()); + var policy = + new RealmPolicyPublishedEvidence.Policy( + policyId, + policySource, + RealmPolicyPublishedEvidence.policyDigest( + policyId, + target, + 1, + bundleRef, + release.contentDigest(), + workflow, + release.manifestHash(), + policySource)); + var frame = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(frame, "game-design-realm-policy-source-capture/v1"); + DraftAuthorizationFenceBinding.frame(frame, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(frame, capture.canonicalBytes()); + var policies = List.of(policy); + String digest = + RealmPolicyPublishedEvidence.computePolicySetDigest( + target, + 1, + draft.commitId(), + "1", + bundleRef, + release.contentDigest(), + workflow, + release.manifestHash(), + publicationVersionStateEpoch, + operation.canonicalBytes(), + frame.toByteArray(), + terminal.canonicalBytes(), + policies); + return new RealmPolicyPublishedEvidence.PublishedSet( + target, + 1, + draft.commitId(), + "1", + bundleRef, + release.contentDigest(), + workflow, + release.manifestHash(), + publicationVersionStateEpoch, + operation.canonicalBytes(), + frame.toByteArray(), + terminal.canonicalBytes(), + 1, + digest, + policies); + } catch (Exception invalid) { + throw new IllegalStateException( + "Controlled complete publication fixture is invalid", invalid); + } + } + + /** + * Controlled original release pair, preserving the schema1 boundary of existing local owner + * tests. + */ + public static net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence + completeBinding( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(publishedSet.terminalEvidenceBytes()); + var release = terminal.releaseContent(); + var participants = + release.participantDigests().stream() + .map( + participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + Long.toString(descriptor.versionId()), + false, + null, + publishedSet.sourceCommitId().toString(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey()), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) + .toList(); + var evidence = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + publishedSet.target().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + publishedSet.publishWorkflowId(), + publishedSet.sourceCommitId().toString(), + participants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + descriptor.generationConfigRevision()); + return new net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence( + descriptor, evidence); + } + + /** Controlled Account-issued tuple input; this helper establishes no live Account authority. */ + public static net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + tuple( + String namespace, + UUID tenant, + UUID ownerAccountUuid, + long gameTemplateId, + String requestId) { + var action = + new net.firedevops.firemud.common.operator.StartSessionOperatorAction( + net.firedevops.firemud.common.operator.StartSessionOperatorAction + .ACTION_FAMILY_SCHEMA_ID, + net.firedevops.firemud.common.operator.StartSessionOperatorAction + .ACTION_FAMILY_SCHEMA_VERSION, + new net.firedevops.firemud.common.operator.StartSessionOperatorAction.Scope( + tenant, namespace), + new net.firedevops.firemud.common.operator.StartSessionOperatorAction.Target( + gameTemplateId, ownerAccountUuid), + net.firedevops.firemud.common.operator.StartSessionOperatorAction.ExpectedVersion + .ABSENT, + new net.firedevops.firemud.common.operator.StartSessionOperatorAction.Mutation( + net.firedevops.firemud.common.operator.StartSessionOperatorAction.ClientIp + .absent()), + "TEST_ONLY original Human allocation"); + var pre = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(requestId, id("actor:" + tenant), action); + var now = java.time.Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MILLIS); + var values = + new net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture + .Values( + id("issuance:" + requestId), + "sha256:" + "a".repeat(64), + "1", + "CURRENT", + now, + now.plusSeconds(3600), + 1, + 1, + 1, + 1, + 1, + 1, + id("ui-token:" + requestId), + "1", + "1"); + return net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple + .createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-only/" + "a".repeat(64), + id("reservation:" + requestId), + 1, + net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture + .canonicalBytes(pre, values), + new net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle + .BundleReference( + net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle + .BUNDLE_VERSION, + "1", + "1", + "1")); + } + + /** + * Calls the actual GS attempt, selection-pin and descriptor-pin owners with controlled upstream + * inputs. + */ + public static net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository.AttemptClaim + pinLaunch( + org.jooq.DSLContext dsl, + org.springframework.transaction.support.TransactionTemplate transactions, + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple, + AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence binding) { + return pinLaunch( + dsl, transactions, tuple, source, publishedSet, binding, java.time.Duration.ofMinutes(5)); + } + + public static net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository.AttemptClaim + pinLaunch( + org.jooq.DSLContext dsl, + org.springframework.transaction.support.TransactionTemplate transactions, + net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple tuple, + AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence binding, + java.time.Duration lease) { + var attempts = + new net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository(dsl, lease); + var selections = + new net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + var descriptors = + new net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionLaunchDescriptorRepository(dsl, selections); + var reservation = + java.util.Objects.requireNonNull(transactions.execute(status -> attempts.reserve(tuple))); + var claim = reservation.claim().orElseThrow(); + var bundle = + net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.decode( + tuple.authorityEvidenceBundleBytes()); + var projection = + new net.firedevops.firemud.gamesession.repository + .GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + bundle.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence()), + tuple.canonicalBytes()); + transactions.executeWithoutResult( + status -> attempts.attachAccountRedemptionProjection(claim, projection)); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(publishedSet.terminalEvidenceBytes()); + var release = terminal.releaseContent(); + var world = release.worldStartLocationEvidence(); + var worldRequest = world.request(); + var intakeRequest = + new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + source.targetNamespace(), + worldRequest.intakeRequestId(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + var receipt = + new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + source.targetNamespace(), + worldRequest.intakeRequestId(), + id("world-source-operation:" + source.operationId()), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.requestDigest( + intakeRequest), + "sha256:" + "9".repeat(64), + source); + var selected = + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Association( + source.canonicalTenantId(), + binding.descriptor().gameTemplateId(), + publishedSet.target().canonicalVersionId(), + publishedSet.sourceCommitId(), + publishedSet.publishWorkflowId(), + GameDesignPublicationOperationBinding.fromStored(publishedSet.operationBytes()) + .account() + .input() + .selection() + .digest(), + "sha256:" + "b".repeat(64), + source.targetNamespace(), + worldRequest.intakeRequestId(), + receipt.operationId(), + source.operationId(), + source.worldSlug(), + source.evidenceDigest(), + new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec + .ByIdReadRequest( + 1, + source.targetNamespace(), + id("world-source-read:" + tuple.controlPlaneRequestId()), + worldRequest.intakeRequestId(), + source.canonicalTenantId()), + receipt); + var proto = + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() + .setId(binding.descriptor().releaseBundleId()) + .setVersionId(binding.descriptor().versionId()) + .setVersionNumber(release.versionNumber()) + .setAttestationSchemaVersion(release.attestationSchemaVersion()) + .setPublishWorkflowId(release.publishWorkflowId()) + .setManifestHash(release.manifestHash()) + .setManifestSchemaVersion(release.manifestSchemaVersion()) + .setGenerationConfigRevision(release.generationConfigRevision()) + .setPublishedReleaseBundleRef(release.publishedReleaseBundleRef()) + .setCanonicalTenantId(source.canonicalTenantId().toString()) + .setCanonicalVersionId(publishedSet.target().canonicalVersionId().toString()); + release + .participantDigests() + .forEach( + participant -> { + var item = + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigest() != null) + item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + proto.addParticipantDigests(item); + }); + var initialRequest = + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Request( + 1, + source.targetNamespace(), + id("first-selection:" + tuple.controlPlaneRequestId()), + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerFence(), + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .InitialConfigured()); + var initial = + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Result( + initialRequest, + selected, + proto.build(), + world, + publishedSet.publicationVersionStateEpoch()); + transactions.execute(status -> selections.pinInitialOrValidateExactReplay(claim, initial)); + var replayRequest = + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Request( + 1, + source.targetNamespace(), + initialRequest.readRequestId(), + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerFence(), + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .ExactReplay( + selected.canonicalVersionId(), + selected.selectedCommitId(), + selected.publishWorkflowId(), + selected.associationDigest())); + var replay = + new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .Result(replayRequest, selected, proto.build(), world, initial.phaseEpoch()); + var resolved = + new net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec.Resolved( + replay, + new net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec + .DescriptorOutcome(binding.descriptor())); + transactions.execute(status -> descriptors.pin(claim, resolved)); + return claim; + } + + private static final class WorldSeed { + private final TargetProof target; + private final String namespace; + private final String baseReference; + + private WorldSeed(TargetProof target, String namespace) { + this.target = target; + this.namespace = namespace; + this.baseReference = + "genesis:" + id("reviewed-genesis:" + namespace + ":" + target.canonicalVersionId()); + this.TENANT_ID = target.canonicalTenantId(); + this.VERSION_ID = target.canonicalVersionId(); + } + + private WorldPublishedStartLocationEvidence build() throws Exception { + return build(freshGraphBinding()); + } + + private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) throws Exception { + var terminal = + WorldDraftTerminalReadEvidence.Request.create(namespace, accountBinding(draft)); + var result = committedReadback(terminal, true); + var applied = JSON.readTree(result.result()); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .sorted( + Comparator.comparing(AffectedUnit::owner) + .thenComparing(AffectedUnit::aggregateType) + .thenComparing(AffectedUnit::aggregateId) + .thenComparing(AffectedUnit::scopeType) + .thenComparing(AffectedUnit::scopeId) + .thenComparing(AffectedUnit::expectedEpoch)) + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + namespace, + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()), + result.fullBinding(), + result.result()); + } + + private final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private final UUID REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private final UUID FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private final UUID TENANT_ID; + private final UUID VERSION_ID; + private final UUID REVISION_ID = uuid("66666666-6666-4666-8666-666666666666"); + private final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private final tools.jackson.databind.ObjectMapper JSON = + new tools.jackson.databind.ObjectMapper(); + + private DraftAuthorizationFenceBinding.OwnerReadback committedReadback( + WorldDraftTerminalReadEvidence.Request request, boolean freshGraph) throws Exception { + var account = request.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), + account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new java.io.DataOutputStream(operation); + java.util.function.Consumer frame = + bytes -> { + try { + frames.writeInt(bytes.length); + frames.write(bytes); + } catch (java.io.IOException impossible) { + throw new AssertionError(impossible); + } + }; + java.util.function.Consumer text = + value -> frame.accept(value.getBytes(StandardCharsets.UTF_8)); + text.accept("world-draft-terminal-operation/v1"); + for (UUID id : + List.of( + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + account.tenantId(), + account.versionId())) text.accept(id.toString()); + frame.accept(draft.canonicalBytes()); + for (String value : + List.of( + request.targetNamespace(), + account.tenantId().toString(), + account.versionId().toString(), + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + Long.toString(draft.target().gameDesignVersionRowId()), + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "a".repeat(64), + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + "b".repeat(64), + "c".repeat(64))) text.accept(value); + text.accept(sha256(account.canonicalBytes())); + frame.accept(account.canonicalBytes()); + byte[] graph = freshGraph ? graphBytes(request, draft) : historicalGraphBytes(account); + String graphDigest = sha256(graph); + var result = new java.util.LinkedHashMap(); + result.put( + "schema", freshGraph ? "world-draft-graph-applied/v2" : "world-draft-graph-applied/v1"); + result.put("status", "APPLIED"); + result.put( + "operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + if (freshGraph) { + var receipt = receipt(request, draft, graphDigest); + byte[] receiptBytes = canonical(receipt); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.get("receiptDigest").textValue()); + } + result.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) + .toList()); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + canonical(JSON.valueToTree(result))); + } + + private DraftCommitBinding freshGraphBinding() throws Exception { + return DraftCommitBinding.create( + new TargetProof( + TENANT_ID, + VERSION_ID, + target.gameDesignVersionRowId(), + target.gameDesignVersionTenantKey(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.sourceProvenanceKind()), + REQUEST_ID, + COMMIT_ID, + baseReference, + freshWorldRevisions(COMMIT_ID, 0), + freshWorldAffectedUnits()); + } + + private List freshWorldRevisions(UUID commitId, int revisionOffset) + throws Exception { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "startLocation", + Map.of( + "tenantId", TENANT_ID.toString(), + "versionId", VERSION_ID.toString(), + "roomTemplateId", ROOM_TEMPLATE_ID.toString()), + "familyCounts", + List.of( + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_REGION", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", "count", 1), + Map.of("family", "WORLD_DESIGN_AGGREGATE_TYPE_ROOM_EXIT", "count", 0), + Map.of( + "family", "WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE", "count", 0), + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_WORLD_ENTITY_SPAWN_BINDING", + "count", + 0)))); + return List.of( + new RevisionPayload( + Integer.toString(revisionOffset), + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + Integer.toString(revisionOffset + 1), + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ZONE_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", + ZONE_TEMPLATE_ID, + null)), + new RevisionPayload( + Integer.toString(revisionOffset + 2), + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + commitId, + ROOM_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", + ROOM_TEMPLATE_ID, + null))); + } + + private List freshWorldAffectedUnits() { + return List.of( + affected("REGION", REGION_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ZONE", ZONE_TEMPLATE_ID, "REGION_SUBTREE", REGION_TEMPLATE_ID), + affected("ROOM", ROOM_TEMPLATE_ID, "ZONE_SUBTREE", ZONE_TEMPLATE_ID)) + .stream() + .flatMap(List::stream) + .toList(); + } + + private String worldRevisionPayload( + UUID commitId, UUID revisionId, String family, UUID templateId, String declaration) + throws Exception { + var payload = new java.util.LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", commitId.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + return JSON.writeValueAsString(payload); + } + + private List affected( + String family, UUID templateId, String scopeType, UUID scopeId) { + return List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + "AGGREGATE", + templateId.toString(), + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + family, + templateId.toString(), + scopeType, + scopeId.toString(), + "0")); + } + + private byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + draft.requestId(), + draft.commitId(), + FENCE_ID, + ACTOR_ID, + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + draft.baseCommitId(), + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .withRequiredOwners() + .canonicalBytes(); + } + + private byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new java.util.LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new java.util.ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + var mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new java.util.LinkedHashMap(); + mapping.put("id", mappingId++); + mapping.put("target_namespace", request.targetNamespace()); + mapping.put("canonical_tenant_id", draft.target().canonicalTenantId().toString()); + mapping.put("canonical_version_id", draft.target().canonicalVersionId().toString()); + mapping.put("family", family); + mapping.put("template_id", mutation.get("aggregateId").textValue()); + mapping.put("private_row_key", privateRowKey++); + mapping.put("tenant_id", 11); + mapping.put("version_id", target.gameDesignVersionRowId()); + mapping.put("version_identity_operation_id", OPERATION_ID.toString()); + mapping.put("request_id", draft.requestId().toString()); + mapping.put("commit_id", draft.commitId().toString()); + mapping.put("revision_id", revision.revisionId().toString()); + mapping.put("revision_order", revision.revisionOrder()); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + root.put("rows", rows); + return JSON.writeValueAsBytes(root); + } + + private byte[] historicalGraphBytes(DraftAuthorizationFenceBinding account) { + throw new IllegalArgumentException("This fixture supplies only selector-bearing APPLIED v2"); + } + + private tools.jackson.databind.node.ObjectNode receipt( + WorldDraftTerminalReadEvidence.Request request, + DraftCommitBinding draft, + String graphDigest) + throws Exception { + var account = request.accountBinding(); + var receipt = + WorldDraftStartLocationEvidence.create( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + sha256(account.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(TENANT_ID, VERSION_ID, ROOM_TEMPLATE_ID), + graphDigest); + return (tools.jackson.databind.node.ObjectNode) JSON.readTree(receipt.canonicalBytes()); + } + + private byte[] canonical(tools.jackson.databind.JsonNode value) throws Exception { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(value)); + } + + private String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private UUID uuid(String value) { + return UUID.fromString(value); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java index f4e082cb1c..f3750559be 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java @@ -4,25 +4,22 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.nio.file.Path; import java.sql.DriverManager; -import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; -import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; @@ -41,7 +38,8 @@ import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; -import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; import net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionHoldPreparation; import net.firedevops.firemud.test.TestContainerImages; @@ -54,7 +52,6 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -70,7 +67,6 @@ class CanonicalInitialAdmissionIntentRepositoryIntegrationTest { private static final UUID INTAKE_REQUEST = uuid(403); private static final UUID CATALOG_REQUEST = uuid(404); private static final UUID ACTOR = uuid(405); - private static final UUID GAME_INSTANCE_UUID = uuid(406); private static final UUID CANONICAL_VERSION = uuid(407); private static final UUID ASSOCIATION_OPERATION = uuid(408); private static final String CONTROL_PLANE_REQUEST_ID = "canonical-intent-launch-1"; @@ -82,7 +78,7 @@ class CanonicalInitialAdmissionIntentRepositoryIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() { + void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() throws java.sql.SQLException { Harness harness = harness(); try { OwnerTarget target = harness.seed(); @@ -106,7 +102,8 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() { .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.PENDING_HOLD); assertThat(reserved.holdIdentity()).isNull(); assertThat(reserved.sourceBinding().gameInstanceId()).isEqualTo(target.gameInstanceId()); - assertThat(reserved.sourceBinding().currentRowVersion()).isPositive(); + assertThat(reserved.sourceBinding().currentRowVersion()) + .isEqualTo(target.launch().association().currentRowVersion()); assertThat( target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) .contains(reserved); @@ -126,6 +123,27 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() { assertThat(retry.sourceBinding().currentRowVersion()) .isEqualTo(reserved.sourceBinding().currentRowVersion()); + var intentEvidence = + harness.dsl.fetchSingle( + "SELECT original_start_session_tuple, catalog_source_intake_operation_id, " + + "catalog_source_intake_request_id FROM game_session_canonical_initial_admission_intent " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + request.targetNamespace(), + request.initialAdmissionRequestId()); + var launchEvidence = + harness.dsl.fetchSingle( + "SELECT original_start_session_tuple, catalog_source_intake_operation_id, " + + "catalog_source_intake_request_id FROM game_session_canonical_instance_launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + request.targetNamespace(), + reserved.sourceBinding().controlPlaneRequestId()); + assertThat(intentEvidence.get("original_start_session_tuple", byte[].class)) + .containsExactly(launchEvidence.get("original_start_session_tuple", byte[].class)); + assertThat(intentEvidence.get("catalog_source_intake_operation_id", UUID.class)) + .isEqualTo(target.catalog().sourceIntakeReceipt().operationId()); + assertThat(intentEvidence.get("catalog_source_intake_request_id", UUID.class)) + .isEqualTo(target.catalog().sourceIntakeReceipt().intakeRequestId()); + assertPendingIntentVisibleFromSeparateConnection(harness, request, lifecycle); var changedLifecycle = target.lifecycleRequest(uuid(413)); assertThatThrownBy( () -> @@ -195,78 +213,32 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() { } @Test - void commitsPendingHoldBeforeWorldAcquireAndRetriesTheSameIntentAfterAcquireFailure() - throws Exception { + void incompleteHumanPreparationDeniesBeforeIntentReservationOrWorldAcquire() { Harness harness = harness(); try { OwnerTarget target = harness.seed(); - var request = holdRequest(target, "intent-coordinator-ordering"); + var request = holdRequest(target, "intent-unprotected-human"); var lifecycle = target.lifecycleRequest(uuid(418)); - var identity = - new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, uuid(419), uuid(420)); WorldCanonicalInitialAdmissionHoldClient worldClient = mock(WorldCanonicalInitialAdmissionHoldClient.class); - AtomicInteger acquireCalls = new AtomicInteger(); - - when(worldClient.acquire(any(), any())) - .thenAnswer( - invocation -> { - var acquireRequest = - invocation.getArgument(0, WorldCanonicalInitialAdmissionHold.Request.class); - var acquireLifecycle = - invocation.getArgument( - 1, WorldCanonicalInstanceLifecycleEvidence.Request.class); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(acquireRequest.canonicalRequestBytes()) - .containsExactly(request.canonicalRequestBytes()); - assertThat(acquireLifecycle.canonicalBytes()) - .containsExactly(lifecycle.canonicalBytes()); - assertPendingIntentVisibleFromSeparateConnection( - harness, acquireRequest, acquireLifecycle); - - if (acquireCalls.incrementAndGet() == 1) { - throw new IllegalStateException("simulated World acquire failure"); - } - return identity; - }); - var preparation = new CanonicalInitialAdmissionHoldPreparation( target.intents(), worldClient, harness.transactionManager); - - assertThatThrownBy(() -> preparation.prepare(request, lifecycle)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("simulated World acquire failure"); - var pending = - target - .intents() - .read(target.targetNamespace(), request.initialAdmissionRequestId()) - .orElseThrow(); - assertThat(pending.state()) - .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.PENDING_HOLD); - assertThat(pending.holdRequest().canonicalRequestBytes()) - .containsExactly(request.canonicalRequestBytes()); - assertThat(pending.lifecycleRequest().canonicalBytes()) - .containsExactly(lifecycle.canonicalBytes()); - assertThat(pending.holdIdentity()).isNull(); - - var attached = preparation.prepare(request, lifecycle); - assertThat(acquireCalls).hasValue(2); - assertThat(attached.state()) - .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.HOLD_ATTACHED); - assertThat(attached.holdRequest().canonicalRequestBytes()) - .containsExactly(request.canonicalRequestBytes()); - assertThat(attached.lifecycleRequest().canonicalBytes()) - .containsExactly(lifecycle.canonicalBytes()); - assertThat(attached.holdIdentity()).isEqualTo(identity); + for (int retry = 0; retry < 2; retry++) { + assertThatThrownBy(() -> preparation.prepare(request, lifecycle)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); + } + verifyNoInteractions(worldClient); assertThat( target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) - .contains(attached); + .isEmpty(); assertThat( harness.dsl.fetchCount( DSL.table(DSL.name("game_session_canonical_initial_admission_intent")))) - .isEqualTo(1); + .isZero(); assertNoAdmissionMutation(harness.dsl); } finally { harness.close(); @@ -687,7 +659,7 @@ private static CreateCanonicalRealmCatalogRequest catalogRequest(IntakeReceipt s true, true, "SHARED", - "explicit-policy-v1", + "PRESEEDED_ONLY", null, null); } @@ -710,8 +682,8 @@ private static CreateCanonicalLaunchPreparationRequest preparationRequest( null, false, null, - false, - null); + true, + "{}"); } private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( @@ -733,7 +705,9 @@ private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( "published-bundle-intent", false, null); - CompleteLaunchBindingEvidence binding = completeBinding(descriptor); + CompleteLaunchBindingEvidence binding = + CanonicalHumanPublicationOwnerTestFixtures.completeBinding( + descriptor, publishedPolicy(source)); when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) .thenReturn(descriptor); when(client.get(any(GetRequest.class))).thenReturn(descriptor); @@ -741,47 +715,17 @@ private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( return client; } - private static CompleteLaunchBindingEvidence completeBinding( - AuthoredWorldLaunchDescriptorEvidence descriptor) { - String commitId = "publish-commit-canonical-intent"; - List participants = - AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - commitId, - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? digest("d") : null)) - .toList(); - AuthoredWorldReleaseAttestationEvidence attestation = - AuthoredWorldReleaseAttestationEvidence.create( - descriptor.targetNamespace(), - descriptor.resultDigest(), - descriptor.canonicalTenantId(), - CANONICAL_VERSION, - descriptor.worldSlug(), - descriptor.authoredWorldSourceOperationId(), - descriptor.authoredWorldSourceEvidenceDigest(), - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - "publish-canonical-intent", - commitId, - participants, - digest("b"), - 1, - List.of(), - List.of(), - List.of(), - descriptor.generationConfigRevision()); - return new CompleteLaunchBindingEvidence(descriptor, attestation); + private static net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence.PublishedSet + publishedPolicy(IntakeReceipt source) { + return CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + catalogRequest(source), + source.source(), + CANONICAL_VERSION, + 72L, + "publish-canonical-intent", + "published-bundle-intent", + "generation-1", + 3L); } private static String digest(String letter) { @@ -831,8 +775,18 @@ OwnerTarget seed() { Objects.requireNonNull( transactions.execute( status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + transactions.execute( + status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source()))); var preparedCatalog = - catalogRepository.prepareInitialPublicProduction(catalogRequest(source)); + catalogRepository.prepareInitialPublicProduction( + catalogRequest(source), publishedPolicy(source)); CanonicalRealmCatalogSnapshot catalog = Objects.requireNonNull( transactions.execute( @@ -849,96 +803,57 @@ OwnerTarget seed() { var preparedLaunch = preparationService.prepare(preparationRequest); CompleteLaunchBindingEvidence binding = preparationService.readCompleteBinding(preparedLaunch); - createTestOnlyFreshMappingAndRunningLaunch(source, binding, launchRepository); + UUID allocatedInstanceUuid = + createTestOnlyFreshMappingAndRunningLaunch(source, binding, launchRepository); CanonicalInitialAdmissionLaunchTarget launch = launchRepository - .readForInitialAdmission(NAMESPACE, TENANT, catalog.realmId(), GAME_INSTANCE_UUID) + .readForInitialAdmission(NAMESPACE, TENANT, catalog.realmId(), allocatedInstanceUuid) .orElseThrow(); var intentRepository = new CanonicalInitialAdmissionIntentRepository(dsl, catalogRepository, launchRepository); return new OwnerTarget(this, catalog, launch, intentRepository); } - private void createTestOnlyFreshMappingAndRunningLaunch( + private UUID createTestOnlyFreshMappingAndRunningLaunch( IntakeReceipt source, CompleteLaunchBindingEvidence binding, CanonicalGameInstanceLaunchAssociationRepository launchRepository) { - RuntimeTenantIdentityEvidence sourceIdentity = - new RuntimeTenantIdentityEvidence( - 1, + var tuple = + CanonicalHumanPublicationOwnerTestFixtures.tuple( NAMESPACE, - source.source().registrationRequestId(), TENANT, - source.source().sourceGameRowId(), - source.source().sourceGameTenantKey(), - source.source().provenanceKind()); - transactions.execute( - status -> { - Record reservation = - Objects.requireNonNull( - dsl.fetchOne( - "INSERT INTO game_session_tenant_scope_reservation " - + "(reservation_kind) VALUES ('FRESH_SOURCE_BOUND') " - + "RETURNING game_session_tenant_id")); - long tenantId = reservation.get("game_session_tenant_id", Long.class); - var tenantAssociation = - new FreshGameSessionTenantAssociation( - ASSOCIATION_OPERATION, tenantId, sourceIdentity); - dsl.execute( - "INSERT INTO game_session_tenant_canonical_claim " - + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, " - + "association_kind, reservation_kind, association_operation_id, " - + "association_request_id) " - + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", - NAMESPACE, - TENANT, - tenantId, - ASSOCIATION_OPERATION, - source.source().registrationRequestId()); - dsl.execute( - "INSERT INTO game_session_fresh_tenant_association " - + "(association_operation_id, target_namespace, association_request_id, " - + "source_schema_version, source_target_namespace, source_request_id, " - + "source_canonical_tenant_id, canonical_tenant_id, " - + "legacy_game_session_tenant_id, source_game_row_id, " - + "source_game_tenant_key, provenance_kind, association_kind) " - + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND')", - ASSOCIATION_OPERATION, - NAMESPACE, - source.source().registrationRequestId(), - NAMESPACE, - source.source().registrationRequestId(), - TENANT, - TENANT, - tenantId, - source.source().sourceGameRowId(), - source.source().sourceGameTenantKey()); - Record instance = - Objects.requireNonNull( - dsl.fetchOne( - "INSERT INTO game_instances " - + "(tenant_id, runtime_version, game_template_id, launch_descriptor_id, " - + "version_id, release_bundle_id, generation_config_revision, " - + "version_state_epoch, owner_account_id, status, row_version, " - + "game_instance_uuid, run_owned_start_request_id, " - + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref, " - + "run_owned_start_preparing_epoch, run_owned_start_active_epoch) " - + "VALUES (?, '72', 404, ?, 72, 73, 'generation-1', 3, 77, 'STARTING', " - + "1, ?, ?, ?, ?, 1, 2) RETURNING id", - tenantId, - binding.descriptor().launchDescriptorId(), - GAME_INSTANCE_UUID, - CONTROL_PLANE_REQUEST_ID, - "c".repeat(64), - binding.descriptor().publishedReleaseBundleRef())); - long gameInstanceId = instance.get("id", Long.class); - launchRepository.capture(tenantAssociation, gameInstanceId, binding); - dsl.execute( - "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", - tenantId, - gameInstanceId); - return null; - }); + ACTOR, + binding.descriptor().gameTemplateId(), + binding.descriptor().controlPlaneRequestId()); + CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( + dsl, transactions, tuple, source.source(), publishedPolicy(source), binding); + return Objects.requireNonNull( + transactions.execute( + status -> { + var association = + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source())); + var starting = + new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE) + .createStarting( + association, + binding, + ACTOR, + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple); + dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + association.legacyGameSessionTenantId(), + starting.gameInstanceId()); + return starting.gameInstanceUuid(); + }), + "Actual owner-allocated canonical instance UUID"); } void close() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index bd8579d5d7..83688f80f3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -4,21 +4,32 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorClient; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; -import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; @@ -34,6 +45,8 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; @@ -41,11 +54,13 @@ import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; 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.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.postgresql.util.PSQLException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; @@ -58,10 +73,11 @@ /** * PostgreSQL proof for the canonical first-OPEN owner transaction. * - *

The direct V25 reservation/claim/association inserts below are test-only owner fixtures for - * exercising the migrated constraints. They are not a runtime fresh-tenant mapping producer. The - * World proof is also test data; production remains disabled until the real verifier and Account - * authorization redemption are composed. + *

Fresh association, catalog, and launch pins use their actual Game Session owners with + * controlled upstream creation, publication, Account tuple/projection, and World inputs. These + * inputs do not execute genuine upstream producers or establish Account terminal protection. Human + * terminal positives remain an implementation obligation until the protected owner boundary is + * composed. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -72,7 +88,6 @@ class CanonicalInitialAdmissionRepositoryIntegrationTest { private static final UUID INTAKE_REQUEST = uuid(103); private static final UUID CATALOG_REQUEST = uuid(104); private static final UUID ACTOR = uuid(105); - private static final UUID GAME_INSTANCE_UUID = uuid(108); private static final UUID CANONICAL_VERSION = uuid(109); private static final UUID ASSOCIATION_OPERATION = uuid(110); private static final String CONTROL_PLANE_REQUEST_ID = "canonical-start-instance-1"; @@ -84,94 +99,46 @@ class CanonicalInitialAdmissionRepositoryIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { - Fixture fixture = fixture(); - IntakeReceipt source = fixture.registerSource(); - CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); - CreateCanonicalLaunchPreparationRequest preparationRequest = - preparationRequest(source, catalog); - AuthoredWorldLaunchDescriptorClient syntheticGameDesign = - syntheticGameDesignClient(preparationRequest, catalog, source); - GameSessionCanonicalLaunchPreparationService preparationService = - new GameSessionCanonicalLaunchPreparationService( - syntheticGameDesign, - fixture.catalogRepository, - fixture.sourceRepository, - fixture.preparationRepository, - fixture.transactionManager, - NAMESPACE); - CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); - CompleteLaunchBindingEvidence completeBinding = - preparationService.readCompleteBinding(preparation); - - FreshGameSessionTenantAssociation tenantAssociation = - fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); - CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); - assertThat(tenantAssociation.legacyGameSessionTenantId()) - .isNotEqualTo(source.source().sourceGameRowId()); - assertThat(request.playableStateNamespaceId()).isEqualTo(catalog.playableStateNamespaceId()); - CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); + void freshHumanReservationDeniesBeforeEffectsAndRetainedPendingCannotCommit() throws Exception { + Fixture fixture = fixture("1005"); + PredecessorAdmission predecessor = preparePre1006Admission(fixture); + PreparedAdmission prepared = predecessor.prepared(); + CanonicalInitialAdmissionRequest request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + reservePre1006Attempt(fixture, predecessor.launch(), request); + migration(fixture, null).migrate(); + migration(fixture, null).validate(); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(request); - return null; - }); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(request); - return null; - }); + CanonicalInitialAdmissionOwnerProof pending = + fixture + .initialAdmissionRepository + .read(NAMESPACE, request.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(pending.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + String before = attemptProjection(fixture, request); + CanonicalInitialAdmissionRequest freshRequest = + initialAdmissionRequest( + prepared.catalog(), + prepared.binding(), + prepared.gameInstanceUuid(), + "fresh-human-reserve-denied-" + prepared.catalog().realmId(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + uuid(115), + uuid(116)); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.reserve(freshRequest)); assertThat( - fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + fixture.initialAdmissionRepository.read( + NAMESPACE, freshRequest.initialAdmissionRequestId())) + .isEmpty(); assertThat( fixture.dsl.fetchCount( DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) .isEqualTo(1); - - CanonicalInitialAdmissionWorldProof changedProof = - new CanonicalInitialAdmissionWorldProof( - worldProof.initialAdmissionRequestId(), - worldProof.requestDigest(), - worldProof.targetNamespace(), - worldProof.canonicalTenantId(), - worldProof.worldSlug(), - worldProof.realmId(), - worldProof.playableStateNamespaceId(), - worldProof.playableStateScope(), - worldProof.canonicalGameInstanceId(), - worldProof.canonicalVersionId(), - worldProof.lifecycleState(), - worldProof.activeLifecycleEpoch(), - worldProof.originKind(), - worldProof.expectedCatalogRevision(), - worldProof.expectedPriorPointerVersion(), - worldProof.holdId(), - uuid(111), - worldProof.holdBindingDigest()); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.commit(request, changedProof, null); - return null; - })) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("does not match the exact initial admission request"); - assertThat( - fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); - assertThat( - Objects.requireNonNull( - fixture - .dsl - .fetchSingle( - "SELECT count(*) FROM gameplay_admission_pointer " - + "WHERE representation_version = 3") - .get(0, Long.class))) + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) .isZero(); UUID mismatchedGameInstance = uuid(998); @@ -235,222 +202,31 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { DSL.field(DSL.name("representation_version"), Integer.class).eq(3))) .isZero(); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.commit(request, worldProof, null); - return null; - }); - - CanonicalInitialAdmissionOwnerProof committed = - fixture - .initialAdmissionRepository - .read(NAMESPACE, request.initialAdmissionRequestId()) - .orElseThrow(); - assertThat(committed.outcome()) - .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); - assertThat(committed.canonicalTenantId()).isEqualTo(TENANT); - assertThat(committed.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_UUID); - assertThat(committed.canonicalVersionId()).isEqualTo(CANONICAL_VERSION); - assertThat(committed.committedPointerVersion()).isEqualTo(1L); - assertThat(committed.auditEventId()).isPositive(); - CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentSnapshot = - fixture.initialAdmissionRepository.readCurrentOpenSnapshotForRealm( - NAMESPACE, TENANT, request.realmId()); - assertThat(currentSnapshot.ownerProof()).isEqualTo(committed); - assertThat(currentSnapshot.admissionPointerSnapshotDigest()).matches("[0-9a-f]{64}"); - assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) - .isEqualTo(1); - - Record pointer = - Objects.requireNonNull( - fixture.dsl.fetchOne( - "SELECT id, pointer_version, tenant_id, game_instance_id, " - + "canonical_tenant_id, realm_id, " - + "canonical_game_instance_id, canonical_version_id, initial_admission_request_id, " - + "admission_state, representation_version FROM gameplay_admission_pointer " - + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ?", - NAMESPACE, - TENANT, - request.realmId())); - assertThat(pointer.get("tenant_id", Long.class)) - .isEqualTo(tenantAssociation.legacyGameSessionTenantId()); - assertThat(pointer.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); - assertThat(pointer.get("realm_id", UUID.class)).isEqualTo(request.realmId()); - assertThat(pointer.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); - assertThat(pointer.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); - assertThat(pointer.get("initial_admission_request_id", String.class)) - .isEqualTo(request.initialAdmissionRequestId()); - assertThat(pointer.get("admission_state", String.class)).isEqualTo("OPEN"); - assertThat(pointer.get("representation_version", Integer.class)).isEqualTo(3); - - Record audit = - Objects.requireNonNull( - fixture.dsl.fetchOne( - "SELECT canonical_tenant_id, realm_id, canonical_game_instance_id, " - + "canonical_version_id, initial_admission_request_id, admission_state " - + "FROM gameplay_admission_pointer_event WHERE id = ?", - committed.auditEventId())); - assertThat(audit.get("canonical_tenant_id", UUID.class)).isEqualTo(TENANT); - assertThat(audit.get("realm_id", UUID.class)).isEqualTo(request.realmId()); - assertThat(audit.get("canonical_game_instance_id", UUID.class)).isEqualTo(GAME_INSTANCE_UUID); - assertThat(audit.get("canonical_version_id", UUID.class)).isEqualTo(CANONICAL_VERSION); - assertThat(audit.get("initial_admission_request_id", String.class)) - .isEqualTo(request.initialAdmissionRequestId()); - assertThat(audit.get("admission_state", String.class)).isEqualTo("OPEN"); - - CanonicalInitialAdmissionRequest replayRequest = - initialAdmissionRequest(catalog, completeBinding); - CanonicalInitialAdmissionWorldProof replayWorldProof = testWorldProof(replayRequest); - assertThat(replayRequest).isEqualTo(request); - assertThat(replayWorldProof).isEqualTo(worldProof); - int pointerRowsBeforeReplay = - fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer"))); - int auditRowsBeforeReplay = - fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event"))); - - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(replayRequest); - return null; - }); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.commit(replayRequest, replayWorldProof, null); - return null; - }); - - CanonicalInitialAdmissionOwnerProof replayed = - fixture - .initialAdmissionRepository - .read(NAMESPACE, replayRequest.initialAdmissionRequestId()) - .orElseThrow(); - assertThat(replayed).isEqualTo(committed); - Record pointerAfterReplay = - Objects.requireNonNull( - fixture.dsl.fetchOne( - "SELECT id, pointer_version, tenant_id, game_instance_id, canonical_tenant_id, " - + "realm_id, canonical_game_instance_id, canonical_version_id, " - + "initial_admission_request_id, admission_state, representation_version " - + "FROM gameplay_admission_pointer WHERE target_namespace = ? " - + "AND canonical_tenant_id = ? AND realm_id = ?", - NAMESPACE, - TENANT, - replayRequest.realmId())); - assertThat(pointerAfterReplay.get("id", Long.class)).isEqualTo(pointer.get("id", Long.class)); - assertThat(pointerAfterReplay.get("pointer_version", Long.class)) - .isEqualTo(pointer.get("pointer_version", Long.class)); - assertThat(pointerAfterReplay.get("tenant_id", Long.class)) - .isEqualTo(pointer.get("tenant_id", Long.class)); - assertThat(pointerAfterReplay.get("game_instance_id", Long.class)) - .isEqualTo(pointer.get("game_instance_id", Long.class)); - assertThat(pointerAfterReplay.get("canonical_tenant_id", UUID.class)) - .isEqualTo(pointer.get("canonical_tenant_id", UUID.class)); - assertThat(pointerAfterReplay.get("realm_id", UUID.class)) - .isEqualTo(pointer.get("realm_id", UUID.class)); - assertThat(pointerAfterReplay.get("canonical_game_instance_id", UUID.class)) - .isEqualTo(pointer.get("canonical_game_instance_id", UUID.class)); - assertThat(pointerAfterReplay.get("canonical_version_id", UUID.class)) - .isEqualTo(pointer.get("canonical_version_id", UUID.class)); - assertThat(pointerAfterReplay.get("initial_admission_request_id", String.class)) - .isEqualTo(pointer.get("initial_admission_request_id", String.class)); - assertThat(pointerAfterReplay.get("admission_state", String.class)) - .isEqualTo(pointer.get("admission_state", String.class)); - assertThat(pointerAfterReplay.get("representation_version", Integer.class)) - .isEqualTo(pointer.get("representation_version", Integer.class)); - Record auditAfterReplay = - Objects.requireNonNull( - fixture.dsl.fetchOne( - "SELECT canonical_tenant_id, realm_id, canonical_game_instance_id, " - + "canonical_version_id, initial_admission_request_id, admission_state " - + "FROM gameplay_admission_pointer_event WHERE id = ?", - replayed.auditEventId())); - assertThat(auditAfterReplay.get("canonical_tenant_id", UUID.class)) - .isEqualTo(audit.get("canonical_tenant_id", UUID.class)); - assertThat(auditAfterReplay.get("realm_id", UUID.class)) - .isEqualTo(audit.get("realm_id", UUID.class)); - assertThat(auditAfterReplay.get("canonical_game_instance_id", UUID.class)) - .isEqualTo(audit.get("canonical_game_instance_id", UUID.class)); - assertThat(auditAfterReplay.get("canonical_version_id", UUID.class)) - .isEqualTo(audit.get("canonical_version_id", UUID.class)); - assertThat(auditAfterReplay.get("initial_admission_request_id", String.class)) - .isEqualTo(audit.get("initial_admission_request_id", String.class)); - assertThat(auditAfterReplay.get("admission_state", String.class)) - .isEqualTo(audit.get("admission_state", String.class)); - assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) - .isEqualTo(1); - assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) - .isEqualTo(pointerRowsBeforeReplay); - assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) - .isEqualTo(auditRowsBeforeReplay); - - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO gameplay_admission_pointer (" - + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " - + "game_instance_id, pointer_version, visible, requires_character_selection, " - + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " - + "public_production_realm, catalog_revision) " - + "VALUES ('numeric-scope-guard-test', 'numeric-scope-guard-test', " - + "'Numeric Scope Guard', 'Numeric Scope Guard', ?, 1, 1, TRUE, FALSE, " - + "'SHARED', 'owner-mode', 'scope-guard-test', 'numeric-only guard', TRUE, 1)", - tenantAssociation.legacyGameSessionTenantId())) - .hasMessageContaining("Numeric-only tenant scope cannot use a fresh source-bound key"); - assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("gameplay_admission_pointer")), - DSL.field(DSL.name("world_slug"), String.class).eq("numeric-scope-guard-test"))) - .isZero(); - - UUID mismatchedTenant = uuid(997); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO gameplay_admission_pointer (" - + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " - + "game_instance_id, pointer_version, visible, requires_character_selection, " - + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " - + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " - + "playable_state_namespace_id, representation_version, target_namespace, " - + "canonical_tenant_id, admission_state, canonical_game_instance_id, " - + "canonical_version_id, runtime_version_id, initial_admission_request_id, " - + "initial_admission_request_digest, initial_admission_origin_kind, " - + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " - + "initial_admission_hold_id, initial_admission_hold_fence, " - + "initial_admission_hold_binding_digest) " - + "SELECT world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " - + "game_instance_id, pointer_version + 1, visible, requires_character_selection, " - + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " - + "created_at, updated_at, public_production_realm, catalog_revision, realm_id, " - + "playable_state_namespace_id, representation_version, target_namespace, ?, " - + "admission_state, canonical_game_instance_id, canonical_version_id, " - + "runtime_version_id, initial_admission_request_id, initial_admission_request_digest, " - + "initial_admission_origin_kind, initial_admission_prior_pointer_version, " - + "initial_admission_active_epoch, initial_admission_hold_id, " - + "initial_admission_hold_fence, initial_admission_hold_binding_digest " - + "FROM gameplay_admission_pointer WHERE id = ?", - mismatchedTenant, - pointer.get("id", Long.class))) - .hasMessageContaining( - "Canonical OPEN pointer requires exact catalog and launch owner evidence"); - assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("gameplay_admission_pointer")), - DSL.field(DSL.name("representation_version"), Integer.class).eq(3))) - .isEqualTo(1); - assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("gameplay_admission_pointer")), - DSL.field(DSL.name("canonical_tenant_id"), UUID.class).eq(mismatchedTenant))) - .isZero(); + for (int retry = 0; retry < 2; retry++) { + assertHumanProtectionUnavailable( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture.initialAdmissionRepository.commit(request, testWorldProof(request)))); + assertHumanProtectionUnavailable( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture.initialAdmissionRepository.abort(request, "Missing protection"))); + assertThat(attemptProjection(fixture, request)).isEqualTo(before); + assertThat( + fixture.initialAdmissionRepository.read( + NAMESPACE, request.initialAdmissionRequestId())) + .contains(pending); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isZero(); + } } @Test - void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { + void denies128CharacterFreshHumanIntentBeforeReservation() { Fixture fixture = fixture(); PreparedAdmission prepared = prepareAdmission(fixture); String requestId = "r".repeat(128); @@ -458,77 +234,57 @@ void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { initialAdmissionRequest( prepared.catalog(), prepared.binding(), + prepared.gameInstanceUuid(), requestId, CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, null, uuid(115), uuid(116)); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(request); - return null; - }); - - CanonicalInitialAdmissionOwnerProof retained = - fixture.initialAdmissionRepository.read(NAMESPACE, requestId).orElseThrow(); - assertThat(retained.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); - assertThat(retained.initialAdmissionRequestId()).isEqualTo(requestId); - assertThat(retained.holdId()).isEqualTo(request.holdId()); - assertThat(retained.holdFence()).isEqualTo(request.holdFence()); + assertHumanProtectionUnavailable(() -> fixture.initialAdmissionRepository.reserve(request)); + assertNoAttemptAndNoPending(fixture, request); + assertThat(fixture.initialAdmissionRepository.read(NAMESPACE, requestId)).isEmpty(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isZero(); } @Test - void newNoPriorPointerReservationRejectsAnAlreadyOpenRealmWithoutLeavingPendingAttempt() { + void competingFreshHumanReservationsDenyBeforeIntentOrPointerEffects() { Fixture fixture = fixture(); - PreparedAdmission preparedAdmission = prepareAdmission(fixture); - CanonicalRealmCatalogSnapshot catalog = preparedAdmission.catalog(); - CompleteLaunchBindingEvidence binding = preparedAdmission.binding(); - CanonicalInitialAdmissionRequest firstRequest = initialAdmissionRequest(catalog, binding); - - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(firstRequest); - return null; - }); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.commit( - firstRequest, testWorldProof(firstRequest), null); - return null; - }); - assertThat( - fixture.initialAdmissionRepository.read( - NAMESPACE, firstRequest.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); - - CanonicalInitialAdmissionRequest staleRequest = + PreparedAdmission prepared = prepareAdmission(fixture); + CanonicalInitialAdmissionRequest first = initialAdmissionRequest( - catalog, - binding, - "canonical-stale-no-prior-" + catalog.realmId(), + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + CanonicalInitialAdmissionRequest competing = + initialAdmissionRequest( + prepared.catalog(), + prepared.binding(), + prepared.gameInstanceUuid(), + "competing-no-prior-" + prepared.catalog().realmId(), CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, null, uuid(117), uuid(118)); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(staleRequest); - return null; - })) - .isInstanceOf( - GameSessionCanonicalAdmissionPointerRepository.CanonicalClosedPointerConflictException - .class) - .hasMessageContaining("already names this target"); - assertNoAttemptAndNoPending(fixture, staleRequest); + assertHumanProtectionUnavailable(() -> fixture.initialAdmissionRepository.reserve(first)); + assertHumanProtectionUnavailable(() -> fixture.initialAdmissionRepository.reserve(competing)); + assertNoAttemptAndNoPending(fixture, first); + assertNoAttemptAndNoPending(fixture, competing); + assertThat( + fixture.initialAdmissionRepository.read(NAMESPACE, first.initialAdmissionRequestId())) + .isEmpty(); + assertThat( + fixture.initialAdmissionRepository.read( + NAMESPACE, competing.initialAdmissionRequestId())) + .isEmpty(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isZero(); } @Test - void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { + void freshExpectedClosedHumanIntentDeniesBeforeEffects() { Fixture fixture = fixture(); PreparedAdmission preparedAdmission = prepareAdmission(fixture); CanonicalRealmCatalogSnapshot catalog = preparedAdmission.catalog(); @@ -554,230 +310,1187 @@ void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { initialAdmissionRequest( catalog, binding, + preparedAdmission.gameInstanceUuid(), "canonical-expected-closed-v129-" + catalog.realmId(), CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, 129L, uuid(119), uuid(120)); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(unsupportedPriorVersion); - return null; - })) - .isInstanceOf( - GameSessionCanonicalAdmissionPointerRepository - .InvalidCanonicalClosedPointerEvidenceException.class) - .hasMessageContaining("versions do not match"); + String closedBefore = pointerAndAuditProjection(fixture); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.reserve(unsupportedPriorVersion)); assertNoAttemptAndNoPending(fixture, unsupportedPriorVersion); + assertThat(pointerAndAuditProjection(fixture)).isEqualTo(closedBefore); CanonicalInitialAdmissionRequest firstOpenRequest = initialAdmissionRequest( catalog, binding, + preparedAdmission.gameInstanceUuid(), "canonical-expected-closed-v1-" + catalog.realmId(), CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, 1L, uuid(121), uuid(122)); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(firstOpenRequest); - return null; - }); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.reserve(firstOpenRequest)); + assertNoAttemptAndNoPending(fixture, firstOpenRequest); + assertHumanProtectionUnavailable( + () -> + fixture.initialAdmissionRepository.commit( + firstOpenRequest, testWorldProof(firstOpenRequest))); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.abort(firstOpenRequest, "Missing protection")); + assertThat(pointerAndAuditProjection(fixture)).isEqualTo(closedBefore); + assertNoAttemptAndNoPending(fixture, firstOpenRequest); assertThat( fixture.initialAdmissionRepository.read( NAMESPACE, firstOpenRequest.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); - var preparedExpectedClosed = - fixture.pointerRepository.prepareExpectedClosedForRealm( - NAMESPACE, TENANT, catalog.realmId(), 1L, catalog.catalogRevision()); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.commit( - firstOpenRequest, testWorldProof(firstOpenRequest), preparedExpectedClosed); - return null; - }); - CanonicalInitialAdmissionOwnerProof committed = - fixture - .initialAdmissionRepository - .read(NAMESPACE, firstOpenRequest.initialAdmissionRequestId()) - .orElseThrow(); - assertThat(committed.provesCommit()).isTrue(); - assertThat(committed.committedPointerVersion()).isEqualTo(2L); - - CanonicalInitialAdmissionRequest staleRequest = - initialAdmissionRequest( - catalog, - binding, - "canonical-stale-expected-closed-" + catalog.realmId(), - CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, - 1L, - uuid(123), - uuid(124)); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(staleRequest); - return null; - })) - .isInstanceOf( - GameSessionCanonicalAdmissionPointerRepository - .InvalidCanonicalClosedPointerEvidenceException.class); - - assertNoAttemptAndNoPending(fixture, staleRequest); + .isEmpty(); } @Test - void directlyConstructedOwnerServiceRunsMutationsInExplicitPostgresTransactions() { + void directlyConstructedHumanServiceDeniesBeforeReservationOrWorldVerification() { Fixture fixture = fixture(); - IntakeReceipt source = fixture.registerSource(); - CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); - CreateCanonicalLaunchPreparationRequest preparationRequest = - preparationRequest(source, catalog); - AuthoredWorldLaunchDescriptorClient syntheticGameDesign = - syntheticGameDesignClient(preparationRequest, catalog, source); - GameSessionCanonicalLaunchPreparationService preparationService = - new GameSessionCanonicalLaunchPreparationService( - syntheticGameDesign, - fixture.catalogRepository, - fixture.sourceRepository, - fixture.preparationRepository, - fixture.transactionManager, - NAMESPACE); - CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); - CompleteLaunchBindingEvidence completeBinding = - preparationService.readCompleteBinding(preparation); - fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); - CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); - CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); - CanonicalInitialAdmissionWorldVerifier worldVerifier = + PreparedAdmission prepared = prepareAdmission(fixture); + var request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + CanonicalInitialAdmissionWorldVerifier verifier = mock(CanonicalInitialAdmissionWorldVerifier.class); - when(worldVerifier.verify(request)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return worldProof; - }); - DatabaseCanonicalInitialAdmissionService service = + var service = new DatabaseCanonicalInitialAdmissionService( fixture.initialAdmissionRepository, fixture.pointerRepository, - worldVerifier, + verifier, fixture.transactionManager); + assertHumanProtectionUnavailable(() -> service.bind(request)); + assertHumanProtectionUnavailable(() -> service.abort(request, "Missing protection")); + verifyNoInteractions(verifier); + assertNoAttemptAndNoPending(fixture, request); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isZero(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } - CanonicalInitialAdmissionOwnerProof committed = service.bind(request); + @Test + void freshHumanReserveCommitAndAbortRetriesLeaveNoOwnerEffects() { + Fixture fixture = fixture(); + PreparedAdmission prepared = prepareAdmission(fixture); + var request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + for (int retry = 0; retry < 2; retry++) { + assertHumanProtectionUnavailable(() -> fixture.initialAdmissionRepository.reserve(request)); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.abort(request, "World hold expired")); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.commit(request, testWorldProof(request))); + assertNoAttemptAndNoPending(fixture, request); + assertThat( + fixture.initialAdmissionRepository.read( + NAMESPACE, request.initialAdmissionRequestId())) + .isEmpty(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) + .isZero(); + } + } - assertThat(committed.outcome()) - .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); - assertThat(committed.committedPointerVersion()).isEqualTo(1L); - assertThat(committed.auditEventId()).isPositive(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + @Test + void retainedPendingRowsPreserveUnprotectedTerminalWriteGuards() throws Exception { + Fixture fixture = fixture("1005"); + PredecessorAdmission predecessor = preparePre1006Admission(fixture); + PreparedAdmission prepared = predecessor.prepared(); + CanonicalInitialAdmissionRequest request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + reservePre1006Attempt(fixture, predecessor.launch(), request); + migration(fixture, null).migrate(); + migration(fixture, null).validate(); + launchGuardProjection(fixture, true); assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) - .isEqualTo(1); + fixture + .dsl + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history WHERE version = '1011' AND success") + .get(0, Long.class)) + .isEqualTo(1L); assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("gameplay_admission_pointer_event")), - DSL.field(DSL.name("initial_admission_request_id"), String.class) - .eq(request.initialAdmissionRequestId()))) - .isEqualTo(1); + fixture + .dsl + .fetchSingle( + "SELECT convalidated FROM pg_constraint WHERE conrelid = " + + "'game_session_canonical_initial_admission_attempt'::regclass " + + "AND conname = 'chk_gs_initial_admission_terminal_requires_protection'") + .get(0, Boolean.class)) + .isFalse(); + String pendingBefore = attemptProjection(fixture, request); + var terminalColumns = + new HashMap<>( + fixture + .dsl + .fetchSingle( + "SELECT * FROM game_session_canonical_initial_admission_attempt " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + request.initialAdmissionRequestId()) + .intoMap()); + terminalColumns.put("initial_admission_request_id", "unprotected-terminal-insert"); + terminalColumns.put("hold_id", UUID.randomUUID()); + terminalColumns.put("status", "ABORTED"); + terminalColumns.put("abort_reason", "Unprotected terminal constraint fixture"); + terminalColumns.put("abort_proof_digest", "sha256:" + "f".repeat(64)); + terminalColumns.put("terminal_at", terminalColumns.get("updated_at")); + + assertThatThrownBy( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture + .dsl + .insertInto( + DSL.table( + DSL.name("game_session_canonical_initial_admission_attempt"))) + .set(terminalColumns) + .execute())) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> { + assertThat(exception.sqlState()).isEqualTo("23514"); + assertThat(exception) + .hasStackTraceContaining( + "New canonical initial-admission attempts must begin PENDING"); + }); + assertThatThrownBy( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET " + + "status = 'ABORTED', abort_reason = ?, abort_proof_digest = ?, " + + "updated_at = updated_at + INTERVAL '1 second', " + + "terminal_at = updated_at + INTERVAL '1 second' " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + terminalColumns.get("abort_reason"), + terminalColumns.get("abort_proof_digest"), + NAMESPACE, + request.initialAdmissionRequestId()))) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> + assertPostgresConstraintFailure( + exception, + "chk_gs_initial_admission_terminal_requires_protection", + "New canonical initial-admission terminal requires complete retained Account protection evidence")); + // The enabled v44 row trigger runs before declarative CHECK evaluation. INSERTs must begin + // PENDING; terminal UPDATEs reject each incomplete evidence shape with exact attribution. + for (String missing : + List.of( + "account_protection_evidence_version", + "account_protection_fence", + "original_owner_fence")) { + var partial = new HashMap<>(terminalColumns); + putControlledPartialProtection(fixture, partial, missing); + assertThatThrownBy( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture + .dsl + .insertInto( + DSL.table( + DSL.name("game_session_canonical_initial_admission_attempt"))) + .set(partial) + .execute())) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> { + assertThat(exception.sqlState()).isEqualTo("23514"); + assertThat(exception) + .hasStackTraceContaining( + "New canonical initial-admission attempts must begin PENDING"); + }); + assertThatThrownBy( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET status = 'ABORTED', " + + "abort_reason = ?, abort_proof_digest = ?, updated_at = updated_at + INTERVAL '1 second', " + + "terminal_at = updated_at + INTERVAL '1 second', account_protection_evidence_version = ?, " + + "account_protection_id = ?, account_protection_fence = ?, original_owner_attempt_id = ?, " + + "original_owner_mutation_id = ?, original_owner_fence = ?, account_protection_evidence_bytes = ? " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + partial.get("abort_reason"), + partial.get("abort_proof_digest"), + partial.get("account_protection_evidence_version"), + partial.get("account_protection_id"), + partial.get("account_protection_fence"), + partial.get("original_owner_attempt_id"), + partial.get("original_owner_mutation_id"), + partial.get("original_owner_fence"), + partial.get("account_protection_evidence_bytes"), + NAMESPACE, + request.initialAdmissionRequestId()))) + .isInstanceOfSatisfying( + DataAccessException.class, + exception -> + assertPostgresConstraintFailure( + exception, + "chk_gs_initial_admission_terminal_requires_protection", + "New canonical initial-admission terminal requires complete retained Account protection evidence")); + } + assertThat(attemptProjection(fixture, request)).isEqualTo(pendingBefore); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_initial_admission_attempt " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + "unprotected-terminal-insert") + .get(0, Long.class)) + .isZero(); } @Test - void exactDefinitivelyAbortedAttemptCannotBeReopenedByRetry() { - Fixture fixture = fixture(); - IntakeReceipt source = fixture.registerSource(); - CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); - CreateCanonicalLaunchPreparationRequest preparationRequest = - preparationRequest(source, catalog); - AuthoredWorldLaunchDescriptorClient syntheticGameDesign = - syntheticGameDesignClient(preparationRequest, catalog, source); - GameSessionCanonicalLaunchPreparationService preparationService = - new GameSessionCanonicalLaunchPreparationService( - syntheticGameDesign, - fixture.catalogRepository, - fixture.sourceRepository, - fixture.preparationRepository, - fixture.transactionManager, - NAMESPACE); - CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); - CompleteLaunchBindingEvidence completeBinding = - preparationService.readCompleteBinding(preparation); - fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); - CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); - // Synthetic World proof input exercises the GS owner fence; it is not live World evidence. - CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); + void originalProtectionMigrationBytesRemainUnchanged() throws Exception { + assertOriginalMigrationBlob( + "V1005__canonical_launch_exact_catalog_identity.sql", + "368bdf18472699e82f1bccd8b956b62f058b2a12"); + assertOriginalMigrationBlob( + "V1006__canonical_initial_admission_terminal_protection.sql", + "ef093cb7262929d9e962f717220088e378f21e6d"); + } - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(request); - return null; - }); - assertThat( - fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); - int pointerRowsBeforeAbort = - fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer"))); - int auditRowsBeforeAbort = - fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event"))); - assertThat(pointerRowsBeforeAbort).isZero(); - assertThat(auditRowsBeforeAbort).isZero(); + private static void assertOriginalMigrationBlob(String filename, String expected) + throws Exception { + byte[] bytes = Files.readAllBytes(Path.of("src/main/resources/db/migration", filename)); + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + digest.update(("blob " + bytes.length + "\0").getBytes(StandardCharsets.UTF_8)); + assertThat(HexFormat.of().formatHex(digest.digest(bytes))).isEqualTo(expected); + } - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.abort(request, null, "World hold expired"); - return null; - }); + @Test + void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Exception { + for (boolean stagedOriginalHistory : List.of(true, false)) { + for (boolean committed : List.of(true, false)) { + Fixture predecessor = fixture("1005"); + PredecessorAdmission predecessorSources = preparePre1006Admission(predecessor); + PreparedAdmission prepared = predecessorSources.prepared(); + CanonicalInitialAdmissionRequest request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + reservePre1006Attempt(predecessor, predecessorSources.launch(), request); + // This is the real target1005 schema. Current terminal writers remain denied, and current + // typed catalog/terminal reads need columns introduced by1010. Only explicit predecessor + // SQL + // supplies the old row shape here; current owner readback is qualified after the upgrade. + seedPre1006Terminal(predecessor, prepared, predecessorSources.launch(), request, committed); + String originalSources = predecessorSourceProjection(predecessor); + String originalAttempt = predecessorAttemptProjection(predecessor, request); + String originalPointerAndAudit = pointerAndAuditProjection(predecessor); + String originalHistory = migrationHistoryProjection(predecessor, "1005"); + String originalGuard = null; + String otherGuards = null; + String originalFullAttempt = null; + if (stagedOriginalHistory) { + migration(predecessor, "1010").migrate(); + migration(predecessor, "1010").validate(); + originalHistory = migrationHistoryProjection(predecessor, "1010"); + originalGuard = launchGuardProjection(predecessor, false); + otherGuards = otherGuardProjection(predecessor); + originalFullAttempt = attemptProjection(predecessor, request); + assertThat(predecessorAttemptProjection(predecessor, request)).isEqualTo(originalAttempt); + assertThat(pointerAndAuditProjection(predecessor)).isEqualTo(originalPointerAndAudit); + assertThat(predecessorSourceProjection(predecessor)).isEqualTo(originalSources); + } + migration(predecessor, "1011").migrate(); + migration(predecessor, "1011").validate(); + assertThat(migrationHistoryProjection(predecessor, stagedOriginalHistory ? "1010" : "1005")) + .isEqualTo(originalHistory); + assertThat( + predecessor + .dsl + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history WHERE version = '1011' AND success") + .get(0, Long.class)) + .isEqualTo(1L); + if (stagedOriginalHistory) { + assertThat(launchGuardProjection(predecessor, true)).isEqualTo(originalGuard); + assertThat(otherGuardProjection(predecessor)).isEqualTo(otherGuards); + assertThat(attemptProjection(predecessor, request)).isEqualTo(originalFullAttempt); + } else { + launchGuardProjection(predecessor, true); + } + String v1011TriggerIdentity = + predecessor + .dsl + .fetchSingle( + "SELECT oid, tgfoid, tgtype, tgenabled FROM pg_trigger " + + "WHERE tgrelid = 'game_session_canonical_instance_launch'::regclass " + + "AND tgname = 'gs_canonical_instance_launch_complete_catalog_identity'") + .formatJSON(); + String v1011Guard = launchGuardProjection(predecessor, true); + migration(predecessor, null).migrate(); + migration(predecessor, null).validate(); + assertThat( + predecessor + .dsl + .fetchSingle( + "SELECT oid, tgfoid, tgtype, tgenabled FROM pg_trigger " + + "WHERE tgrelid = 'game_session_canonical_instance_launch'::regclass " + + "AND tgname = 'gs_canonical_instance_launch_complete_catalog_identity'") + .formatJSON()) + .isEqualTo(v1011TriggerIdentity); + assertThat(launchGuardProjection(predecessor, true)).isNotEqualTo(v1011Guard); + assertThat( + predecessor + .dsl + .fetchSingle( + "SELECT pg_get_functiondef('require_complete_canonical_launch_catalog_identity()'::regprocedure)") + .get(0, String.class)) + .contains( + "catalog_row.complete_policy_set_evidence IS NULL", + "octet_length(catalog_row.complete_policy_set_evidence) = 0"); + if (stagedOriginalHistory) { + assertThat(otherGuardProjection(predecessor)).isEqualTo(otherGuards); + assertThat(attemptProjection(predecessor, request)).isEqualTo(originalFullAttempt); + } + assertThat( + predecessor + .dsl + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history WHERE version = '1006' AND success") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + predecessor + .dsl + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history WHERE version = '1010' AND success") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + predecessor + .dsl + .fetchSingle( + "SELECT convalidated FROM pg_constraint WHERE conrelid = " + + "'game_session_canonical_initial_admission_attempt'::regclass " + + "AND conname = 'chk_gs_initial_admission_terminal_requires_protection'") + .get(0, Boolean.class)) + .isFalse(); + assertThat(predecessorAttemptProjection(predecessor, request)).isEqualTo(originalAttempt); + assertThat(pointerAndAuditProjection(predecessor)).isEqualTo(originalPointerAndAudit); + assertThat(predecessorSourceProjection(predecessor)).isEqualTo(originalSources); + CanonicalInitialAdmissionOwnerProof retained = + predecessor + .initialAdmissionRepository + .read(NAMESPACE, request.initialAdmissionRequestId()) + .orElseThrow(); + assertThat(retained.outcome()) + .isEqualTo( + committed + ? CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED + : CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); + assertThat(retained.requestDigest()).isEqualTo(request.requestDigest()); + assertThat(retained.holdId()).isEqualTo(request.holdId()); + if (committed) { + assertThat(retained.committedPointerVersion()).isEqualTo(1L); + assertThat(retained.auditEventId()).isPositive(); + } else { + assertThat(retained.provesAbort()).isTrue(); + assertThat(retained.committedPointerVersion()).isNull(); + assertThat(retained.auditEventId()).isNull(); + } + assertThat( + predecessor + .dsl + .fetchSingle( + "SELECT account_protection_evidence_version, account_protection_id, " + + "account_protection_fence, original_owner_attempt_id, original_owner_mutation_id, " + + "original_owner_fence, account_protection_evidence_bytes " + + "FROM game_session_canonical_initial_admission_attempt " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + request.initialAdmissionRequestId()) + .intoArray()) + .containsOnlyNulls(); + assertHumanProtectionUnavailable( + () -> predecessor.initialAdmissionRepository.commit(request, testWorldProof(request))); + assertHumanProtectionUnavailable( + () -> + predecessor.initialAdmissionRepository.abort( + request, "Current Human retry remains unprotected")); + assertThatThrownBy( + () -> + predecessor.transactions.executeWithoutResult( + status -> + predecessor.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET updated_at = updated_at + INTERVAL '1 second' " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + request.initialAdmissionRequestId()))) + .isInstanceOf(DataAccessException.class); + assertThat(predecessorAttemptProjection(predecessor, request)).isEqualTo(originalAttempt); + assertThat(pointerAndAuditProjection(predecessor)).isEqualTo(originalPointerAndAudit); + assertThat(predecessorSourceProjection(predecessor)).isEqualTo(originalSources); + } + } + } - CanonicalInitialAdmissionOwnerProof aborted = + @Test + void malformedProtectedOriginalHistoryFailsCorrectionWithoutChangingRowsGuardsOrHistory() + throws Exception { + Fixture fixture = fixture("1005"); + PredecessorAdmission predecessor = preparePre1006Admission(fixture); + var prepared = predecessor.prepared(); + var request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + reservePre1006Attempt(fixture, predecessor.launch(), request); + seedPre1006Terminal(fixture, prepared, predecessor.launch(), request, false); + migration(fixture, "1010").migrate(); + migration(fixture, "1010").validate(); + var partial = + new HashMap<>( + fixture + .dsl + .fetchSingle( + "SELECT * FROM game_session_canonical_initial_admission_attempt WHERE target_namespace = ? " + + "AND initial_admission_request_id = ?", + NAMESPACE, + request.initialAdmissionRequestId()) + .intoMap()); + partial.put("initial_admission_request_id", "malformed-retained-protected-attempt"); + partial.put("hold_id", UUID.randomUUID()); + partial.put("status", "PENDING"); + partial.put("abort_reason", null); + partial.put("abort_proof_digest", null); + partial.put("terminal_at", null); + putControlledPartialProtection(fixture, partial, "account_protection_fence"); + // Simulate historical corruption admitted by the original SQL's UNKNOWN CHECK branch. + // Only the original v44 protection trigger is isolated for this one pending INSERT; V28, + // source/owner FK, pointer/audit, launch and truncate guards remain active. This is not + // Account-produced terminal protection or a supported owner write. + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_initial_admission_attempt DISABLE TRIGGER " + + "game_session_canonical_initial_admission_v44_terminal_evidence"); + try { + fixture.transactions.executeWithoutResult( + status -> + fixture + .dsl + .insertInto( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt"))) + .set(partial) + .execute()); + } finally { + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_initial_admission_attempt ENABLE TRIGGER " + + "game_session_canonical_initial_admission_v44_terminal_evidence"); + } + String rows = allAttemptProjection(fixture); + String sources = predecessorSourceProjection(fixture); + String pointers = pointerAndAuditProjection(fixture); + String history = migrationHistoryProjection(fixture, "1010"); + String checks = constraintProjection(fixture); + String guards = otherGuardProjection(fixture); + String launchGuard = launchGuardProjection(fixture, false); + assertThatThrownBy(() -> migration(fixture, null).migrate()) + .hasStackTraceContaining("23514") + .hasStackTraceContaining( + "Retained canonical initial-admission protection evidence is malformed or partial"); + assertThat(allAttemptProjection(fixture)).isEqualTo(rows); + assertThat(predecessorSourceProjection(fixture)).isEqualTo(sources); + assertThat(pointerAndAuditProjection(fixture)).isEqualTo(pointers); + assertThat(migrationHistoryProjection(fixture, "1010")).isEqualTo(history); + assertThat( + fixture + .dsl + .fetchSingle("SELECT count(*) FROM flyway_schema_history WHERE version = '1011'") + .get(0, Long.class)) + .isZero(); + assertThat(constraintProjection(fixture)).isEqualTo(checks); + assertThat(otherGuardProjection(fixture)).isEqualTo(guards); + assertThat(launchGuardProjection(fixture, false)).isEqualTo(launchGuard); + migration(fixture, "1010").validate(); + } + + /** + * Deliberately incomplete synthetic bytes exercise SQL null semantics, never Account authority. + */ + private static void putControlledPartialProtection( + Fixture fixture, HashMap row, String missing) { + row.put("account_protection_evidence_version", 1); + row.put("account_protection_id", UUID.randomUUID()); + row.put("account_protection_fence", 1L); + row.put( + "original_owner_attempt_id", fixture - .initialAdmissionRepository - .read(NAMESPACE, request.initialAdmissionRequestId()) - .orElseThrow(); - assertThat(aborted.provesAbort()).isTrue(); - assertThat(aborted.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); - assertThat(aborted.committedPointerVersion()).isNull(); - assertThat(aborted.auditEventId()).isNull(); - assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) - .isEqualTo(pointerRowsBeforeAbort); - assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) - .isEqualTo(auditRowsBeforeAbort); + .dsl + .fetchSingle( + "SELECT owner_attempt_id FROM game_session_start_session_operator_attempt " + + "WHERE target_namespace = ? ORDER BY owner_attempt_id LIMIT 1", + NAMESPACE) + .get(0, UUID.class)); + row.put("original_owner_mutation_id", UUID.randomUUID()); + row.put("original_owner_fence", 1L); + row.put("account_protection_evidence_bytes", new byte[] {1, 2, 3}); + row.put(missing, null); + } - fixture.transactions.execute( + private static String allAttemptProjection(Fixture fixture) { + return fixture + .dsl + .fetchSingle( + "SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(attempt)) " + + "ORDER BY initial_admission_request_id)::TEXT FROM game_session_canonical_initial_admission_attempt attempt") + .get(0, String.class); + } + + private static String constraintProjection(Fixture fixture) { + return fixture + .dsl + .fetchSingle( + "SELECT jsonb_agg(to_jsonb(guard) ORDER BY oid)::TEXT FROM (" + + "SELECT oid, conname, convalidated, pg_get_constraintdef(oid) AS definition FROM pg_constraint " + + "WHERE conrelid IN ('game_session_canonical_initial_admission_attempt'::regclass, " + + "'game_session_canonical_instance_launch'::regclass)) guard") + .get(0, String.class); + } + + /** Old-schema SQL is confined to rows whose current owners require unavailable1010 columns. */ + private static PredecessorAdmission preparePre1006Admission(Fixture fixture) throws Exception { + IntakeReceipt source = fixture.registerSource(); + var association = + Objects.requireNonNull( + fixture.transactions.execute( + status -> + new GameSessionFreshTenantAssociationRepository(fixture.dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source())))); + var request = catalogRequest(source); + var policy = publishedPolicy(source); + // This preparation is compatible with1005 and validates the complete closed policy/source + // evidence through the current owner; only its subsequent SQL writer needs1010 columns. + assertThat(fixture.catalogRepository.prepareInitialPublicProduction(request, policy)) + .isNotNull(); + byte[] policyBytes = RealmPolicyPublishedEvidenceCodec.encode(policy); + var authored = source.source(); + UUID realm = UUID.randomUUID(); + UUID namespace = UUID.randomUUID(); + String baseDigest = + predecessorCatalogFrame( + fixture, + "game-session-canonical-realm-catalog-request/v1", + "1", + request.requestId().toString(), + NAMESPACE, + TENANT.toString(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + Integer.toString(authored.schemaVersion()), + authored.registrationRequestId().toString(), + authored.operationId().toString(), + authored.requestDigest(), + TENANT.toString(), + authored.tenantSlug(), + authored.worldSlug(), + authored.worldDisplayName(), + Long.toString(authored.sourceGameRowId()), + authored.sourceGameTenantKey(), + authored.provenanceKind(), + authored.evidenceDigest(), + request.realmSlug(), + request.realmDisplayName(), + "true", + "true", + "SHARED", + request.characterCreationPolicy(), + "ABSENT", + "ABSENT"); + String catalogDigest = + predecessorCatalogFrame( + fixture, + "game-session-complete-catalog-request/v1", + baseDigest, + HexFormat.of().formatHex(policyBytes)); + String receiptDigest = + predecessorCatalogFrame( + fixture, + "game-session-canonical-realm-catalog-receipt/v1", + "1", + NAMESPACE, + TENANT.toString(), + request.requestId().toString(), + catalogDigest, + realm.toString(), + namespace.toString(), + "1", + source.operationId().toString(), + source.receiptDigest()); + var catalog = + new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT, + authored.tenantSlug(), + authored.worldSlug(), + realm, + request.realmSlug(), + request.realmDisplayName(), + true, + true, + "SHARED", + namespace, + request.characterCreationPolicy(), + 1L, + request.requestId(), + catalogDigest, + receiptDigest, + source); + fixture.transactions.executeWithoutResult( status -> { - fixture.initialAdmissionRepository.reserve(request); - return null; + fixture.dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace (tenant_id, " + + "playable_state_namespace_id, canonical_tenant_id, target_namespace, " + + "source_intake_operation_id, source_intake_schema_version, source_intake_request_id, " + + "source_intake_request_digest, source_intake_receipt_digest, source_schema_version, " + + "source_registration_request_id, source_operation_id, source_request_digest, " + + "source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest) " + + "VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + namespace, + TENANT, + NAMESPACE, + source.operationId(), + source.intakeRequestId(), + source.requestDigest(), + source.receiptDigest(), + authored.schemaVersion(), + authored.registrationRequestId(), + authored.operationId(), + authored.requestDigest(), + authored.sourceGameRowId(), + authored.sourceGameTenantKey(), + authored.provenanceKind(), + authored.evidenceDigest()); + fixture.dsl.execute( + "INSERT INTO game_session_canonical_realm_catalog (target_namespace, canonical_tenant_id, " + + "tenant_slug, world_slug, realm_id, realm_slug, realm_display_name, visible, " + + "public_production, state_scope, playable_state_namespace_id, character_creation_policy, " + + "catalog_revision, creation_request_id, request_digest, receipt_digest, " + + "source_intake_operation_id, source_intake_schema_version, source_intake_request_id, " + + "source_intake_request_digest, source_intake_receipt_digest, source_schema_version, " + + "source_registration_request_id, source_operation_id, source_request_digest, " + + "source_world_display_name, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, complete_policy_set_evidence) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, 1, ?, ?, ?, ?, 1, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + NAMESPACE, + TENANT, + authored.tenantSlug(), + authored.worldSlug(), + realm, + request.realmSlug(), + request.realmDisplayName(), + namespace, + request.characterCreationPolicy(), + request.requestId(), + catalogDigest, + receiptDigest, + source.operationId(), + source.intakeRequestId(), + source.requestDigest(), + source.receiptDigest(), + authored.schemaVersion(), + authored.registrationRequestId(), + authored.operationId(), + authored.requestDigest(), + authored.worldDisplayName(), + authored.sourceGameRowId(), + authored.sourceGameTenantKey(), + authored.provenanceKind(), + authored.evidenceDigest(), + policyBytes); }); - fixture.transactions.execute( + var preparationRequest = preparationRequest(source, catalog); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + preparationRequest.descriptorRequest(catalog, authored), + "launch-descriptor-canonical-admission", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "published-bundle-73", + false, + null); + var binding = CanonicalHumanPublicationOwnerTestFixtures.completeBinding(descriptor, policy); + var tuple = + CanonicalHumanPublicationOwnerTestFixtures.tuple( + NAMESPACE, + TENANT, + ACTOR, + descriptor.gameTemplateId(), + descriptor.controlPlaneRequestId()); + CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( + fixture.dsl, fixture.transactions, tuple, authored, policy, binding); + UUID instanceUuid = UUID.randomUUID(); + String bindingJson = + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(binding); + long tenantId = association.legacyGameSessionTenantId(); + var sourceIdentity = association.sourceEvidence(); + Long instanceId = + fixture.transactions.execute( + status -> { + long allocated = + fixture + .dsl + .fetchSingle( + "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_uuid, status, " + + "row_version, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "version_state_epoch, generation_config_revision, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref, " + + "game_instance_uuid) VALUES (?, ?, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "RETURNING id", + tenantId, + Long.toString(descriptor.versionId()), + ACTOR, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.versionStateEpoch(), + descriptor.generationConfigRevision(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + descriptor.publishedReleaseBundleRef(), + instanceUuid) + .get("id", Long.class); + fixture.dsl.execute( + "INSERT INTO game_session_canonical_instance_launch (target_namespace, control_plane_request_id, " + + "game_session_tenant_id, canonical_tenant_id, tenant_association_operation_id, " + + "tenant_association_request_id, tenant_source_schema_version, tenant_source_target_namespace, " + + "tenant_source_request_id, tenant_source_canonical_tenant_id, tenant_source_game_row_id, " + + "tenant_source_game_tenant_key, tenant_source_provenance_kind, tenant_association_kind, " + + "game_instance_id, game_instance_uuid, canonical_realm_id, world_slug, " + + "playable_state_namespace_id, playable_state_scope, public_production, " + + "captured_starting_row_version, game_template_id, launch_descriptor_id, version_id, " + + "release_bundle_id, generation_config_revision, version_state_epoch, complete_launch_binding_evidence, " + + "original_start_session_tuple, catalog_creation_request_id, catalog_revision, " + + "catalog_source_intake_operation_id, catalog_source_intake_request_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, " + + "'SHARED', TRUE, 0, ?, ?, ?, ?, ?, ?, CAST(? AS JSONB), ?, ?, 1, ?, ?)", + NAMESPACE, + tuple.controlPlaneRequestId(), + tenantId, + TENANT, + ASSOCIATION_OPERATION, + sourceIdentity.requestId(), + sourceIdentity.schemaVersion(), + NAMESPACE, + sourceIdentity.requestId(), + TENANT, + sourceIdentity.sourceGameRowId(), + sourceIdentity.sourceGameTenantKey(), + sourceIdentity.provenanceKind(), + allocated, + instanceUuid, + realm, + authored.worldSlug(), + namespace, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + bindingJson, + tuple.canonicalBytes(), + CATALOG_REQUEST, + source.operationId(), + source.intakeRequestId()); + fixture.dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + tenantId, + allocated); + return allocated; + }); + var captured = + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + tenantId, + ASSOCIATION_OPERATION, + TENANT, + instanceUuid, + authored.worldSlug(), + namespace, + RealmEntryPolicy.StateScope.SHARED, + true, + tuple.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + 0L, + binding, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING, + 0L); + var launch = + new CanonicalInitialAdmissionLaunchTarget( + captured, realm, Objects.requireNonNull(instanceId), descriptor.versionId()); + return new PredecessorAdmission(new PreparedAdmission(catalog, binding, instanceUuid), launch); + } + + private static void reservePre1006Attempt( + Fixture fixture, + CanonicalInitialAdmissionLaunchTarget launch, + CanonicalInitialAdmissionRequest request) { + fixture.transactions.executeWithoutResult( + status -> + fixture.dsl.execute( + "INSERT INTO game_session_canonical_initial_admission_attempt (target_namespace, " + + "initial_admission_request_id, request_digest, canonical_tenant_id, world_slug, realm_id, " + + "playable_state_namespace_id, playable_state_scope, canonical_game_instance_id, " + + "game_session_tenant_id, game_instance_id, canonical_version_id, runtime_version_id, " + + "expected_catalog_revision, origin_kind, expected_prior_pointer_version, active_lifecycle_epoch, " + + "hold_id, hold_fence, hold_binding_digest, status, created_at, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', " + + "clock_timestamp(), clock_timestamp())", + NAMESPACE, + request.initialAdmissionRequestId(), + request.requestDigest(), + TENANT, + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + launch.association().gameSessionTenantId(), + launch.gameInstanceId(), + request.canonicalVersionId(), + launch.runtimeVersionId(), + request.expectedCatalogRevision(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest())); + } + + /** Independent SQL encoding of the predecessor catalog's decimal-length UTF-8 framing. */ + private static String predecessorCatalogFrame(Fixture fixture, String... fields) { + return fixture + .dsl + .fetchSingle( + "SELECT 'sha256:' || encode(sha256(string_agg(convert_to(octet_length(convert_to(field, 'UTF8'))::TEXT " + + "|| ':', 'UTF8') || convert_to(field, 'UTF8'), ''::BYTEA ORDER BY ordinal)), 'hex') AS digest " + + "FROM unnest(?::TEXT[]) WITH ORDINALITY framed(field, ordinal)", + (Object) fields) + .get("digest", String.class); + } + + private record PredecessorAdmission( + PreparedAdmission prepared, CanonicalInitialAdmissionLaunchTarget launch) {} + + /** Entire original source, namespace, catalog, runtime, launch and original-pin heap evidence. */ + private static String predecessorSourceProjection(Fixture fixture) { + return fixture + .dsl + .fetchSingle( + "SELECT jsonb_build_array(" + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY operation_id) FROM game_session_authored_world_source_intake source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY canonical_tenant_id) FROM game_session_authored_world_tenant_source_binding source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY association_operation_id) FROM game_session_fresh_tenant_association source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY canonical_tenant_id) FROM game_session_tenant_canonical_claim source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY to_jsonb(source)::TEXT) FROM game_session_tenant_scope_reservation source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY canonical_tenant_id) FROM gameplay_tenant_shared_playable_state_namespace source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source) - ARRAY['fixture_policy_request_bytes', 'fixture_policy_seal_operation_id', 'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest']) ORDER BY realm_id) FROM game_session_canonical_realm_catalog source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY id) FROM game_instances source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source) - ARRAY['fixture_policy_request_bytes', 'fixture_policy_seal_operation_id', 'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest']) ORDER BY game_instance_id) FROM game_session_canonical_instance_launch source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY owner_attempt_id) FROM game_session_start_session_operator_attempt source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY owner_attempt_id) FROM game_session_start_session_template_association_pin source)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(source)) ORDER BY owner_attempt_id) FROM game_session_start_session_launch_descriptor_pin source))::TEXT AS projection") + .get("projection", String.class); + } + + private static void seedPre1006Terminal( + Fixture fixture, + PreparedAdmission prepared, + CanonicalInitialAdmissionLaunchTarget launch, + CanonicalInitialAdmissionRequest request, + boolean committed) { + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT count(*) FROM information_schema.columns WHERE table_schema = current_schema() " + + "AND table_name = 'game_session_canonical_initial_admission_attempt' " + + "AND column_name = 'account_protection_evidence_bytes'") + .get(0, Long.class)) + .isZero(); + Instant terminalAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + fixture.transactions.executeWithoutResult( status -> { - fixture.initialAdmissionRepository.commit(request, worldProof, null); - return null; + Long pointerId = null; + Long auditId = null; + String reason = "Explicit pre1006 owner abort fixture"; + if (committed) { + auditId = + new GameplayAdmissionPointerEventRepository(fixture.dsl) + .appendCanonicalInitialAdmissionOpen( + request, + prepared.catalog(), + launch, + 1L, + prepared.catalog().catalogRevision(), + terminalAt); + pointerId = + fixture + .dsl + .fetchSingle( + "INSERT INTO gameplay_admission_pointer (world_slug, realm_slug, world_display_name, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, " + + "last_updated_by, last_update_reason, created_at, updated_at, " + + "public_production_realm, catalog_revision, realm_id, playable_state_namespace_id, " + + "representation_version, target_namespace, canonical_tenant_id, admission_state, " + + "canonical_game_instance_id, canonical_version_id, runtime_version_id, " + + "initial_admission_request_id, initial_admission_request_digest, " + + "initial_admission_origin_kind, initial_admission_prior_pointer_version, " + + "initial_admission_active_epoch, initial_admission_hold_id, " + + "initial_admission_hold_fence, initial_admission_hold_binding_digest) " + + "SELECT world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, occurred_at, " + + "occurred_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, " + + "canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " + + "initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_hold_binding_digest FROM gameplay_admission_pointer_event " + + "WHERE id = ? RETURNING id", + auditId) + .get("id", Long.class); + } + String proof = + predecessorTerminalProofDigest( + fixture, request, committed, auditId, reason, terminalAt); + if (committed) { + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET " + + "status = 'COMMITTED', pointer_id = ?, pointer_version = 1, audit_event_id = ?, " + + "commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " + + "terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + pointerId, + auditId, + proof, + terminalAt.atOffset(ZoneOffset.UTC), + terminalAt.atOffset(ZoneOffset.UTC), + NAMESPACE, + request.initialAdmissionRequestId()); + } else { + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET " + + "status = 'ABORTED', abort_reason = ?, abort_proof_digest = ?, " + + "updated_at = CAST(? AS TIMESTAMPTZ), terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + reason, + proof, + terminalAt.atOffset(ZoneOffset.UTC), + terminalAt.atOffset(ZoneOffset.UTC), + NAMESPACE, + request.initialAdmissionRequestId()); + } }); + } - CanonicalInitialAdmissionOwnerProof afterRetry = - fixture - .initialAdmissionRepository - .read(NAMESPACE, request.initialAdmissionRequestId()) - .orElseThrow(); - assertThat(afterRetry).isEqualTo(aborted); + /** Independent PostgreSQL encoding of the retained v1 length-prefixed terminal frame. */ + private static String predecessorTerminalProofDigest( + Fixture fixture, + CanonicalInitialAdmissionRequest request, + boolean committed, + Long auditId, + String reason, + Instant terminalAt) { + return fixture + .dsl + .fetchSingle( + "SELECT 'sha256:' || encode(sha256(string_agg(int4send(octet_length(convert_to(field, 'UTF8'))) " + + "|| convert_to(field, 'UTF8'), ''::BYTEA ORDER BY ordinal)), 'hex') AS proof " + + "FROM game_session_canonical_initial_admission_attempt attempt " + + "CROSS JOIN LATERAL unnest(ARRAY[?::TEXT, request_digest, " + + "initial_admission_request_id, target_namespace, canonical_tenant_id::TEXT, world_slug, " + + "realm_id::TEXT, playable_state_namespace_id::TEXT, playable_state_scope, " + + "canonical_game_instance_id::TEXT, canonical_version_id::TEXT, runtime_version_id::TEXT, " + + "active_lifecycle_epoch::TEXT, expected_catalog_revision::TEXT, origin_kind, " + + "COALESCE(expected_prior_pointer_version::TEXT, ''), hold_id::TEXT, hold_fence::TEXT, " + + "hold_binding_digest] || CASE WHEN ? THEN ARRAY['1', ?::TEXT] ELSE ARRAY[?::TEXT] END " + + "|| ARRAY['', '', '', ?::TEXT]) WITH ORDINALITY fields(field, ordinal) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + committed + ? "gs-canonical-initial-admission-commit-proof/v1" + : "gs-canonical-initial-admission-abort-proof/v1", + committed, + auditId == null ? null : auditId.toString(), + reason, + terminalAt.toString(), + NAMESPACE, + request.initialAdmissionRequestId()) + .get("proof", String.class); + } + + /** Every pre1006 attempt column, including byte values, and the original heap xmin. */ + private static String predecessorAttemptProjection( + Fixture fixture, CanonicalInitialAdmissionRequest request) { + return fixture + .dsl + .fetchSingle( + "SELECT jsonb_build_array(xmin::TEXT, to_jsonb(attempt) - ARRAY[" + + "'account_protection_evidence_version', 'account_protection_id', " + + "'account_protection_fence', 'original_owner_attempt_id', 'original_owner_mutation_id', " + + "'original_owner_fence', 'account_protection_evidence_bytes'])::TEXT AS projection " + + "FROM game_session_canonical_initial_admission_attempt attempt " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + request.initialAdmissionRequestId()) + .get("projection", String.class); + } + + private static void assertHumanProtectionUnavailable(Runnable operation) { + assertThatThrownBy(operation::run) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); + } + + private static void assertPostgresConstraintFailure( + Throwable failure, String expectedConstraint, String expectedMessage) { + PSQLException postgresFailure = postgresException(failure); + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat(postgresFailure.getServerErrorMessage()).isNotNull(); + assertThat(postgresFailure.getServerErrorMessage().getConstraint()) + .isEqualTo(expectedConstraint); + assertThat(postgresFailure.getServerErrorMessage().getMessage()).isEqualTo(expectedMessage); + } + + private static PSQLException postgresException(Throwable failure) { + Throwable current = failure; + for (int depth = 0; current != null && depth < 8; depth++, current = current.getCause()) { + if (current instanceof PSQLException postgresFailure) { + return postgresFailure; + } + } + throw new AssertionError("PostgreSQL exception was not present in the cause chain", failure); + } + + private static String attemptProjection( + Fixture fixture, CanonicalInitialAdmissionRequest request) { + return fixture + .dsl + .fetchSingle( + "SELECT xmin::text || '/' || to_jsonb(attempt)::text AS projection " + + "FROM game_session_canonical_initial_admission_attempt attempt WHERE target_namespace = ? " + + "AND initial_admission_request_id = ?", + request.targetNamespace(), + request.initialAdmissionRequestId()) + .get("projection", String.class); + } + + private static String pointerAndAuditProjection(Fixture fixture) { + return fixture + .dsl + .fetchSingle( + "SELECT jsonb_build_array(" + + "(SELECT jsonb_agg(jsonb_build_array(xmin::text, to_jsonb(pointer)) ORDER BY id) FROM gameplay_admission_pointer pointer)," + + "(SELECT jsonb_agg(jsonb_build_array(xmin::text, to_jsonb(event)) ORDER BY id) FROM gameplay_admission_pointer_event event))::text AS projection") + .get("projection", String.class); + } + + private static Flyway migration(Fixture fixture, String target) { + String schema = fixture.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + var configuration = + Flyway.configure() + .dataSource(Objects.requireNonNull(fixture.transactionManager.getDataSource())) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (target != null) { + configuration.target(MigrationVersion.fromVersion(target)); + } + return configuration.load(); + } + + private static String migrationHistoryProjection(Fixture fixture, String frontier) { + return fixture + .dsl + .fetchSingle( + "SELECT jsonb_agg(to_jsonb(history) ORDER BY installed_rank)::TEXT FROM flyway_schema_history history " + + "WHERE version::NUMERIC <= ?::NUMERIC", + frontier) + .get(0, String.class); + } + + /** Rename must preserve the actual trigger OID, function OID/body and INSERT event mask. */ + private static String launchGuardProjection(Fixture fixture, boolean corrected) { + String name = + corrected + ? "gs_canonical_instance_launch_complete_catalog_identity" + : "game_session_canonical_instance_launch_complete_catalog_identit"; + var guards = + fixture.dsl.fetch( + "SELECT trigger.oid::TEXT, tgfoid::TEXT, tgtype, tgenabled::TEXT, pg_get_functiondef(tgfoid) " + + "FROM pg_trigger trigger WHERE tgrelid = 'game_session_canonical_instance_launch'::regclass " + + "AND NOT tgisinternal AND tgfoid = 'require_complete_canonical_launch_catalog_identity()'::regprocedure"); + assertThat(guards).hasSize(1); + assertThat(guards.get(0).get("tgtype", Short.class)).isEqualTo((short) 7); + assertThat(guards.get(0).get("tgenabled", String.class)).isEqualTo("O"); + assertThat(guards.get(0).get(4, String.class)) + .contains("fixture_policy", "complete_policy_set_evidence"); assertThat( - fixture.dsl.fetchCount( - DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")))) - .isEqualTo(1); - assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) - .isEqualTo(pointerRowsBeforeAbort); - assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer_event")))) - .isEqualTo(auditRowsBeforeAbort); + fixture + .dsl + .fetchSingle( + "SELECT tgname::TEXT FROM pg_trigger WHERE oid = ?::OID", + guards.get(0).get(0, String.class)) + .get(0, String.class)) + .isEqualTo(name); + return guards.get(0).formatJSON(); + } + + private static String otherGuardProjection(Fixture fixture) { + return fixture + .dsl + .fetchSingle( + "SELECT jsonb_agg(to_jsonb(guard) ORDER BY guard.oid)::TEXT FROM (" + + "SELECT oid, tgrelid, tgname, tgfoid, tgtype, tgenabled FROM pg_trigger " + + "WHERE tgrelid IN ('game_session_canonical_instance_launch'::regclass, " + + "'game_session_canonical_initial_admission_attempt'::regclass, " + + "'game_session_canonical_initial_admission_intent'::regclass) " + + "AND tgfoid <> 'require_complete_canonical_launch_catalog_identity()'::regprocedure) guard") + .get(0, String.class); } private Fixture fixture() { + return fixture(null); + } + + private Fixture fixture(String targetVersion) { String schema = "gs_canonical_admission_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); @@ -785,14 +1498,17 @@ private Fixture fixture() { dataSource.setUsername(postgres.getUsername()); dataSource.setPassword(postgres.getPassword()); dataSource.setSchema(schema); - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load() - .migrate(); + var migration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (targetVersion != null) { + migration.target(MigrationVersion.fromVersion(targetVersion)); + } + migration.load().migrate(); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); @@ -811,8 +1527,7 @@ private Fixture fixture() { CanonicalGameInstanceLaunchAssociationRepository launchRepository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); CanonicalInitialAdmissionRepository initialAdmissionRepository = - new CanonicalInitialAdmissionRepository( - dsl, catalogRepository, pointerRepository, launchRepository, eventRepository); + new CanonicalInitialAdmissionRepository(dsl, catalogRepository, pointerRepository); return new Fixture( dsl, transactionManager, @@ -882,8 +1597,8 @@ private static CreateCanonicalLaunchPreparationRequest preparationRequest( null, false, null, - false, - null); + true, + "{}"); } private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( @@ -905,7 +1620,9 @@ private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( "published-bundle-73", false, null); - CompleteLaunchBindingEvidence binding = completeBinding(descriptor); + CompleteLaunchBindingEvidence binding = + CanonicalHumanPublicationOwnerTestFixtures.completeBinding( + descriptor, publishedPolicy(source)); when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) .thenReturn(descriptor); when(client.get(any(GetRequest.class))).thenReturn(descriptor); @@ -913,54 +1630,27 @@ private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( return client; } - private static CompleteLaunchBindingEvidence completeBinding( - AuthoredWorldLaunchDescriptorEvidence descriptor) { - String commitId = "publish-commit-canonical-admission"; - List participants = - AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - commitId, - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? digest("d") : null)) - .toList(); - AuthoredWorldReleaseAttestationEvidence attestation = - AuthoredWorldReleaseAttestationEvidence.create( - descriptor.targetNamespace(), - descriptor.resultDigest(), - descriptor.canonicalTenantId(), - CANONICAL_VERSION, - descriptor.worldSlug(), - descriptor.authoredWorldSourceOperationId(), - descriptor.authoredWorldSourceEvidenceDigest(), - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - "publish-canonical-admission", - commitId, - participants, - digest("b"), - 1, - List.of(), - List.of(), - List.of(), - descriptor.generationConfigRevision()); - return new CompleteLaunchBindingEvidence(descriptor, attestation); + private static net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence.PublishedSet + publishedPolicy(IntakeReceipt source) { + return CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + catalogRequest(source), + source.source(), + CANONICAL_VERSION, + 72L, + "publish-canonical-admission", + "published-bundle-73", + "generation-1", + 3L); } private static CanonicalInitialAdmissionRequest initialAdmissionRequest( - CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding) { + CanonicalRealmCatalogSnapshot catalog, + CompleteLaunchBindingEvidence binding, + UUID gameInstanceUuid) { return initialAdmissionRequest( catalog, binding, + gameInstanceUuid, "canonical-first-open-" + catalog.realmId(), CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, null, @@ -971,6 +1661,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( private static CanonicalInitialAdmissionRequest initialAdmissionRequest( CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding, + UUID gameInstanceUuid, String requestId, CanonicalInitialAdmissionRequest.OriginKind origin, Long expectedPriorPointerVersion, @@ -986,7 +1677,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( catalog.realmId(), catalog.playableStateNamespaceId(), "SHARED", - GAME_INSTANCE_UUID, + gameInstanceUuid, canonicalVersionId, activeEpoch, catalog.catalogRevision(), @@ -1000,7 +1691,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( catalog.realmId(), catalog.playableStateNamespaceId(), "SHARED", - GAME_INSTANCE_UUID, + gameInstanceUuid, canonicalVersionId, activeEpoch, catalog.catalogRevision(), @@ -1046,7 +1737,9 @@ private static PreparedAdmission prepareAdmission(Fixture fixture) { CanonicalLaunchPreparationSnapshot preparation = preparationService.prepare(preparationRequest); CompleteLaunchBindingEvidence binding = preparationService.readCompleteBinding(preparation); fixture.createTestOnlyFreshMappingAndRunningLaunch(source, binding); - return new PreparedAdmission(catalog, binding); + UUID allocatedInstanceUuid = + fixture.launchRepository.read(CONTROL_PLANE_REQUEST_ID).orElseThrow().gameInstanceUuid(); + return new PreparedAdmission(catalog, binding, allocatedInstanceUuid); } private static CanonicalInitialAdmissionWorldProof testWorldProof( @@ -1083,7 +1776,7 @@ private static CreateCanonicalRealmCatalogRequest catalogRequest(IntakeReceipt s true, true, "SHARED", - "explicit-policy-v1", + "PRESEEDED_ONLY", null, null); } @@ -1097,7 +1790,9 @@ private static UUID uuid(int value) { } private record PreparedAdmission( - CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding) {} + CanonicalRealmCatalogSnapshot catalog, + CompleteLaunchBindingEvidence binding, + UUID gameInstanceUuid) {} private record Fixture( DSLContext dsl, @@ -1115,7 +1810,18 @@ IntakeReceipt registerSource() { } CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { - var prepared = catalogRepository.prepareInitialPublicProduction(catalogRequest(source)); + transactions.execute( + status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source()))); + var prepared = + catalogRepository.prepareInitialPublicProduction( + catalogRequest(source), publishedPolicy(source)); return Objects.requireNonNull( transactions.execute( status -> catalogRepository.createInitialPublicProduction(prepared))); @@ -1123,87 +1829,42 @@ CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { FreshGameSessionTenantAssociation createTestOnlyFreshMappingAndRunningLaunch( IntakeReceipt source, CompleteLaunchBindingEvidence binding) { - RuntimeTenantIdentityEvidence sourceIdentity = - new RuntimeTenantIdentityEvidence( - 1, + var tuple = + CanonicalHumanPublicationOwnerTestFixtures.tuple( NAMESPACE, - source.source().registrationRequestId(), TENANT, - source.source().sourceGameRowId(), - source.source().sourceGameTenantKey(), - source.source().provenanceKind()); - FreshGameSessionTenantAssociation association = + ACTOR, + binding.descriptor().gameTemplateId(), + binding.descriptor().controlPlaneRequestId()); + CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( + dsl, transactions, tuple, source.source(), publishedPolicy(source), binding); + return Objects.requireNonNull( transactions.execute( status -> { - Record reservation = - Objects.requireNonNull( - dsl.fetchOne( - "INSERT INTO game_session_tenant_scope_reservation " - + "(reservation_kind) VALUES ('FRESH_SOURCE_BOUND') " - + "RETURNING game_session_tenant_id")); - long allocatedTenantId = reservation.get("game_session_tenant_id", Long.class); - FreshGameSessionTenantAssociation allocatedAssociation = - new FreshGameSessionTenantAssociation( - ASSOCIATION_OPERATION, allocatedTenantId, sourceIdentity); + var association = + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source())); + var starting = + new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE) + .createStarting( + association, + binding, + ACTOR, + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple); dsl.execute( - "INSERT INTO game_session_tenant_canonical_claim " - + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, " - + "association_kind, reservation_kind, association_operation_id, " - + "association_request_id) " - + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", - NAMESPACE, - TENANT, - allocatedTenantId, - ASSOCIATION_OPERATION, - source.source().registrationRequestId()); - dsl.execute( - "INSERT INTO game_session_fresh_tenant_association " - + "(association_operation_id, target_namespace, association_request_id, " - + "source_schema_version, source_target_namespace, source_request_id, " - + "source_canonical_tenant_id, canonical_tenant_id, " - + "legacy_game_session_tenant_id, source_game_row_id, " - + "source_game_tenant_key, provenance_kind, association_kind) " - + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', " - + "'FRESH_SOURCE_BOUND')", - ASSOCIATION_OPERATION, - NAMESPACE, - source.source().registrationRequestId(), - NAMESPACE, - source.source().registrationRequestId(), - TENANT, - TENANT, - allocatedTenantId, - source.source().sourceGameRowId(), - source.source().sourceGameTenantKey()); - Record instance = - Objects.requireNonNull( - dsl.fetchOne( - "INSERT INTO game_instances " - + "(tenant_id, runtime_version, game_template_id, " - + "launch_descriptor_id, version_id, release_bundle_id, " - + "generation_config_revision, version_state_epoch, " - + "owner_account_id, status, row_version, game_instance_uuid, " - + "run_owned_start_request_id, run_owned_start_request_digest, " - + "run_owned_start_published_release_bundle_ref, " - + "run_owned_start_preparing_epoch, run_owned_start_active_epoch) " - + "VALUES (?, '72', 404, ?, 72, 73, 'generation-1', 3, 77, " - + "'STARTING', 1, ?, ?, ?, ?, 1, 2) RETURNING id", - allocatedTenantId, - binding.descriptor().launchDescriptorId(), - GAME_INSTANCE_UUID, - CONTROL_PLANE_REQUEST_ID, - "c".repeat(64), - binding.descriptor().publishedReleaseBundleRef())); - long gameInstanceId = instance.get("id", Long.class); - launchRepository.capture(allocatedAssociation, gameInstanceId, binding); - dsl.execute( - "UPDATE game_instances SET status = 'RUNNING' " - + "WHERE tenant_id = ? AND id = ?", - allocatedTenantId, - gameInstanceId); - return allocatedAssociation; - }); - return Objects.requireNonNull(association, "test fixture tenant association"); + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + association.legacyGameSessionTenantId(), + starting.gameInstanceId()); + return association; + }), + "Controlled actual GS tenant association"); } } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index eb0921758b..86ed6859e5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -20,6 +20,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.CatalogConflictException; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.PreparedInitialPublicProduction; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -60,7 +61,7 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric Fixture fixture = fixture(true); IntakeReceipt source = fixture.register(tenant(1), "new-world", "Fresh World", "NEW_GAME_ROW"); CreateCanonicalRealmCatalogRequest request = - request(source, uuid(20), "public-realm-east", "Public Realm", "owner-policy-v2", "SHARED"); + request(source, uuid(20), "public-realm-east", "Public Realm", "PRESEEDED_ONLY", "SHARED"); String retainedNamespaceXmin = requiredRecord( fixture.dsl, @@ -198,7 +199,7 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric uuid(21), "another-realm", "Another Realm", - "owner-mode", + "PRESEEDED_ONLY", "SHARED"))) .isInstanceOf(CatalogConflictException.class) .hasMessageContaining("already has a public-production"); @@ -254,15 +255,125 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric .contains(created); } + @Test + void historicalCatalogAndAssociationRemainUnchangedWithoutPoisoningFreshDiscovery() { + Fixture fixture = fixture(false, MigrationVersion.fromVersion("40")); + IntakeReceipt historicalSource = + fixture.register(tenant(40), "historical-world", "Historical World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest historicalRequest = + request( + historicalSource, + uuid(1040), + "historical-realm", + "Historical Realm", + "ALLOW_NEW", + "ISOLATED"); + insertHistoricalFreshAssociation(fixture, historicalSource); + insertCatalogRow(fixture, historicalSource, historicalRequest, java.util.Map.of()); + Record catalogBefore = retainedCatalogState(fixture, historicalRequest.requestId()); + Record associationBefore = retainedAssociationState(fixture, tenant(40)); + + fixture.migrateToLatest(); + + assertThat(retainedCatalogState(fixture, historicalRequest.requestId())) + .isEqualTo(catalogBefore); + assertThat(retainedAssociationState(fixture, tenant(40))).isEqualTo(associationBefore); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT complete_policy_set_evidence IS NULL AND fixture_policy_request_bytes IS NULL " + + "AND fixture_policy_seal_operation_id IS NULL AND fixture_policy_seal_request_digest IS NULL " + + "AND fixture_policy_seal_evidence_digest IS NULL AS historical " + + "FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + historicalRequest.requestId()) + .get("historical", Boolean.class)) + .isTrue(); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT complete_source_evidence FROM game_session_fresh_tenant_association WHERE canonical_tenant_id = ?", + tenant(40)) + .get("complete_source_evidence")) + .isNull(); + assertThat(fixture.catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)).isEmpty(); + assertThatThrownBy( + () -> fixture.catalogRepository.readByRequest(NAMESPACE, historicalRequest.requestId())) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("Exactly one complete catalog policy provenance required"); + assertThatThrownBy( + () -> + fixture.catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, tenant(40))) + .isInstanceOf(InvalidCatalogEvidenceException.class); + + IntakeReceipt freshSource = + fixture.register(tenant(41), "fresh-world", "Fresh World", "NEW_GAME_ROW"); + CanonicalRealmCatalogSnapshot fresh = + fixture.create( + request( + freshSource, uuid(1041), "fresh-realm", "Fresh Realm", "PRESEEDED_ONLY", "SHARED")); + assertThat(fixture.catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .containsExactly(fresh); + assertThat(retainedCatalogState(fixture, historicalRequest.requestId())) + .isEqualTo(catalogBefore); + assertThat(retainedAssociationState(fixture, tenant(40))).isEqualTo(associationBefore); + } + + @Test + void discoveryStillRejectsMalformedEvidenceAndDatabaseRejectsPartialOrBothProvenances() { + Fixture fixture = fixture(false); + IntakeReceipt source = + fixture.register(tenant(42), "invalid-world", "Invalid World", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(1042), "invalid-realm", "Invalid Realm", "ALLOW_NEW", "ISOLATED"); + for (String column : + java.util.List.of( + "fixture_policy_request_bytes", "fixture_policy_seal_operation_id", + "fixture_policy_seal_request_digest", "fixture_policy_seal_evidence_digest")) { + Object value = + column.endsWith("bytes") + ? new byte[] {1} + : column.endsWith("operation_id") ? uuid(1043) : "sha256:" + "a".repeat(64); + assertThatThrownBy( + () -> insertCatalogRow(fixture, source, request, java.util.Map.of(column, value))) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy( + () -> + insertCatalogRow( + fixture, + source, + request, + java.util.Map.of( + "complete_policy_set_evidence", + new byte[] {1}, + "fixture_policy_request_bytes", + new byte[] {1}, + "fixture_policy_seal_operation_id", + uuid(1043), + "fixture_policy_seal_request_digest", + "sha256:" + "a".repeat(64), + "fixture_policy_seal_evidence_digest", + "sha256:" + "b".repeat(64)))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> insertCatalogRow(fixture, source, request, java.util.Map.of())) + .isInstanceOf(DataAccessException.class); + + // The insert guard checks presence; authoritative readback validates the actual policy bytes. + insertCatalogRow( + fixture, source, request, java.util.Map.of("complete_policy_set_evidence", new byte[] {1})); + assertThatThrownBy( + () -> fixture.catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .isInstanceOf(InvalidCatalogEvidenceException.class); + } + @Test void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenance() { Fixture fixture = fixture(false); IntakeReceipt source = fixture.register(tenant(2), "world-two", "World Two", "NEW_GAME_ROW"); CreateCanonicalRealmCatalogRequest request = - request(source, uuid(30), "realm", "Realm", "owner-mode", "SHARED"); + request(source, uuid(30), "realm", "Realm", "PRESEEDED_ONLY", "SHARED"); - PreparedInitialPublicProduction prepared = - fixture.catalogRepository.prepareInitialPublicProduction(request); + PreparedInitialPublicProduction prepared = fixture.prepare(request); assertThatThrownBy(() -> fixture.catalogRepository.createInitialPublicProduction(prepared)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("active owner transaction"); @@ -284,7 +395,7 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan request.requestId()) .get("xmin", String.class); CreateCanonicalRealmCatalogRequest changed = - request(source, request.requestId(), "realm", "Changed Realm", "owner-mode", "SHARED"); + request(source, request.requestId(), "realm", "Changed Realm", "PRESEEDED_ONLY", "SHARED"); assertThatThrownBy(() -> fixture.create(changed)).isInstanceOf(CatalogConflictException.class); assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) .contains(created); @@ -308,10 +419,10 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan true, true, "SHARED", - "owner-mode", + "PRESEEDED_ONLY", null, null); - assertThatThrownBy(() -> fixture.catalogRepository.prepareInitialPublicProduction(wrongSource)) + assertThatThrownBy(() -> fixture.prepare(wrongSource)) .isInstanceOf(InvalidCatalogEvidenceException.class) .hasMessageContaining("source intake is missing"); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) @@ -330,11 +441,10 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan true, true, "SHARED", - "owner-mode", + "PRESEEDED_ONLY", null, null); - assertThatThrownBy( - () -> fixture.catalogRepository.prepareInitialPublicProduction(mismatchedSource)) + assertThatThrownBy(() -> fixture.prepare(mismatchedSource)) .isInstanceOf(InvalidCatalogEvidenceException.class) .hasMessageContaining("conflicts with the immutable canonical tenant source binding"); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) @@ -359,7 +469,8 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan assertThatThrownBy( () -> fixture.create( - request(retained, uuid(31), "retained-realm", "Realm", "owner-mode", "SHARED"))) + request( + retained, uuid(31), "retained-realm", "Realm", "PRESEEDED_ONLY", "SHARED"))) .isInstanceOf(InvalidCatalogEvidenceException.class) .hasMessageContaining("fresh Game Design"); assertThat( @@ -584,10 +695,12 @@ void isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry( CanonicalRealmCatalogSnapshot first = fixture.create( - request(firstSource, uuid(40), "realm-four", "Realm Four", "owner-mode", "ISOLATED")); + request( + firstSource, uuid(40), "realm-four", "Realm Four", "PRESEEDED_ONLY", "ISOLATED")); CanonicalRealmCatalogSnapshot second = fixture.create( - request(secondSource, uuid(50), "realm-five", "Realm Five", "owner-mode", "ISOLATED")); + request( + secondSource, uuid(50), "realm-five", "Realm Five", "PRESEEDED_ONLY", "ISOLATED")); assertThat(first.playableStateNamespaceId()).isNotEqualTo(second.playableStateNamespaceId()); assertThat(first.tenantSlug()).isNotEqualTo(first.worldSlug()); @@ -625,7 +738,8 @@ void concurrentExactCreationRecoversOneDurableRealmAndNamespace() throws Excepti IntakeReceipt source = fixture.register(tenant(6), "concurrent-world", "Concurrent World", "NEW_GAME_ROW"); CreateCanonicalRealmCatalogRequest request = - request(source, uuid(60), "concurrent-realm", "Concurrent Realm", "owner-mode", "SHARED"); + request( + source, uuid(60), "concurrent-realm", "Concurrent Realm", "PRESEEDED_ONLY", "SHARED"); CountDownLatch ready = new CountDownLatch(2); CountDownLatch start = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); @@ -668,11 +782,9 @@ void freshCatalogAndRetainedAssociationCannotBothAcquireTenantAuthorityInEitherO uuid(71), "association-first-realm", "Association First Realm", - "owner-mode", + "PRESEEDED_ONLY", "SHARED"); - assertThatThrownBy( - () -> - associationFirst.catalogRepository.prepareInitialPublicProduction(afterAssociation)) + assertThatThrownBy(() -> associationFirst.prepare(afterAssociation)) .isInstanceOf(CatalogConflictException.class) .hasMessageContaining("retained numeric Game Session identity"); assertThat( @@ -694,11 +806,12 @@ void freshCatalogAndRetainedAssociationCannotBothAcquireTenantAuthorityInEitherO uuid(80), "catalog-first-realm", "Catalog First Realm", - "owner-mode", + "PRESEEDED_ONLY", "SHARED")); assertThatThrownBy(() -> catalogFirst.insertRetainedAssociation(catalogFirstSource, uuid(81))) .isInstanceOf(DataAccessException.class) - .hasStackTraceContaining("cannot replace fresh canonical tenant namespace authority"); + .hasStackTraceContaining( + "Retained tenant mapping conflicts with a Game Session owner claim"); assertThat( catalogFirst.dsl.fetchCount( DSL.table(DSL.name("game_session_canonical_realm_catalog")))) @@ -868,7 +981,201 @@ private Fixture fixture(boolean seedRetainedNumericRows, MigrationVersion target transactionManager, transactions, dataSource, - schema); + schema, + new java.util.concurrent.ConcurrentHashMap<>()); + } + + private static Record retainedCatalogState(Fixture fixture, UUID requestId) { + return requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin, (to_jsonb(catalog) - ARRAY['complete_policy_set_evidence', " + + "'fixture_policy_request_bytes', 'fixture_policy_seal_operation_id', " + + "'fixture_policy_seal_request_digest', 'fixture_policy_seal_evidence_digest'])::text AS bytes " + + "FROM game_session_canonical_realm_catalog catalog WHERE creation_request_id = ?", + requestId); + } + + private static Record retainedAssociationState(Fixture fixture, UUID tenantId) { + return requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin, (to_jsonb(association) - 'complete_source_evidence')::text AS bytes " + + "FROM game_session_fresh_tenant_association association WHERE canonical_tenant_id = ?", + tenantId); + } + + private static void insertHistoricalFreshAssociation(Fixture fixture, IntakeReceipt receipt) { + AuthoredWorldSourceEvidence source = receipt.source(); + UUID operationId = uuid(1044); + long privateTenantId = 1044L; + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "INSERT INTO game_session_tenant_scope_reservation " + + "(game_session_tenant_id, reservation_kind) VALUES (?, 'FRESH_SOURCE_BOUND')", + privateTenantId); + fixture.dsl.execute( + "INSERT INTO game_session_tenant_canonical_claim " + + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, association_kind, " + + "reservation_kind, association_operation_id, association_request_id) " + + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", + NAMESPACE, + source.canonicalTenantId(), + privateTenantId, + operationId, + source.registrationRequestId()); + fixture.dsl.execute( + "INSERT INTO game_session_fresh_tenant_association " + + "(association_operation_id, target_namespace, association_request_id, source_schema_version, " + + "source_target_namespace, source_request_id, source_canonical_tenant_id, canonical_tenant_id, " + + "legacy_game_session_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW')", + operationId, + NAMESPACE, + source.registrationRequestId(), + NAMESPACE, + source.registrationRequestId(), + source.canonicalTenantId(), + source.canonicalTenantId(), + privateTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey()); + return null; + }); + } + + private static void insertCatalogRow( + Fixture fixture, + IntakeReceipt receipt, + CreateCanonicalRealmCatalogRequest request, + java.util.Map provenance) { + Record intake = + requiredRecord( + fixture.dsl, + "SELECT * FROM game_session_authored_world_source_intake WHERE operation_id = ?", + receipt.operationId()); + java.util.Map values = new java.util.LinkedHashMap<>(); + for (String field : + java.util.List.of("target_namespace", "canonical_tenant_id", "tenant_slug", "world_slug")) { + values.put(field, intake.get(field)); + } + UUID realmId = request.requestId(); + UUID namespaceId = + UUID.nameUUIDFromBytes( + ("historical-namespace/" + realmId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String requestDigest = historicalRequestDigest(request, receipt); + values.put("realm_id", realmId); + values.put("realm_slug", request.realmSlug()); + values.put("realm_display_name", request.realmDisplayName()); + values.put("visible", true); + values.put("public_production", true); + values.put("state_scope", request.stateScope()); + values.put("playable_state_namespace_id", namespaceId); + values.put("character_creation_policy", request.characterCreationPolicy()); + values.put("catalog_revision", 1L); + values.put("creation_request_id", request.requestId()); + values.put("request_digest", requestDigest); + values.put( + "receipt_digest", + historicalReceiptDigest(request, receipt, realmId, namespaceId, requestDigest)); + values.put("source_intake_operation_id", receipt.operationId()); + values.put("source_intake_schema_version", 1); + values.put("source_intake_request_id", receipt.intakeRequestId()); + values.put("source_intake_request_digest", receipt.requestDigest()); + values.put("source_intake_receipt_digest", receipt.receiptDigest()); + for (String field : + java.util.List.of( + "source_schema_version", + "source_registration_request_id", + "source_operation_id", + "source_request_digest", + "source_game_row_id", + "source_game_tenant_key", + "source_provenance_kind", + "source_evidence_digest")) { + values.put(field, intake.get(field)); + } + values.put("source_world_display_name", intake.get("world_display_name")); + values.putAll(provenance); + fixture + .dsl + .insertInto(DSL.table(DSL.name("game_session_canonical_realm_catalog"))) + .columns(values.keySet().stream().map(name -> DSL.field(DSL.name(name))).toList()) + .values(values.values()) + .execute(); + } + + private static String historicalRequestDigest( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt receipt) { + AuthoredWorldSourceEvidence source = receipt.source(); + // Independent V23 framing: decimal UTF-8 byte length, colon, then exact bytes per field. + return historicalDigest( + java.util.List.of( + "game-session-canonical-realm-catalog-request/v1", + "1", + request.requestId().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.sourceIntakeOperationId().toString(), + receipt.intakeRequestId().toString(), + receipt.requestDigest(), + receipt.receiptDigest(), + Integer.toString(source.schemaVersion()), + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + request.realmSlug(), + request.realmDisplayName(), + Boolean.toString(request.visible()), + Boolean.toString(request.publicProduction()), + request.stateScope(), + request.characterCreationPolicy(), + "ABSENT", + "ABSENT")); + } + + private static String historicalReceiptDigest( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt receipt, + UUID realmId, + UUID namespaceId, + String requestDigest) { + return historicalDigest( + java.util.List.of( + "game-session-canonical-realm-catalog-receipt/v1", + "1", + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.requestId().toString(), + requestDigest, + realmId.toString(), + namespaceId.toString(), + "1", + receipt.operationId().toString(), + receipt.receiptDigest())); + } + + private static String historicalDigest(java.util.List fields) { + try { + java.security.MessageDigest hash = java.security.MessageDigest.getInstance("SHA-256"); + for (String value : fields) { + byte[] bytes = value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + hash.update( + Integer.toString(bytes.length).getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + hash.update((byte) ':'); + hash.update(bytes); + } + return "sha256:" + java.util.HexFormat.of().formatHex(hash.digest()); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } } private static UUID tenant(int value) { @@ -891,7 +1198,11 @@ private record Fixture( DataSourceTransactionManager transactionManager, TransactionTemplate transactions, DriverManagerDataSource dataSource, - String schema) { + String schema, + java.util.Map< + CreateCanonicalRealmCatalogRequest, + net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence.PublishedSet> + publishedSets) { void migrateToLatest() { Flyway.configure() .dataSource(dataSource) @@ -915,9 +1226,67 @@ IntakeReceipt register(UUID tenantId, String worldSlug, String displayName, Stri return java.util.Objects.requireNonNull(receipt); } + PreparedInitialPublicProduction prepare(CreateCanonicalRealmCatalogRequest request) { + Record sourceRow = + dsl.fetchOne( + "SELECT world_slug FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (sourceRow == null) return catalogRepository.prepareInitialPublicProduction(request, null); + IntakeReceipt source = + sourceRepository + .read( + request.sourceIntakeOperationId(), + request.canonicalTenantId(), + sourceRow.get("world_slug", String.class), + request.targetNamespace()) + .orElse(null); + if (source == null) return catalogRepository.prepareInitialPublicProduction(request, null); + boolean retained = + Boolean.TRUE.equals( + dsl.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?) AS retained", + request.targetNamespace(), + request.canonicalTenantId()) + .get("retained", Boolean.class)); + if (retained || !"NEW_GAME_ROW".equals(source.source().provenanceKind())) { + return catalogRepository.prepareInitialPublicProduction(request, null); + } + transactions.execute( + status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.nameUUIDFromBytes( + ("gs-association/" + source.source().canonicalTenantId()) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + source.source().targetNamespace(), + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source()))); + UUID versionId = + UUID.nameUUIDFromBytes( + ("controlled-version/" + source.source().canonicalTenantId()) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return catalogRepository.prepareInitialPublicProduction( + request, + publishedSets.computeIfAbsent( + request, + selected -> + CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + selected, + source.source(), + versionId, + 72L, + "publish-policy-" + selected.requestId(), + "release-bundle:" + versionId, + "generation-1", + 3L))); + } + CanonicalRealmCatalogSnapshot create(CreateCanonicalRealmCatalogRequest request) { - PreparedInitialPublicProduction prepared = - catalogRepository.prepareInitialPublicProduction(request); + PreparedInitialPublicProduction prepared = prepare(request); CanonicalRealmCatalogSnapshot snapshot = transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); return java.util.Objects.requireNonNull(snapshot); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java index d3ab440bb2..b5aecb79bb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java @@ -4,26 +4,28 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; -import java.util.List; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.util.Objects; 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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; -import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository.CanonicalGameInstanceLaunchAssociationConflictException; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository; -import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.CanonicalStartingInstanceConflictException; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.InvalidCanonicalStartingInstanceEvidenceException; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalStartingInstanceRepository.StartingInstance; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; @@ -61,10 +63,13 @@ class GameSessionCanonicalStartingInstanceRepositoryIntegrationTest { private static final UUID CANONICAL_VERSION_ID = uuid(207); private static final UUID OWNER_ACCOUNT_UUID = uuid(208); private static final String CONTROL_PLANE_REQUEST_ID = "canonical-starting-control-request-1"; - private static final String REQUEST_DIGEST = "a".repeat(64); + private static final StartSessionPostAuthorizationExecutionTuple ORIGINAL_TUPLE = + CanonicalHumanPublicationOwnerTestFixtures.tuple( + NAMESPACE, TENANT, OWNER_ACCOUNT_UUID, 301L, CONTROL_PLANE_REQUEST_ID); + private static final String REQUEST_DIGEST = ORIGINAL_TUPLE.mutationDigest(); private static final String OTHER_REQUEST_DIGEST = "b".repeat(64); - private static final String RUNTIME_FLAGS_JSON = "{\"eventMode\":true}"; - private static final String OTHER_RUNTIME_FLAGS_JSON = "{\"eventMode\":false}"; + private static final String RUNTIME_FLAGS_JSON = "{}"; + private static final String CHANGED_LAUNCH_DESCRIPTOR_ID = "descriptor-for-starting-changed"; private static final long GAME_TEMPLATE_ID = 301L; private static final long VERSION_ID = 302L; private static final long RELEASE_BUNDLE_ID = 303L; @@ -81,7 +86,7 @@ class GameSessionCanonicalStartingInstanceRepositoryIntegrationTest { void createsUuidOwnedStartingRowAndAssociationAndExactRetryReturnsOriginalIdentity() { Fixture fixture = fixture(true); CompleteLaunchBindingEvidence binding = - launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + launchBinding(fixture.source().source(), fixture.publishedSet(), CONTROL_PLANE_REQUEST_ID); StartingInstance first = fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); @@ -91,9 +96,10 @@ void createsUuidOwnedStartingRowAndAssociationAndExactRetryReturnsOriginalIdenti assertThat(retry).isEqualTo(first); assertThat(first.gameInstanceId()).isPositive(); assertThat(first.gameInstanceUuid()).isNotEqualTo(new UUID(0L, 0L)); - assertThat(first.gameInstanceId()).isNotEqualTo(SOURCE_GAME_ROW_ID); - assertThat(fixture.tenantAssociation().legacyGameSessionTenantId()) - .isNotEqualTo(SOURCE_GAME_ROW_ID); + assertThat(fixture.tenantAssociation().sourceEvidence().sourceGameRowId()) + .isEqualTo(fixture.source().source().sourceGameRowId()); + assertThat(fixture.tenantAssociation().sourceEvidence().sourceGameTenantKey()) + .isEqualTo(fixture.source().source().sourceGameTenantKey()); assertThat(first.launchAssociation().gameInstanceUuid()).isEqualTo(first.gameInstanceUuid()); assertThat(first.launchAssociation().currentGameInstanceStatus().name()).isEqualTo("STARTING"); assertThat(first.launchAssociation().capturedStartingRowVersion()).isZero(); @@ -134,16 +140,27 @@ void createsUuidOwnedStartingRowAndAssociationAndExactRetryReturnsOriginalIdenti fixture.dsl(), "SELECT complete_launch_binding_evidence -> 'descriptor' ->> 'runtimeFlagsJson' " + "AS runtime_flags, complete_launch_binding_evidence -> 'descriptor' " - + "->> 'scriptPatchVersion' AS candidate_script_patch, game_instance_uuid " + + "->> 'scriptPatchVersion' AS candidate_script_patch, game_instance_uuid, " + + "original_start_session_tuple, catalog_creation_request_id, catalog_revision " + "FROM game_session_canonical_instance_launch " + "WHERE target_namespace = ? AND control_plane_request_id = ?", NAMESPACE, CONTROL_PLANE_REQUEST_ID); assertThat(association.get("runtime_flags", String.class)).isEqualTo(RUNTIME_FLAGS_JSON); - assertThat(association.get("candidate_script_patch", String.class)) - .isEqualTo("candidate-script-v1"); + assertThat(association.get("candidate_script_patch", String.class)).isNull(); assertThat(association.get("game_instance_uuid", UUID.class)) .isEqualTo(first.gameInstanceUuid()); + assertThat(association.get("original_start_session_tuple", byte[].class)) + .containsExactly(fixture.originalTuple().canonicalBytes()); + assertThat(association.get("catalog_creation_request_id", UUID.class)) + .isEqualTo(CATALOG_REQUEST_ID); + assertThat(association.get("catalog_revision", Long.class)) + .isEqualTo( + fixture + .catalogRepository() + .readByRequest(NAMESPACE, CATALOG_REQUEST_ID) + .orElseThrow() + .catalogRevision()); assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); assertThat( fixture.dsl().fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) @@ -156,7 +173,7 @@ void createsUuidOwnedStartingRowAndAssociationAndExactRetryReturnsOriginalIdenti void sameRequestContendersReturnOneOriginalRowAndAssociation() throws Exception { Fixture fixture = fixture(true); CompleteLaunchBindingEvidence binding = - launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + launchBinding(fixture.source().source(), fixture.publishedSet(), CONTROL_PLANE_REQUEST_ID); CountDownLatch ready = new CountDownLatch(2); CountDownLatch start = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); @@ -187,30 +204,34 @@ void sameRequestContendersReturnOneOriginalRowAndAssociation() throws Exception void changedOwnerDigestOrBindingConflictsWithoutCreatingAnotherRuntimeRow() { Fixture fixture = fixture(true); CompleteLaunchBindingEvidence binding = - launchBinding(fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + launchBinding(fixture.source().source(), fixture.publishedSet(), CONTROL_PLANE_REQUEST_ID); StartingInstance original = fixture.start(OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding); assertThatThrownBy( () -> fixture.start(uuid(209), CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding)) - .isInstanceOf(CanonicalStartingInstanceConflictException.class) + .isInstanceOf(InvalidCanonicalStartingInstanceEvidenceException.class) .hasMessageContaining("owner"); assertThatThrownBy( () -> fixture.start( OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, OTHER_REQUEST_DIGEST, binding)) - .isInstanceOf(CanonicalStartingInstanceConflictException.class) - .hasMessageContaining("request digest"); + .isInstanceOf(InvalidCanonicalStartingInstanceEvidenceException.class) + .hasMessageContaining("launch request"); CompleteLaunchBindingEvidence changedBinding = launchBinding( - fixture.source().source(), CONTROL_PLANE_REQUEST_ID, OTHER_RUNTIME_FLAGS_JSON); + fixture.source().source(), + fixture.publishedSet(), + CONTROL_PLANE_REQUEST_ID, + CHANGED_LAUNCH_DESCRIPTOR_ID, + fixture.source().source().operationId()); assertThatThrownBy( () -> fixture.start( OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, changedBinding)) - .isInstanceOf(CanonicalGameInstanceLaunchAssociationConflictException.class) - .hasMessageContaining("changed tenant, instance, or source binding"); + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Canonical descriptor pin differs from complete launch binding"); assertThat( requiredRecord( @@ -232,7 +253,11 @@ void invalidPersistedSourceAndMissingRealmLeaveNoPartialStartingRowOrAssociation Fixture fixture = fixture(true); CompleteLaunchBindingEvidence mismatchedSource = launchBinding( - fixture.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON, uuid(299)); + fixture.source().source(), + fixture.publishedSet(), + CONTROL_PLANE_REQUEST_ID, + "descriptor-for-starting", + uuid(299)); assertThatThrownBy( () -> fixture.start( @@ -243,7 +268,8 @@ void invalidPersistedSourceAndMissingRealmLeaveNoPartialStartingRowOrAssociation Fixture missingRealm = fixture(false); CompleteLaunchBindingEvidence validBinding = - launchBinding(missingRealm.source().source(), CONTROL_PLANE_REQUEST_ID, RUNTIME_FLAGS_JSON); + launchBinding( + missingRealm.source().source(), missingRealm.publishedSet(), CONTROL_PLANE_REQUEST_ID); assertThatThrownBy( () -> missingRealm.start( @@ -253,6 +279,116 @@ void invalidPersistedSourceAndMissingRealmLeaveNoPartialStartingRowOrAssociation assertNoStartingRows(missingRealm); } + @Test + void captureWaitsForRequestLockBeforeRejectingUnavailableOriginalPins() throws Exception { + Fixture fixture = fixture(true); + String requestId = CONTROL_PLANE_REQUEST_ID + "-without-pins"; + StartSessionPostAuthorizationExecutionTuple unpinnedTuple = + CanonicalHumanPublicationOwnerTestFixtures.tuple( + NAMESPACE, TENANT, OWNER_ACCOUNT_UUID, GAME_TEMPLATE_ID, requestId); + CompleteLaunchBindingEvidence unpinnedBinding = + launchBinding(fixture.source().source(), fixture.publishedSet(), requestId); + CanonicalGameInstanceLaunchAssociationRepository associationRepository = + new CanonicalGameInstanceLaunchAssociationRepository(fixture.dsl(), NAMESPACE); + String lockKey = NAMESPACE + ":" + requestId; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try (Connection lockConnection = fixture.dataSource().getConnection()) { + boolean lockHeld = false; + try { + try (PreparedStatement acquire = + lockConnection.prepareStatement( + "SELECT pg_advisory_lock(hashtextextended(? || ':' || ?, 0))")) { + acquire.setString(1, NAMESPACE); + acquire.setString(2, requestId); + acquire.execute(); + lockHeld = true; + } + + Future capture = + executor.submit( + () -> + fixture + .transactions() + .executeWithoutResult( + status -> + associationRepository.capture( + fixture.tenantAssociation(), + 1L, + unpinnedBinding, + unpinnedTuple))); + awaitAdvisoryWaiter(fixture, lockKey, capture); + assertThat(capture.isDone()).isFalse(); + assertNoStartingRows(fixture); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + + try (PreparedStatement release = + lockConnection.prepareStatement( + "SELECT pg_advisory_unlock(hashtextextended(? || ':' || ?, 0))")) { + release.setString(1, NAMESPACE); + release.setString(2, requestId); + release.execute(); + lockHeld = false; + } + + assertThatThrownBy(() -> capture.get(20, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasRootCauseInstanceOf(IllegalStateException.class) + .hasRootCauseMessage("Exact canonical pins are required before STARTING"); + assertNoStartingRows(fixture); + assertThat(fixture.dsl().fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))) + .isZero(); + } finally { + if (lockHeld) { + try (PreparedStatement release = + lockConnection.prepareStatement( + "SELECT pg_advisory_unlock(hashtextextended(? || ':' || ?, 0))")) { + release.setString(1, NAMESPACE); + release.setString(2, requestId); + release.execute(); + } + } + } + } finally { + executor.shutdownNow(); + } + } + + private static void awaitAdvisoryWaiter(Fixture fixture, String lockKey, Future capture) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); + while (System.nanoTime() < deadline) { + Long waiting = + Objects.requireNonNull( + fixture + .dsl() + .fetchOne( + "SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' " + + "AND NOT granted AND objsubid = 1 " + + "AND classid = (((hashtextextended(?, 0) >> 32) " + + "& 4294967295)::oid) " + + "AND objid = ((hashtextextended(?, 0) & 4294967295)::oid)", + lockKey, + lockKey), + "PostgreSQL did not return the advisory-lock waiter count") + .get(0, Long.class); + if (waiting == 1L) { + return; + } + if (capture.isDone()) { + throw new AssertionError( + "Capture completed before it waited on the request lock and checked original pins"); + } + try { + Thread.sleep(10); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while awaiting the canonical request-lock waiter", interrupted); + } + } + throw new AssertionError("Capture did not wait on the canonical request advisory lock"); + } + private static StartingInstance contender( Fixture fixture, CompleteLaunchBindingEvidence binding, @@ -274,14 +410,18 @@ private static void assertNoStartingRows(Fixture fixture) { } private static CompleteLaunchBindingEvidence launchBinding( - AuthoredWorldSourceEvidence source, String requestId, String runtimeFlagsJson) { - return launchBinding(source, requestId, runtimeFlagsJson, source.operationId()); + AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + String requestId) { + return launchBinding( + source, publishedSet, requestId, "descriptor-for-starting", source.operationId()); } private static CompleteLaunchBindingEvidence launchBinding( AuthoredWorldSourceEvidence source, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, String requestId, - String runtimeFlagsJson, + String launchDescriptorId, UUID authoredWorldSourceOperationId) { AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = new AuthoredWorldLaunchDescriptorEvidence.Request( @@ -292,66 +432,29 @@ private static CompleteLaunchBindingEvidence launchBinding( authoredWorldSourceOperationId, source.evidenceDigest(), GAME_TEMPLATE_ID, - true, - "candidate-script-v1", + false, + null, false, null, false, null, true, - runtimeFlagsJson); + RUNTIME_FLAGS_JSON); AuthoredWorldLaunchDescriptorEvidence descriptor = AuthoredWorldLaunchDescriptorEvidence.create( descriptorRequest, - "descriptor-for-starting", + launchDescriptorId, VERSION_ID, - true, - "candidate-script-v1", - runtimeFlagsJson, + false, + null, + RUNTIME_FLAGS_JSON, "generation-config-8", VERSION_STATE_EPOCH, RELEASE_BUNDLE_ID, "published-release-bundle-303", false, null); - List participants = - AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(VERSION_ID), - false, - null, - "commit-starting-303", - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) - .toList(); - AuthoredWorldReleaseAttestationEvidence release = - AuthoredWorldReleaseAttestationEvidence.create( - NAMESPACE, - descriptor.resultDigest(), - source.canonicalTenantId(), - CANONICAL_VERSION_ID, - source.worldSlug(), - authoredWorldSourceOperationId, - source.evidenceDigest(), - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - "publish-starting-303", - "commit-starting-303", - participants, - "sha256:" + "e".repeat(64), - 1, - List.of(), - List.of(), - List.of("LOOK"), - descriptor.generationConfigRevision()); - return new CompleteLaunchBindingEvidence(descriptor, release); + return CanonicalHumanPublicationOwnerTestFixtures.completeBinding(descriptor, publishedSet); } private static AuthoredWorldSourceEvidence freshSource() { @@ -401,13 +504,16 @@ private static UUID uuid(int value) { private record Fixture( DSLContext dsl, + DriverManagerDataSource dataSource, TransactionTemplate transactions, GameSessionAuthoredWorldSourceRepository sourceRepository, GameSessionFreshTenantAssociationRepository tenantAssociationRepository, GameSessionCanonicalRealmCatalogRepository catalogRepository, GameSessionCanonicalStartingInstanceRepository startingRepository, IntakeReceipt source, - FreshGameSessionTenantAssociation tenantAssociation) { + FreshGameSessionTenantAssociation tenantAssociation, + StartSessionPostAuthorizationExecutionTuple originalTuple, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { StartingInstance start( UUID ownerAccountUuid, String controlPlaneRequestId, @@ -421,7 +527,8 @@ StartingInstance start( binding, ownerAccountUuid, controlPlaneRequestId, - requestDigest)), + requestDigest, + originalTuple)), "canonical STARTING owner result"); } } @@ -461,39 +568,59 @@ private static Fixture fixture(boolean createRealm) { transactions.execute( status -> sourceRepository.register(INTAKE_REQUEST_ID, freshSource())), "registered authored-world source receipt"); - if (createRealm) { - var request = - new CreateCanonicalRealmCatalogRequest( - CATALOG_REQUEST_ID, - NAMESPACE, - TENANT, - source.operationId(), - "amber-realm", - "Amber Realm", - true, - true, - "SHARED", - "explicit-policy-v1", - null, - null); - var prepared = catalogRepository.prepareInitialPublicProduction(request); - transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); - } FreshGameSessionTenantAssociation tenantAssociation = Objects.requireNonNull( transactions.execute( status -> tenantAssociationRepository.associateFresh( - TENANT_ASSOCIATION_OPERATION_ID, NAMESPACE, source)), - "fresh source-bound Game Session tenant association"); + TENANT_ASSOCIATION_OPERATION_ID, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source()))), + "fresh complete source-bound Game Session tenant association"); + var request = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST_ID, + NAMESPACE, + TENANT, + source.operationId(), + "amber-realm", + "Amber Realm", + true, + true, + "SHARED", + "PRESEEDED_ONLY", + null, + null); + var publishedSet = + CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + request, + source.source(), + CANONICAL_VERSION_ID, + VERSION_ID, + "publication-for-starting-303", + "published-release-bundle-303", + "generation-config-8", + VERSION_STATE_EPOCH); + if (createRealm) { + var prepared = catalogRepository.prepareInitialPublicProduction(request, publishedSet); + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + } + var binding = launchBinding(source.source(), publishedSet, CONTROL_PLANE_REQUEST_ID); + CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( + dsl, transactions, ORIGINAL_TUPLE, source.source(), publishedSet, binding); return new Fixture( dsl, + dataSource, transactions, sourceRepository, tenantAssociationRepository, catalogRepository, startingRepository, source, - tenantAssociation); + tenantAssociation, + ORIGINAL_TUPLE, + publishedSet); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index eaff698f94..fde64b437f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -2,8 +2,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -11,13 +16,19 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamesession.client.GameDesignFreshTenantCreationClient; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantSourceException; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import net.firedevops.firemud.test.TestContainerImages; @@ -29,6 +40,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -64,10 +76,13 @@ void allocatesPrivateIdentityAndReturnsTheOriginalExactAssociationOnRetry() { assertThat(retry).isEqualTo(first); assertThat(first.associationOperationId()).isEqualTo(associationOperationId); assertThat(first.legacyGameSessionTenantId()).isPositive(); - assertThat(first.legacyGameSessionTenantId()).isNotEqualTo(source.source().sourceGameRowId()); assertThat(first.sourceEvidence().requestId()) - .isEqualTo(source.source().registrationRequestId()); + .isEqualTo(creationEvidence(source.source()).creationRequestId()); assertThat(first.sourceEvidence().canonicalTenantId()).isEqualTo(TENANT); + assertThat(first.sourceEvidence().sourceGameRowId()) + .isEqualTo(source.source().sourceGameRowId()); + assertThat(first.sourceEvidence().sourceGameTenantKey()) + .isEqualTo(source.source().sourceGameTenantKey()); assertThat(first.sourceEvidence().provenanceKind()).isEqualTo("NEW_GAME_ROW"); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) .isEqualTo(1); @@ -88,6 +103,184 @@ void allocatesPrivateIdentityAndReturnsTheOriginalExactAssociationOnRetry() { .isEqualTo("FRESH_SOURCE_BOUND"); } + @Test + void skipsExplicitLegacyReservationWhenTheDefaultIdentitySequenceCollides() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + fixture.dsl.execute( + "INSERT INTO game_session_tenant_scope_reservation" + + " (game_session_tenant_id, reservation_kind, reserved_at)" + + " VALUES (1, 'LEGACY_OCCUPIED', TIMESTAMPTZ '2020-01-02 03:04:05+00')"); + setTenantReservationSequenceNextValue(fixture.dsl, 1L); + var legacyReservation = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT reservation_kind, reserved_at, xmin::text AS xmin" + + " FROM game_session_tenant_scope_reservation" + + " WHERE game_session_tenant_id = 1"), + "expected explicit legacy reservation"); + + FreshGameSessionTenantAssociation association = fixture.associate(uuid(627), NAMESPACE, source); + + assertThat(association.legacyGameSessionTenantId()).isEqualTo(2L); + var preservedReservation = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT reservation_kind, reserved_at, xmin::text AS xmin" + + " FROM game_session_tenant_scope_reservation" + + " WHERE game_session_tenant_id = 1"), + "expected legacy reservation after allocation"); + assertThat(preservedReservation.get("reservation_kind", String.class)) + .isEqualTo(legacyReservation.get("reservation_kind", String.class)); + assertThat(preservedReservation.get("reserved_at")) + .isEqualTo(legacyReservation.get("reserved_at")); + assertThat(preservedReservation.get("xmin", String.class)) + .isEqualTo(legacyReservation.get("xmin", String.class)); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(2); + } + + @Test + void skipsExistingFreshReservationAndKeepsItsExactAssociationReplay() { + Fixture fixture = fixture(); + IntakeReceipt originalSource = fixture.registerFreshSource(); + FreshGameSessionTenantAssociation original = + fixture.associate(uuid(628), NAMESPACE, originalSource); + long originalTenantId = original.legacyGameSessionTenantId(); + var originalReservation = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT reservation_kind, reserved_at, xmin::text AS xmin" + + " FROM game_session_tenant_scope_reservation" + + " WHERE game_session_tenant_id = ?", + originalTenantId), + "expected original fresh reservation"); + IntakeReceipt nextSource = + fixture.registerSource(uuid(629), uuid(630), uuid(631), uuid(632), 968L, "second-world"); + setTenantReservationSequenceNextValue(fixture.dsl, originalTenantId); + + FreshGameSessionTenantAssociation next = fixture.associate(uuid(633), NAMESPACE, nextSource); + FreshGameSessionTenantAssociation replay = + fixture.associate(uuid(628), NAMESPACE, originalSource); + + assertThat(next.legacyGameSessionTenantId()).isEqualTo(originalTenantId + 1); + assertThat(replay).isEqualTo(original); + var preservedReservation = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT reservation_kind, reserved_at, xmin::text AS xmin" + + " FROM game_session_tenant_scope_reservation" + + " WHERE game_session_tenant_id = ?", + originalTenantId), + "expected original fresh reservation after allocation and replay"); + assertThat(preservedReservation.get("reservation_kind", String.class)) + .isEqualTo("FRESH_SOURCE_BOUND"); + assertThat(preservedReservation.get("reserved_at")) + .isEqualTo(originalReservation.get("reserved_at")); + assertThat(preservedReservation.get("xmin", String.class)) + .isEqualTo(originalReservation.get("xmin", String.class)); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(2); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(2); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isEqualTo(2); + } + + @Test + void refusesAfterBoundedReservationCollisionsWithoutCreatingPartialAssociation() { + Fixture fixture = fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + fixture.dsl.execute( + "INSERT INTO game_session_tenant_scope_reservation" + + " (game_session_tenant_id, reservation_kind)" + + " SELECT occupied_id, 'LEGACY_OCCUPIED'" + + " FROM generate_series(1, 64) AS occupied(occupied_id)"); + setTenantReservationSequenceNextValue(fixture.dsl, 1L); + + assertThatThrownBy(() -> fixture.associate(uuid(634), NAMESPACE, source)) + .isExactlyInstanceOf(InvalidFreshTenantAssociationException.class) + .hasMessageContaining("bounded allocation attempts"); + + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(64); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + } + + private static void setTenantReservationSequenceNextValue(DSLContext dsl, long nextValue) { + dsl.fetchOne( + "SELECT setval(pg_get_serial_sequence(" + + "'game_session_tenant_scope_reservation', 'game_session_tenant_id'), ?, false)", + nextValue); + } + + @Test + void exactHumanRetryReadsCommittedAssociationAfterAdvisoryWaitOnRepeatableReadDefault() + throws Exception { + HumanRetryFixture humanFixture = fixtureWithRepeatableReadDefault(); + Fixture fixture = humanFixture.fixture(); + IntakeReceipt source = + fixture.registerSource( + uuid(641), uuid(642), uuid(643), UUID.randomUUID(), 966L, "human-retry-world"); + FreshTenantCreationEvidence creation = creationEvidence(source.source()); + when(humanFixture + .gameDesignClient() + .resolveCreation(creation.creationRequestId(), creation.requestDigest())) + .thenReturn(creation); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne("SHOW default_transaction_isolation"), + "PostgreSQL did not return the transaction isolation setting") + .get(0, String.class)) + .isEqualTo("repeatable read"); + + String canonicalLockKey = + "fresh-tenant-canonical:" + creation.targetNamespace() + ":" + creation.canonicalTenantId(); + ExecutorService executor = Executors.newSingleThreadExecutor(); + AtomicReference> retry = new AtomicReference<>(); + try { + FreshGameSessionTenantAssociation first = + fixture.transactions.execute( + status -> { + fixture.dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", canonicalLockKey); + retry.set( + executor.submit( + () -> + fixture.associationRepository.associateFreshTenant( + creation.creationRequestId(), creation.requestDigest()))); + awaitAdvisoryWait(fixture, canonicalLockKey); + return fixture.associateFresh(uuid(640), NAMESPACE, source); + }); + + FreshTenantAssociation actualRetry = retry.get().get(15, TimeUnit.SECONDS); + assertThat(actualRetry.targetNamespace()).isEqualTo(creation.targetNamespace()); + assertThat(actualRetry.canonicalTenantId()).isEqualTo(creation.canonicalTenantId()); + assertThat(actualRetry.gameSessionTenantId()).isEqualTo(first.legacyGameSessionTenantId()); + assertThat(actualRetry.associationOperationId()).isEqualTo(first.associationOperationId()); + assertThat(actualRetry.sourceEvidence()).isEqualTo(creation); + assertThat( + fixture.associationRepository.readByCanonicalTenantId(creation.canonicalTenantId())) + .contains(actualRetry); + assertThat(first.sourceEvidence().requestId()).isEqualTo(creation.creationRequestId()); + assertThat(first.sourceEvidence().canonicalTenantId()) + .isEqualTo(creation.canonicalTenantId()); + assertThat(first.sourceEvidence().sourceGameRowId()).isEqualTo(creation.sourceGameRowId()); + assertThat(first.sourceEvidence().sourceGameTenantKey()) + .isEqualTo(creation.sourceGameTenantKey()); + assertThat(first.sourceEvidence().provenanceKind()).isEqualTo(creation.provenanceKind()); + verify(humanFixture.gameDesignClient()) + .resolveCreation(creation.creationRequestId(), creation.requestDigest()); + } finally { + executor.shutdownNow(); + } + } + @Test void rejectsChangedReceiptMissingReceiptAndNamespaceMismatchBeforeAllocation() { Fixture fixture = fixture(); @@ -97,10 +290,10 @@ void rejectsChangedReceiptMissingReceiptAndNamespaceMismatchBeforeAllocation() { assertThatThrownBy( () -> fixture.associate(associationOperationId, NAMESPACE, changedReceipt(source))) .isInstanceOf(InvalidFreshTenantSourceException.class) - .hasMessageContaining("differs from the requested exact receipt"); + .hasMessageContaining("Complete creation and authored-source receipts differ"); assertThatThrownBy( () -> fixture.associate(associationOperationId, NAMESPACE + "-other", source)) - .isInstanceOf(FreshTenantAssociationConflictException.class) + .isInstanceOf(InvalidFreshTenantSourceException.class) .hasMessageContaining("namespace"); IntakeReceipt missing = receiptFor(uuid(607), freshSource(uuid(608), uuid(609), TENANT, 960L)); @@ -122,11 +315,10 @@ void rejectsSameOperationWithDifferentSourceOrNamespaceAsAnIdempotencyConflict() FreshGameSessionTenantAssociation committed = fixture.associate(associationOperationId, NAMESPACE, firstSource); assertThatThrownBy(() -> fixture.associate(associationOperationId, NAMESPACE, secondSource)) - .isInstanceOf(FreshTenantAssociationConflictException.class) - .hasMessageContaining("different source or namespace"); + .isExactlyInstanceOf(FreshTenantAssociationConflictException.class); assertThatThrownBy( () -> fixture.associate(associationOperationId, NAMESPACE + "-other", firstSource)) - .isInstanceOf(FreshTenantAssociationConflictException.class); + .isInstanceOf(InvalidFreshTenantSourceException.class); assertThat( Objects.requireNonNull( @@ -143,6 +335,98 @@ void rejectsSameOperationWithDifferentSourceOrNamespaceAsAnIdempotencyConflict() .isEqualTo(1); } + @Test + void differentCreationRequestForBoundCanonicalTenantConflictsWithoutOwnerMutation() { + HumanRetryFixture humanFixture = fixtureWithRepeatableReadDefault(); + Fixture fixture = humanFixture.fixture(); + IntakeReceipt source = fixture.registerFreshSource(); + FreshTenantCreationEvidence originalEvidence = creationEvidence(source.source()); + FreshGameSessionTenantAssociation original = + fixture.associate(uuid(630), NAMESPACE, source, originalEvidence); + FreshTenantCreationEvidence competingEvidence = creationEvidence(source.source(), uuid(631)); + assertThat(competingEvidence.creationRequestId()) + .isNotEqualTo(originalEvidence.creationRequestId()); + when(humanFixture + .gameDesignClient() + .resolveCreation( + competingEvidence.creationRequestId(), competingEvidence.requestDigest())) + .thenReturn(competingEvidence); + + var associationBefore = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, association_operation_id, association_request_id, " + + "legacy_game_session_tenant_id FROM game_session_fresh_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + TENANT), + "expected complete original fresh association"); + var claimBefore = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, association_operation_id, association_request_id, " + + "legacy_game_session_tenant_id FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + TENANT), + "expected complete original canonical tenant claim"); + var reservationBefore = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, game_session_tenant_id, reservation_kind " + + "FROM game_session_tenant_scope_reservation " + + "WHERE game_session_tenant_id = ?", + original.legacyGameSessionTenantId()), + "expected original source-bound tenant reservation"); + + assertThatThrownBy( + () -> + fixture.associationRepository.associateFreshTenant( + competingEvidence.creationRequestId(), competingEvidence.requestDigest())) + .isExactlyInstanceOf(FreshTenantAssociationConflictException.class) + .hasMessageContaining("canonical tenant"); + verify(humanFixture.gameDesignClient()) + .resolveCreation(competingEvidence.creationRequestId(), competingEvidence.requestDigest()); + + var associationAfter = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, association_operation_id, association_request_id, " + + "legacy_game_session_tenant_id FROM game_session_fresh_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + TENANT), + "original complete fresh association remains present"); + var claimAfter = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, association_operation_id, association_request_id, " + + "legacy_game_session_tenant_id FROM game_session_tenant_canonical_claim " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + TENANT), + "original complete canonical tenant claim remains present"); + var reservationAfter = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT xmin::text AS xmin, game_session_tenant_id, reservation_kind " + + "FROM game_session_tenant_scope_reservation " + + "WHERE game_session_tenant_id = ?", + original.legacyGameSessionTenantId()), + "original source-bound tenant reservation remains present"); + assertThat(associationAfter.intoMap()).isEqualTo(associationBefore.intoMap()); + assertThat(claimAfter.intoMap()).isEqualTo(claimBefore.intoMap()); + assertThat(reservationAfter.intoMap()).isEqualTo(reservationBefore.intoMap()); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + } + @Test void oneConcurrentContenderOwnsTheCanonicalTenantMapping() throws Exception { Fixture fixture = fixture(); @@ -200,7 +484,15 @@ void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { "expected retained source intake") .get("xmin", String.class); - assertThatThrownBy(() -> fixture.associate(uuid(622), NAMESPACE, retainedSource)) + // A complete NEW_GAME_ROW candidate is deliberately paired with the committed retained + // receipt so the real GS intake reader exercises its provenance refusal before allocation. + assertThatThrownBy( + () -> + fixture.associate( + uuid(622), + NAMESPACE, + retainedSource, + creationEvidence(retainedSource.source(), "NEW_GAME_ROW"))) .isInstanceOf(InvalidFreshTenantSourceException.class) .hasMessageContaining("NEW_GAME_ROW"); @@ -246,7 +538,9 @@ private static Attempt contender( } try { return new Attempt(fixture.associate(associationOperationId, NAMESPACE, source), false); - } catch (FreshTenantAssociationConflictException conflict) { + } catch (InvalidFreshTenantAssociationException conflict) { + assertThat(conflict) + .hasMessageContaining("Association operation differs from its immutable original"); return new Attempt(null, true); } } @@ -262,6 +556,62 @@ private static void assertNoFreshAssociation(Fixture fixture) { assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); } + /** Controlled upstream creation receipt; this GS owner test does not execute Game Design. */ + private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + return creationEvidence(source, source.provenanceKind()); + } + + private static FreshTenantCreationEvidence creationEvidence( + AuthoredWorldSourceEvidence source, String provenanceKind) { + UUID request = + UUID.nameUUIDFromBytes( + ("creation-request/" + source.canonicalTenantId()) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + UUID operation = + UUID.nameUUIDFromBytes( + ("creation-operation/" + source.canonicalTenantId()) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return creationEvidence(source, provenanceKind, request, operation); + } + + private static FreshTenantCreationEvidence creationEvidence( + AuthoredWorldSourceEvidence source, UUID request) { + UUID operation = + UUID.nameUUIDFromBytes( + ("creation-operation/" + request).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return creationEvidence(source, source.provenanceKind(), request, operation); + } + + private static FreshTenantCreationEvidence creationEvidence( + AuthoredWorldSourceEvidence source, String provenanceKind, UUID request, UUID operation) { + String requestDigest = + GameTenantCreationDigest.requestDigest( + source.targetNamespace(), + request, + source.sourceGameTenantKey(), + source.worldDisplayName(), + null); + return new FreshTenantCreationEvidence( + 1, + source.targetNamespace(), + request, + operation, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + request, + operation, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + provenanceKind)); + } + private static IntakeReceipt changedReceipt(IntakeReceipt receipt) { AuthoredWorldSourceEvidence source = receipt.source(); String changedName = source.worldDisplayName() + " changed"; @@ -459,13 +809,26 @@ FreshGameSessionTenantAssociation associateFresh( UUID associationOperationId, String namespace, IntakeReceipt source) { return transactions.execute( status -> - associationRepository.associateFresh(associationOperationId, namespace, source)); + associationRepository.associateFresh( + associationOperationId, namespace, source, creationEvidence(source.source()))); } FreshGameSessionTenantAssociation associate( UUID associationOperationId, String namespace, IntakeReceipt source) { + return associate( + associationOperationId, namespace, source, creationEvidence(source.source())); + } + + FreshGameSessionTenantAssociation associate( + UUID associationOperationId, + String namespace, + IntakeReceipt source, + FreshTenantCreationEvidence creationEvidence) { return Objects.requireNonNull( - associateFresh(associationOperationId, namespace, source), + transactions.execute( + status -> + associationRepository.associateFresh( + associationOperationId, namespace, source, creationEvidence)), "fresh tenant association result"); } } @@ -497,4 +860,76 @@ private Fixture fixture() { new GameSessionAuthoredWorldSourceRepository(dsl), new GameSessionFreshTenantAssociationRepository(dsl)); } + + private HumanRetryFixture fixtureWithRepeatableReadDefault() { + String schema = "gs_fresh_tenant_rr_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = + new DriverManagerDataSource() { + @Override + public Connection getConnection() throws SQLException { + Connection connection = super.getConnection(); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + return connection; + } + }; + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameDesignFreshTenantCreationClient gameDesignClient = + mock(GameDesignFreshTenantCreationClient.class); + GameSessionFreshTenantAssociationRepository associationRepository = + new GameSessionFreshTenantAssociationRepository( + dsl, transactionManager, gameDesignClient, NAMESPACE); + return new HumanRetryFixture( + new Fixture(dsl, transactions, sourceRepository, associationRepository), gameDesignClient); + } + + private static void awaitAdvisoryWait(Fixture fixture, String lockKey) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (System.nanoTime() < deadline) { + Boolean waiting = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype = 'advisory' " + + "AND NOT granted AND objsubid = 1 " + + "AND classid = (((hashtextextended(?, 0) >> 32) & 4294967295)::oid) " + + "AND objid = ((hashtextextended(?, 0) & 4294967295)::oid))", + lockKey, + lockKey), + "PostgreSQL did not return the advisory-lock wait query result") + .get(0, Boolean.class); + if (Boolean.TRUE.equals(waiting)) { + return; + } + try { + Thread.sleep(10); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while awaiting the owner advisory lock", interrupted); + } + } + throw new AssertionError("Human retry did not wait for the canonical association owner lock"); + } + + private record HumanRetryFixture( + Fixture fixture, GameDesignFreshTenantCreationClient gameDesignClient) {} } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java index 6a90adce66..30a73a5412 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -5,13 +5,12 @@ import java.nio.file.Path; import java.time.Duration; -import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.InitialConfigured; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; @@ -33,7 +32,6 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; -import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; @@ -84,6 +82,17 @@ void readsOnlyTheExactRetainedAssociationAndDescriptorForTheOriginalPendingAttem .containsExactly(tuple.canonicalBytes()); assertThat(read.ownerAttemptId()).isEqualTo(starting.claim().ownerAttemptId()); assertThat(read.ownerFence()).isEqualTo(starting.claim().ownerFence()).isPositive(); + var catalog = + fixture + .dsl() + .fetchOne( + "SELECT realm_id, catalog_revision FROM game_session_canonical_realm_catalog " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + fixture.namespace(), + fixture.tenantId()); + assertThat(catalog).isNotNull(); + assertThat(read.canonicalRealmId()).isEqualTo(catalog.get("realm_id", UUID.class)); + assertThat(read.catalogRevision()).isEqualTo(catalog.get("catalog_revision", Long.class)); assertThat( fixture .dsl() @@ -104,9 +113,11 @@ void absentOriginalAttemptAndPinsDoNotExposeTheStartingAssociation() { GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( "original-association-handoff-no-owner"); Fixture fixture = fixture(tuple, Duration.ofSeconds(30)); - StartingInstance starting = fixture.startWithoutOwnerPins(tuple); - - assertThat(fixture.read(selector(starting.launchAssociation()))).isEmpty(); + assertThatThrownBy(() -> fixture.startWithoutOwnerPins(tuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact canonical pins are required before STARTING"); + assertThat(count(fixture, "game_instances")).isZero(); + assertThat(count(fixture, "game_session_canonical_instance_launch")).isZero(); } @Test @@ -354,9 +365,11 @@ void historicalReadDeniesAnAbsentImmutableSelectionPin() { GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.tuple( "historical-original-association-no-selection-pin"); Fixture fixture = fixture(tuple, Duration.ofSeconds(30)); - OwnerBackedStarting starting = fixture.startWithOwnerAttemptWithoutPins(tuple); - - assertThat(fixture.historicalRead(historicalRequest(starting))).isEmpty(); + assertThatThrownBy(() -> fixture.startWithOwnerAttemptWithoutPins(tuple)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact canonical pins are required before STARTING"); + assertThat(count(fixture, "game_instances")).isZero(); + assertThat(count(fixture, "game_session_canonical_instance_launch")).isZero(); Fixture mismatched = fixture(tuple, Duration.ofSeconds(30)); OwnerBackedStarting mismatchedStarting = mismatched.startWithOwnerPins(tuple); @@ -463,45 +476,11 @@ private static void enableSelectionPinImmutability(Fixture fixture) { } private static CompleteLaunchBindingEvidence completeBinding( - AuthoredWorldLaunchDescriptorEvidence descriptor, UUID canonicalVersionId) { - List participants = - AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - "original-association-commit", - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) - .toList(); - var release = - AuthoredWorldReleaseAttestationEvidence.create( - descriptor.targetNamespace(), - descriptor.resultDigest(), - descriptor.canonicalTenantId(), - canonicalVersionId, - descriptor.worldSlug(), - descriptor.authoredWorldSourceOperationId(), - descriptor.authoredWorldSourceEvidenceDigest(), - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - "original-association-publish", - "original-association-commit", - participants, - "sha256:" + "e".repeat(64), - 1, - List.of(), - List.of(), - List.of(), - descriptor.generationConfigRevision()); - return new CompleteLaunchBindingEvidence(descriptor, release); + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID canonicalVersionId, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + assertThat(publishedSet.target().canonicalVersionId()).isEqualTo(canonicalVersionId); + return CanonicalHumanPublicationOwnerTestFixtures.completeBinding(descriptor, publishedSet); } private static AuthoredWorldLaunchDescriptorEvidence unpinnedDescriptor( @@ -580,6 +559,16 @@ private static Fixture fixture( Objects.requireNonNull( transactions.execute(status -> sourceRepository.register(UUID.randomUUID(), source)), "registered fresh source receipt"); + FreshGameSessionTenantAssociation tenantAssociation = + Objects.requireNonNull( + transactions.execute( + status -> + tenantRepository.associateFresh( + UUID.randomUUID(), + namespace, + sourceReceipt, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))), + "fresh tenant association"); var createCatalog = new CreateCanonicalRealmCatalogRequest( UUID.randomUUID(), @@ -591,18 +580,23 @@ private static Fixture fixture( true, true, "SHARED", - "explicit-policy-v1", + "PRESEEDED_ONLY", null, null); - var preparedCatalog = catalogRepository.prepareInitialPublicProduction(createCatalog); + var publishedSet = + CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + createCatalog, + source, + CANONICAL_VERSION, + 19L, + "original-association-publication", + "immutable-release-ref", + "generation-1", + 5L); + var preparedCatalog = + catalogRepository.prepareInitialPublicProduction(createCatalog, publishedSet); transactions.executeWithoutResult( status -> catalogRepository.createInitialPublicProduction(preparedCatalog)); - FreshGameSessionTenantAssociation tenantAssociation = - Objects.requireNonNull( - transactions.execute( - status -> - tenantRepository.associateFresh(UUID.randomUUID(), namespace, sourceReceipt)), - "fresh tenant association"); return new Fixture( namespace, tenantId, @@ -614,7 +608,9 @@ private static Fixture fixture( startingRepository, new CanonicalGameInstanceLaunchAssociationRepository(dsl, namespace), source, - tenantAssociation); + tenantAssociation, + publishedSet, + ownerClaimLease); } private record Fixture( @@ -628,34 +624,16 @@ private record Fixture( GameSessionCanonicalStartingInstanceRepository starting, CanonicalGameInstanceLaunchAssociationRepository reads, AuthoredWorldSourceEvidence source, - FreshGameSessionTenantAssociation tenantAssociation) { + FreshGameSessionTenantAssociation tenantAssociation, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + Duration ownerClaimLease) { OwnerBackedStarting startWithOwnerPins(StartSessionPostAuthorizationExecutionTuple tuple) { - ReservationResult reservation = - Objects.requireNonNull(transactions.execute(status -> attempts.reserve(tuple))); - AttemptClaim claim = reservation.claim().orElseThrow(); - var projection = - GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection(tuple); - transactions.executeWithoutResult( - status -> attempts.attachAccountRedemptionProjection(claim, projection)); - var initial = - GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.result( - tuple, claim, new InitialConfigured(), UUID.randomUUID()); - PinnedAssociationSnapshot pinnedAssociation = - Objects.requireNonNull( - transactions.execute( - status -> templateAssociations.pinInitialOrValidateExactReplay(claim, initial))); - var resolved = - GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.descriptorFor( - pinnedAssociation.result(), "original-start-session-descriptor"); - transactions.executeWithoutResult(status -> descriptors.pin(claim, resolved)); - var descriptor = - ((net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec - .DescriptorOutcome) - resolved.outcome()) - .descriptor(); + var descriptor = unpinnedDescriptor(tuple, source); var binding = - completeBinding( - descriptor, pinnedAssociation.result().association().canonicalVersionId()); + completeBinding(descriptor, publishedSet.target().canonicalVersionId(), publishedSet); + AttemptClaim claim = + CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( + dsl, transactions, tuple, source, publishedSet, binding, ownerClaimLease); StartingInstance startingInstance = Objects.requireNonNull( transactions.execute( @@ -665,7 +643,8 @@ OwnerBackedStarting startWithOwnerPins(StartSessionPostAuthorizationExecutionTup binding, tuple.preAuthorizationTuple().action().target().ownerAccountId(), tuple.controlPlaneRequestId(), - "f".repeat(64)))); + tuple.mutationDigest(), + tuple))); return new OwnerBackedStarting(startingInstance, claim); } @@ -681,7 +660,7 @@ OwnerBackedStarting startWithOwnerAttemptWithoutPins( GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection( tuple))); var descriptor = unpinnedDescriptor(tuple, source); - var binding = completeBinding(descriptor, CANONICAL_VERSION); + var binding = completeBinding(descriptor, CANONICAL_VERSION, publishedSet); StartingInstance startingInstance = Objects.requireNonNull( transactions.execute( @@ -691,13 +670,14 @@ OwnerBackedStarting startWithOwnerAttemptWithoutPins( binding, tuple.preAuthorizationTuple().action().target().ownerAccountId(), tuple.controlPlaneRequestId(), - "f".repeat(64)))); + tuple.mutationDigest(), + tuple))); return new OwnerBackedStarting(startingInstance, claim); } StartingInstance startWithoutOwnerPins(StartSessionPostAuthorizationExecutionTuple tuple) { var descriptor = unpinnedDescriptor(tuple, source); - var binding = completeBinding(descriptor, CANONICAL_VERSION); + var binding = completeBinding(descriptor, CANONICAL_VERSION, publishedSet); return Objects.requireNonNull( transactions.execute( status -> @@ -706,7 +686,8 @@ StartingInstance startWithoutOwnerPins(StartSessionPostAuthorizationExecutionTup binding, tuple.preAuthorizationTuple().action().target().ownerAccountId(), tuple.controlPlaneRequestId(), - "f".repeat(64)))); + tuple.mutationDigest(), + tuple))); } java.util.Optional read( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..4ede003816 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java @@ -0,0 +1,985 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +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.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.FixtureCanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.FixtureCanonicalRealmCatalog; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +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.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for the current verified-fixture source, fresh association, catalog, and + * STARTING launch owners. The upstream GDS receipt and fixture-policy seal are controlled test-only + * inputs parsed by the production closed parser; this does not create Human terminal or Account + * protection rows, activate a runtime, write World state, or claim a genuine owner handoff. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest { + private static final String NAMESPACE = + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE; + private static final long SOURCE_GAME_ROW_ID = 919L; + private static final String SOURCE_GAME_TENANT_KEY = "919"; + private static final long GAME_TEMPLATE_ID = 301L; + private static final long OWNER_ACCOUNT_ID = 401L; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void allocatesOneStartingLaunchWithExactPolicyAndIndependentOwnerReadback() throws Exception { + Fixture fixture = fixture(); + AuthoredWorldSourceEvidence source = source(SOURCE_GAME_ROW_ID); + RunOwnedInitialAdmissionLaunchEvidence evidence = launchEvidence(source, OWNER_ACCOUNT_ID); + UUID fixtureOperationId = UUID.fromString(evidence.fixtureCapability().operationId()); + IntakeReceipt sourceReceipt = + Objects.requireNonNull( + fixture.transactions.execute( + status -> fixture.sourceRepository.register(fixtureOperationId, source)), + "registered test-only GDS source receipt"); + assertThat(fixture.sourceRepository.readByIntakeRequest(NAMESPACE, fixtureOperationId)) + .contains(sourceReceipt); + + FreshGameSessionTenantAssociation freshAssociation = + Objects.requireNonNull( + fixture.transactions.execute( + status -> + fixture.tenantAssociationRepository.associateFresh( + associationOperationId(source), + NAMESPACE, + sourceReceipt, + evidence.creationEvidence())), + "actual Game Session fresh private-tenant allocation"); + assertThat(freshAssociation.legacyGameSessionTenantId()).isPositive(); + assertThat(freshAssociation.sourceEvidence().sourceGameRowId()) + .isEqualTo(source.sourceGameRowId()); + assertThat(freshAssociation.sourceEvidence().sourceGameTenantKey()) + .isEqualTo(source.sourceGameTenantKey()); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + FixtureCanonicalInstanceLaunch first; + FixtureCanonicalInstanceLaunch second; + try { + Future firstAttempt = + executor.submit(() -> contender(fixture, evidence, ready, start)); + Future secondAttempt = + executor.submit(() -> contender(fixture, evidence, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + first = firstAttempt.get(30, TimeUnit.SECONDS); + second = secondAttempt.get(30, TimeUnit.SECONDS); + } finally { + executor.shutdownNow(); + } + + assertThat(second).isEqualTo(first); + FixtureCanonicalInstanceLaunch replay = + fixture.launchRepository.createVerifiedFixtureStartingLaunch(evidence); + assertThat(replay).isEqualTo(first); + FixtureCanonicalInstanceLaunch independentReadback = + fixture.launchRepository.readVerifiedFixtureLaunch(evidence); + assertThat(independentReadback).isEqualTo(first); + assertThat(first.status()) + .isEqualTo( + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(first.rowVersion()).isZero(); + assertThat(first.gameInstanceId()).isPositive(); + assertThat(first.gameInstanceUuid()).isNotEqualTo(new UUID(0L, 0L)); + + FixtureCanonicalRealmCatalog catalog = first.catalog(); + assertThat(catalog.snapshot().catalogRevision()).isPositive(); + assertThat(catalog.snapshot().sourceIntakeReceipt()).isEqualTo(sourceReceipt); + assertThat(catalog.association().sourceEvidence()).isEqualTo(evidence.creationEvidence()); + assertThat(catalog.association().gameSessionTenantId()) + .isEqualTo(freshAssociation.legacyGameSessionTenantId()); + + var sealedPolicy = + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes( + evidence.fixturePolicyRequestBytes()); + assertThat(sealedPolicy.sourceEvidence()).isEqualTo(source); + assertThat(sealedPolicy.creationEvidence()).isEqualTo(evidence.creationEvidence()); + assertThat(sealedPolicy.launchReadEvidence().publishedReleaseBundle()) + .isEqualTo(evidence.publishedReleaseBundle()); + assertThat(sealedPolicy.launchReadEvidence().versionAssetArtifactState()) + .isEqualTo(evidence.versionAssetArtifactState()); + assertThat(sealedPolicy.launchReadEvidence().versionState()).isEqualTo(evidence.versionState()); + assertThat(sealedPolicy.launchReadEvidence().launchDescriptor()) + .isEqualTo(evidence.launchDescriptor()); + + Record catalogRow = + requiredRecord( + fixture.dsl, + "SELECT source_game_row_id, source_game_tenant_key, fixture_policy_request_bytes, " + + "fixture_policy_seal_operation_id, " + + "fixture_policy_seal_request_digest, fixture_policy_seal_evidence_digest " + + "FROM game_session_canonical_realm_catalog WHERE target_namespace = ? " + + "AND creation_request_id = ?", + NAMESPACE, + fixtureOperationId); + assertThat(catalogRow.get("source_game_row_id", Long.class)) + .isEqualTo(source.sourceGameRowId()); + assertThat(catalogRow.get("source_game_tenant_key", String.class)) + .isEqualTo(source.sourceGameTenantKey()); + assertThat(catalogRow.get("fixture_policy_request_bytes", byte[].class)) + .containsExactly(evidence.fixturePolicyRequestBytes()); + assertThat(catalogRow.get("fixture_policy_seal_operation_id", UUID.class)) + .isEqualTo(evidence.fixturePolicySeal().operationId()); + assertThat(catalogRow.get("fixture_policy_seal_request_digest", String.class)) + .isEqualTo(evidence.fixturePolicySeal().requestDigest()); + assertThat(catalogRow.get("fixture_policy_seal_evidence_digest", String.class)) + .isEqualTo(evidence.fixturePolicySeal().evidenceDigest()); + + Record launchRow = + requiredRecord( + fixture.dsl, + "SELECT game_session_tenant_id, game_instance_id, game_instance_uuid, " + + "catalog_creation_request_id, catalog_revision, fixture_policy_request_bytes, " + + "fixture_policy_seal_operation_id, fixture_policy_seal_request_digest, " + + "fixture_policy_seal_evidence_digest FROM game_session_canonical_instance_launch " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + NAMESPACE, + fixtureOperationId.toString()); + assertThat(launchRow.get("game_session_tenant_id", Long.class)) + .isEqualTo(freshAssociation.legacyGameSessionTenantId()); + assertThat(launchRow.get("game_instance_id", Long.class)).isEqualTo(first.gameInstanceId()); + assertThat(launchRow.get("game_instance_uuid", UUID.class)).isEqualTo(first.gameInstanceUuid()); + assertThat(launchRow.get("catalog_creation_request_id", UUID.class)) + .isEqualTo(catalog.snapshot().creationRequestId()); + assertThat(launchRow.get("catalog_revision", Long.class)) + .isEqualTo(catalog.snapshot().catalogRevision()); + assertThat(launchRow.get("fixture_policy_request_bytes", byte[].class)) + .containsExactly(evidence.fixturePolicyRequestBytes()); + assertThat(launchRow.get("fixture_policy_seal_operation_id", UUID.class)) + .isEqualTo(evidence.fixturePolicySeal().operationId()); + assertThat(launchRow.get("fixture_policy_seal_request_digest", String.class)) + .isEqualTo(evidence.fixturePolicySeal().requestDigest()); + assertThat(launchRow.get("fixture_policy_seal_evidence_digest", String.class)) + .isEqualTo(evidence.fixturePolicySeal().evidenceDigest()); + + Record runtime = + requiredRecord( + fixture.dsl, + "SELECT tenant_id, id, game_instance_uuid, owner_account_id, status, row_version, " + + "game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "generation_config_revision, version_state_epoch, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref " + + "FROM game_instances WHERE tenant_id = ? AND id = ?", + freshAssociation.legacyGameSessionTenantId(), + first.gameInstanceId()); + assertThat(runtime.get("game_instance_uuid", UUID.class)).isEqualTo(first.gameInstanceUuid()); + assertThat(runtime.get("owner_account_id", Long.class)) + .isEqualTo(evidence.fixtureCapability().ownerAccountId()); + assertThat(runtime.get("status", String.class)).isEqualTo("STARTING"); + assertThat(runtime.get("row_version", Long.class)).isZero(); + assertThat(runtime.get("game_template_id", Long.class)).isEqualTo(evidence.gameTemplateId()); + assertThat(runtime.get("launch_descriptor_id", String.class)) + .isEqualTo(evidence.launchDescriptor().getLaunchDescriptorId()); + assertThat(runtime.get("version_id", Long.class)) + .isEqualTo(evidence.publishedReleaseBundle().getVersionId()); + assertThat(runtime.get("release_bundle_id", Long.class)) + .isEqualTo(evidence.publishedReleaseBundle().getId()); + assertThat(runtime.get("generation_config_revision", String.class)) + .isEqualTo(evidence.publishedReleaseBundle().getGenerationConfigRevision()); + assertThat(runtime.get("version_state_epoch", Long.class)) + .isEqualTo(evidence.versionState().getVersionStateEpoch()) + .isPositive(); + assertThat(runtime.get("run_owned_start_request_id", String.class)) + .isEqualTo(evidence.fixtureCapability().operationId()); + assertThat(runtime.get("run_owned_start_request_digest", String.class)) + .isEqualTo(evidence.fixtureRuntimeRequestDigest()); + assertThat(runtime.get("run_owned_start_published_release_bundle_ref", String.class)) + .isEqualTo(evidence.publishedReleaseBundle().getPublishedReleaseBundleRef()); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_authored_world_source_intake")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_scope_reservation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_tenant_canonical_claim")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); + + OwnerRows beforeNakedInsert = ownerRows(fixture, evidence, first.gameInstanceId()); + assertThatThrownBy(() -> insertNakedCatalogRow(fixture, evidence)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining( + "New canonical realm requires exactly one complete Human or verified fixture policy provenance"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat(ownerRows(fixture, evidence, first.gameInstanceId())).isEqualTo(beforeNakedInsert); + + OwnerRows originalRows = ownerRows(fixture, evidence, first.gameInstanceId()); + AuthoredWorldSourceEvidence changedSource = source(SOURCE_GAME_ROW_ID + 1L); + RunOwnedInitialAdmissionLaunchEvidence changedSourceEvidence = + launchEvidence(changedSource, OWNER_ACCOUNT_ID); + assertThatThrownBy( + () -> + fixture.launchRepository.createVerifiedFixtureStartingLaunch(changedSourceEvidence)) + .isInstanceOf(InvalidFreshTenantAssociationException.class) + .hasMessageContaining("complete original Game Design receipt"); + assertThat(ownerRows(fixture, evidence, first.gameInstanceId())).isEqualTo(originalRows); + + RunOwnedInitialAdmissionLaunchEvidence changedPolicyEvidence = + launchEvidence(source, OWNER_ACCOUNT_ID + 1L); + assertThatThrownBy( + () -> + fixture.launchRepository.createVerifiedFixtureStartingLaunch(changedPolicyEvidence)) + .isInstanceOf(GameSessionCanonicalRealmCatalogRepository.CatalogConflictException.class) + .hasMessageContaining("reused with changed input or source evidence"); + assertThat(ownerRows(fixture, evidence, first.gameInstanceId())).isEqualTo(originalRows); + } + + @Test + void retriesCanonicalLaunchAfterAdvisoryWaitWithRepeatableReadDatasourceDefault() + throws Exception { + Fixture fixture = fixtureWithRepeatableReadDefault(); + AuthoredWorldSourceEvidence source = source(SOURCE_GAME_ROW_ID); + RunOwnedInitialAdmissionLaunchEvidence evidence = launchEvidence(source, OWNER_ACCOUNT_ID); + FixtureCanonicalRealmCatalog preparedCatalog = + fixture.catalogRepository.establishVerifiedFixtureRealm(evidence); + assertThat( + Objects.requireNonNull( + fixture.dsl.fetchOne("SHOW default_transaction_isolation"), + "PostgreSQL did not return the datasource transaction isolation setting") + .get(0, String.class)) + .isEqualTo("repeatable read"); + assertThat(fixture.catalogRepository.readVerifiedFixtureRealm(evidence)) + .isEqualTo(preparedCatalog); + + String lockKey = + "canonical-launch:" + NAMESPACE + ":" + evidence.fixtureCapability().operationId(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try (Connection lockConnection = fixture.dataSource.getConnection()) { + boolean lockHeld = false; + try { + try (PreparedStatement acquire = + lockConnection.prepareStatement("SELECT pg_advisory_lock(hashtextextended(?, 0))")) { + acquire.setString(1, lockKey); + acquire.execute(); + lockHeld = true; + } + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + Future firstAttempt = + executor.submit(() -> contender(fixture, evidence, ready, start)); + Future secondAttempt = + executor.submit(() -> contender(fixture, evidence, ready, start)); + assertThat(ready.await(15, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + awaitAdvisoryWaiters(fixture, lockKey, 2); + + try (PreparedStatement release = + lockConnection.prepareStatement("SELECT pg_advisory_unlock(hashtextextended(?, 0))")) { + release.setString(1, lockKey); + try (var result = release.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getBoolean(1)).isTrue(); + } + lockHeld = false; + } + + FixtureCanonicalInstanceLaunch first = firstAttempt.get(30, TimeUnit.SECONDS); + FixtureCanonicalInstanceLaunch second = secondAttempt.get(30, TimeUnit.SECONDS); + assertThat(second).isEqualTo(first); + assertThat(first.status()) + .isEqualTo( + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + + OwnerRows committedRows = ownerRows(fixture, evidence, first.gameInstanceId()); + assertThat(fixture.launchRepository.readVerifiedFixtureLaunch(evidence)).isEqualTo(first); + assertThat(fixture.launchRepository.createVerifiedFixtureStartingLaunch(evidence)) + .isEqualTo(first); + assertThat(ownerRows(fixture, evidence, first.gameInstanceId())).isEqualTo(committedRows); + } finally { + if (lockHeld) { + try (PreparedStatement release = + lockConnection.prepareStatement( + "SELECT pg_advisory_unlock(hashtextextended(?, 0))")) { + release.setString(1, lockKey); + release.execute(); + } + } + } + } finally { + executor.shutdownNow(); + } + } + + private static void awaitAdvisoryWaiters(Fixture fixture, String lockKey, int expectedWaiters) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); + while (System.nanoTime() < deadline) { + Long waiting = + Objects.requireNonNull( + fixture.dsl.fetchOne( + "SELECT count(*) FROM pg_locks WHERE locktype = 'advisory' " + + "AND NOT granted AND objsubid = 1 " + + "AND classid = (((hashtextextended(?, 0) >> 32) & 4294967295)::oid) " + + "AND objid = ((hashtextextended(?, 0) & 4294967295)::oid)", + lockKey, + lockKey), + "PostgreSQL did not return the advisory-lock waiter count") + .get(0, Long.class); + if (waiting == expectedWaiters) return; + try { + Thread.sleep(10); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while awaiting canonical launch advisory-lock waiters", interrupted); + } + } + throw new AssertionError( + "Both canonical launch calls did not wait on the original advisory lock"); + } + + private static FixtureCanonicalInstanceLaunch contender( + Fixture fixture, + RunOwnedInitialAdmissionLaunchEvidence evidence, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent canonical launch gate was not released"); + } + return fixture.launchRepository.createVerifiedFixtureStartingLaunch(evidence); + } + + @Test + void forwardHumanPolicyGuardPreservesActualV1011HistoryAndRejectsLegacyCatalogReuse() { + Fixture fixture = fixture("1003"); + var source = source(SOURCE_GAME_ROW_ID); + var evidence = launchEvidence(source, OWNER_ACCOUNT_ID); + var receipt = registerAndAssociate(fixture, source, evidence); + UUID realmId = uuid(1101); + insertHistoricalCatalog(fixture, receipt, realmId); + migrate(fixture, "1011").load().migrate(); + insertHumanLaunch(fixture, receipt, realmId, "retained-human-launch"); + var before = retainedLaunchCatalogRows(fixture); + Record triggerBefore = launchTriggerIdentity(fixture); + + migrate(fixture, null).load().migrate(); + + assertThat(retainedLaunchCatalogRows(fixture)).isEqualTo(before); + assertThat(launchTriggerIdentity(fixture)).isEqualTo(triggerBefore); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT count(*) FROM flyway_schema_history WHERE version = '1011.1' AND success") + .get(0, Long.class)) + .isEqualTo(1L); + assertThatThrownBy( + () -> insertHumanLaunch(fixture, receipt, realmId, "new-legacy-human-launch")) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "Launch provenance differs from the exact retained canonical catalog owner"); + assertThat(retainedLaunchCatalogRows(fixture)).isEqualTo(before); + } + + @Test + void forwardHumanPolicyGuardAcceptsCompletePublishedCatalog() { + Fixture fixture = fixture(); + var source = source(SOURCE_GAME_ROW_ID); + var evidence = launchEvidence(source, OWNER_ACCOUNT_ID); + var receipt = registerAndAssociate(fixture, source, evidence); + var request = + new net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest( + uuid(1102), + NAMESPACE, + source.canonicalTenantId(), + receipt.operationId(), + "human-production", + "Human Production", + true, + true, + "SHARED", + "PRESEEDED_ONLY", + null, + null); + var policy = + CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + request, + source, + uuid(1103), + 72L, + "human-policy-publication", + "human-release-bundle", + "generation-1", + 3L); + var prepared = fixture.catalogRepository.prepareInitialPublicProduction(request, policy); + var catalog = + Objects.requireNonNull( + fixture.transactions.execute( + status -> fixture.catalogRepository.createInitialPublicProduction(prepared))); + insertHumanLaunch(fixture, receipt, catalog.realmId(), "complete-human-launch"); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch")))) + .isEqualTo(1); + } + + private static IntakeReceipt registerAndAssociate( + Fixture fixture, + AuthoredWorldSourceEvidence source, + RunOwnedInitialAdmissionLaunchEvidence evidence) { + var receipt = + Objects.requireNonNull( + fixture.transactions.execute( + status -> + fixture.sourceRepository.register( + UUID.fromString(evidence.fixtureCapability().operationId()), source))); + fixture.transactions.executeWithoutResult( + status -> + fixture.tenantAssociationRepository.associateFresh( + associationOperationId(source), NAMESPACE, receipt, evidence.creationEvidence())); + return receipt; + } + + private static java.util.List retainedLaunchCatalogRows(Fixture fixture) { + return fixture + .dsl + .fetch( + "SELECT 'catalog' AS kind, xmin::text AS xmin, to_jsonb(owner_row)::text AS bytes " + + "FROM game_session_canonical_realm_catalog owner_row UNION ALL " + + "SELECT 'launch', xmin::text, to_jsonb(owner_row)::text " + + "FROM game_session_canonical_instance_launch owner_row ORDER BY kind, bytes") + .map(row -> row.get("kind") + "/" + row.get("xmin") + "/" + row.get("bytes")); + } + + private static Record launchTriggerIdentity(Fixture fixture) { + return fixture.dsl.fetchSingle( + "SELECT oid, tgname, tgfoid, tgtype, tgenabled FROM pg_trigger " + + "WHERE tgrelid = 'game_session_canonical_instance_launch'::regclass " + + "AND tgname = 'gs_canonical_instance_launch_complete_catalog_identity'"); + } + + private static void insertHistoricalCatalog( + Fixture fixture, IntakeReceipt receipt, UUID realmId) { + var intake = + requiredRecord( + fixture.dsl, + "SELECT * FROM game_session_authored_world_source_intake WHERE operation_id = ?", + receipt.operationId()); + var columns = new java.util.LinkedHashMap(); + for (String field : + java.util.List.of( + "target_namespace", + "canonical_tenant_id", + "tenant_slug", + "world_slug", + "source_schema_version", + "source_registration_request_id", + "source_operation_id", + "source_request_digest", + "source_game_row_id", + "source_game_tenant_key", + "source_provenance_kind", + "source_evidence_digest")) { + columns.put(field, intake.get(field)); + } + columns.put("realm_id", realmId); + columns.put("realm_slug", "historical-production"); + columns.put("realm_display_name", "Historical Production"); + columns.put("visible", true); + columns.put("public_production", true); + columns.put("state_scope", "SHARED"); + columns.put("playable_state_namespace_id", uuid(1104)); + columns.put("character_creation_policy", "ALLOW_NEW"); + columns.put("catalog_revision", 1L); + columns.put("creation_request_id", uuid(1105)); + var source = receipt.source(); + UUID creationId = uuid(1105); + String requestDigest = + CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( + "game-session-canonical-realm-catalog-request/v1", + "1", + creationId.toString(), + NAMESPACE, + source.canonicalTenantId().toString(), + receipt.operationId().toString(), + receipt.intakeRequestId().toString(), + receipt.requestDigest(), + receipt.receiptDigest(), + Integer.toString(source.schemaVersion()), + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + "historical-production", + "Historical Production", + "true", + "true", + "SHARED", + "ALLOW_NEW", + "ABSENT", + "ABSENT"); + columns.put("request_digest", requestDigest); + columns.put( + "receipt_digest", + CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( + "game-session-canonical-realm-catalog-receipt/v1", + "1", + NAMESPACE, + source.canonicalTenantId().toString(), + creationId.toString(), + requestDigest, + realmId.toString(), + uuid(1104).toString(), + "1", + receipt.operationId().toString(), + receipt.receiptDigest())); + columns.put("source_intake_operation_id", receipt.operationId()); + columns.put("source_intake_schema_version", 1); + columns.put("source_intake_request_id", receipt.intakeRequestId()); + columns.put("source_intake_request_digest", receipt.requestDigest()); + columns.put("source_intake_receipt_digest", receipt.receiptDigest()); + columns.put("source_world_display_name", receipt.source().worldDisplayName()); + var namespace = new java.util.LinkedHashMap(); + for (var entry : columns.entrySet()) { + String field = entry.getKey(); + if (field.equals("target_namespace") + || field.equals("canonical_tenant_id") + || field.equals("playable_state_namespace_id") + || field.startsWith("source_") && !field.equals("source_world_display_name")) { + namespace.put(field, entry.getValue()); + } + } + fixture.transactions.executeWithoutResult( + status -> { + insertOwnerRow(fixture, "gameplay_tenant_shared_playable_state_namespace", namespace); + insertOwnerRow(fixture, "game_session_canonical_realm_catalog", columns); + }); + } + + private static void insertHumanLaunch( + Fixture fixture, IntakeReceipt receipt, UUID realmId, String requestId) { + var fresh = + requiredRecord( + fixture.dsl, + "SELECT * FROM game_session_fresh_tenant_association WHERE canonical_tenant_id = ?", + receipt.source().canonicalTenantId()); + var catalog = + requiredRecord( + fixture.dsl, + "SELECT * FROM game_session_canonical_realm_catalog WHERE realm_id = ?", + realmId); + UUID instanceUuid = UUID.randomUUID(); + var tuple = + CanonicalHumanPublicationOwnerTestFixtures.tuple( + NAMESPACE, + receipt.source().canonicalTenantId(), + uuid(Math.toIntExact(OWNER_ACCOUNT_ID)), + GAME_TEMPLATE_ID, + requestId); + fixture.transactions.executeWithoutResult( + status -> { + long instanceId = + fixture + .dsl + .fetchSingle( + "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, status, row_version, " + + "game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "generation_config_revision, version_state_epoch, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref) " + + "VALUES (?, '72', ?, 'STARTING', 0, ?, ?, 'human-launch-descriptor', 72, 73, 'generation-1', " + + "3, ?, ?, 'human-release-bundle') RETURNING id", + fresh.get("legacy_game_session_tenant_id"), + OWNER_ACCOUNT_ID, + instanceUuid, + GAME_TEMPLATE_ID, + requestId, + tuple.mutationDigest()) + .get("id", Long.class); + var columns = new java.util.LinkedHashMap(); + columns.put("target_namespace", NAMESPACE); + columns.put("control_plane_request_id", requestId); + columns.put("game_session_tenant_id", fresh.get("legacy_game_session_tenant_id")); + columns.put("canonical_tenant_id", receipt.source().canonicalTenantId()); + for (String field : + java.util.List.of( + "association_operation_id", + "association_request_id", + "source_schema_version", + "source_target_namespace", + "source_request_id", + "source_canonical_tenant_id", + "source_game_row_id", + "source_game_tenant_key", + "source_provenance_kind", + "association_kind")) { + String target = "tenant_" + field; + if (field.equals("source_provenance_kind")) { + columns.put(target, fresh.get("provenance_kind")); + } else { + columns.put(target, fresh.get(field)); + } + } + columns.put("game_instance_id", instanceId); + columns.put("game_instance_uuid", instanceUuid); + columns.put("canonical_realm_id", realmId); + columns.put("world_slug", catalog.get("world_slug")); + columns.put("playable_state_namespace_id", catalog.get("playable_state_namespace_id")); + columns.put("playable_state_scope", catalog.get("state_scope")); + columns.put("public_production", true); + columns.put("captured_starting_row_version", 0L); + columns.put("game_template_id", GAME_TEMPLATE_ID); + columns.put("launch_descriptor_id", "human-launch-descriptor"); + columns.put("version_id", 72L); + columns.put("release_bundle_id", 73L); + columns.put("generation_config_revision", "generation-1"); + columns.put("version_state_epoch", 3L); + // Guard-level SQL input; the full Human launch binding remains separately + // owner-validated. + String bindingJson = + String.format( + "{\"descriptor\":{\"targetNamespace\":\"%s\",\"controlPlaneRequestId\":\"%s\"," + + "\"canonicalTenantId\":\"%s\",\"worldSlug\":\"%s\",\"gameTemplateId\":%d," + + "\"launchDescriptorId\":\"human-launch-descriptor\",\"versionId\":72,\"releaseBundleId\":73," + + "\"generationConfigRevision\":\"generation-1\",\"versionStateEpoch\":3," + + "\"publishedReleaseBundleRef\":\"human-release-bundle\"},\"releaseAttestation\":{}}", + NAMESPACE, + requestId, + receipt.source().canonicalTenantId(), + catalog.get("world_slug"), + GAME_TEMPLATE_ID); + columns.put("complete_launch_binding_evidence", org.jooq.JSONB.valueOf(bindingJson)); + columns.put("original_start_session_tuple", tuple.canonicalBytes()); + columns.put("catalog_creation_request_id", catalog.get("creation_request_id")); + columns.put("catalog_revision", catalog.get("catalog_revision")); + columns.put("catalog_source_intake_operation_id", receipt.operationId()); + columns.put("catalog_source_intake_request_id", receipt.intakeRequestId()); + insertOwnerRow(fixture, "game_session_canonical_instance_launch", columns); + }); + } + + private static void insertOwnerRow( + Fixture fixture, String table, java.util.Map columns) { + fixture + .dsl + .insertInto(DSL.table(DSL.name(table))) + .columns(columns.keySet().stream().map(field -> DSL.field(DSL.name(field))).toList()) + .values(columns.values()) + .execute(); + } + + private static org.flywaydb.core.api.configuration.FluentConfiguration migrate( + Fixture fixture, String target) { + var configuration = + Flyway.configure() + .dataSource(fixture.dataSource) + .schemas(fixture.schema) + .defaultSchema(fixture.schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (target != null) configuration.target(target); + return configuration; + } + + private static void insertNakedCatalogRow( + Fixture fixture, RunOwnedInitialAdmissionLaunchEvidence evidence) { + FixtureCanonicalRealmCatalog catalog = + fixture.catalogRepository.readVerifiedFixtureRealm(evidence); + IntakeReceipt sourceReceipt = catalog.snapshot().sourceIntakeReceipt(); + fixture.dsl.execute( + "INSERT INTO game_session_canonical_realm_catalog " + + "(target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id, " + + "realm_slug, realm_display_name, visible, public_production, state_scope, " + + "playable_state_namespace_id, character_creation_policy, catalog_revision, " + + "creation_request_id, request_digest, receipt_digest, source_intake_operation_id, " + + "source_intake_schema_version, source_intake_request_id, source_intake_request_digest, " + + "source_intake_receipt_digest, source_schema_version, source_registration_request_id, " + + "source_operation_id, source_request_digest, source_world_display_name, " + + "source_game_row_id, source_game_tenant_key, source_provenance_kind, " + + "source_evidence_digest) " + + "SELECT intake.target_namespace, intake.canonical_tenant_id, intake.tenant_slug, " + + "intake.world_slug, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, intake.operation_id, " + + "intake.schema_version, intake.intake_request_id, intake.request_digest, " + + "intake.receipt_digest, intake.source_schema_version, " + + "intake.source_registration_request_id, intake.source_operation_id, " + + "intake.source_request_digest, intake.world_display_name, intake.source_game_row_id, " + + "intake.source_game_tenant_key, intake.source_provenance_kind, " + + "intake.source_evidence_digest FROM game_session_authored_world_source_intake intake " + + "WHERE intake.operation_id = ?", + UUID.randomUUID(), + "naked-realm", + "Naked Realm", + evidence.fixtureCapability().visible(), + evidence.fixtureCapability().publicProductionRealm(), + evidence.fixtureCapability().stateScope(), + catalog.snapshot().playableStateNamespaceId(), + evidence.fixtureCapability().characterCreationPolicy(), + UUID.randomUUID(), + "sha256:" + "0".repeat(64), + "sha256:" + "1".repeat(64), + sourceReceipt.operationId()); + } + + private static OwnerRows ownerRows( + Fixture fixture, RunOwnedInitialAdmissionLaunchEvidence evidence, long gameInstanceId) { + UUID fixtureOperationId = UUID.fromString(evidence.fixtureCapability().operationId()); + return new OwnerRows( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_authored_world_source_intake"))), + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_fresh_tenant_association"))), + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog"))), + fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances"))), + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_instance_launch"))), + xmin( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_authored_world_source_intake " + + "WHERE intake_request_id = ?", + fixtureOperationId), + xmin( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_fresh_tenant_association " + + "WHERE association_request_id = ?", + evidence.creationEvidence().creationRequestId()), + xmin( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + fixtureOperationId), + xmin( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_instances WHERE id = ?", + gameInstanceId), + xmin( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_instance_launch " + + "WHERE control_plane_request_id = ?", + fixtureOperationId.toString())); + } + + private static String xmin(DSLContext dsl, String sql, Object selector) { + return requiredRecord(dsl, sql, selector).get("xmin", String.class); + } + + private static AuthoredWorldSourceEvidence source(long sourceGameRowId) { + UUID canonicalTenantId = uuid(1001); + UUID registrationRequestId = + UUID.fromString(RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId()); + UUID sourceOperationId = uuid(1002); + String tenantSlug = "run-owned-fixture-tenant"; + String worldSlug = RunOwnedInitialAdmissionFixtureWireCodec.WORLD_SLUG; + String displayName = RunOwnedInitialAdmissionFixtureWireCodec.WORLD_DISPLAY_NAME; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static RunOwnedInitialAdmissionLaunchEvidence launchEvidence( + AuthoredWorldSourceEvidence source, long ownerAccountId) { + // The closed GDS fixture receipt binds this controlled capability to the source-owner key. + // Game Session's private key comes from its association owner and is never selected here. + StartSessionRequest controlledCapabilityInput = + new StartSessionRequest( + Long.parseLong(source.sourceGameTenantKey()), + GAME_TEMPLATE_ID, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + ownerAccountId); + RunOwnedInitialAdmissionLaunchEvidence evidence = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create(controlledCapabilityInput, source); + assertThat(evidence.fixtureCapability().tenantId()) + .isEqualTo(Long.parseLong(source.sourceGameTenantKey())); + return evidence; + } + + private static UUID associationOperationId(AuthoredWorldSourceEvidence source) { + return UUID.nameUUIDFromBytes( + ("test-only-gs-fresh-association:" + source.canonicalTenantId()) + .getBytes(StandardCharsets.UTF_8)); + } + + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { + return Objects.requireNonNull(dsl.fetchOne(sql, bindings), "Expected committed owner row"); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static Fixture fixture() { + return fixture(null); + } + + private static Fixture fixture(String targetVersion) { + return fixture(targetVersion, false); + } + + private static Fixture fixtureWithRepeatableReadDefault() { + return fixture(null, true); + } + + private static Fixture fixture(String targetVersion, boolean repeatableReadDefault) { + String schema = "gs_run_owned_launch_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = + repeatableReadDefault + ? new DriverManagerDataSource() { + @Override + public Connection getConnection() throws SQLException { + Connection connection = super.getConnection(); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + return connection; + } + } + : new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + var migration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION); + if (targetVersion != null) migration.target(targetVersion); + migration.load().migrate(); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(dsl); + GameSessionFreshTenantAssociationRepository tenantAssociationRepository = + new GameSessionFreshTenantAssociationRepository(dsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + GameSessionCanonicalInstanceLaunchRepository launchRepository = + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogRepository); + return new Fixture( + dsl, + transactions, + sourceRepository, + tenantAssociationRepository, + catalogRepository, + launchRepository, + dataSource, + schema); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionFreshTenantAssociationRepository tenantAssociationRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalInstanceLaunchRepository launchRepository, + DriverManagerDataSource dataSource, + String schema) {} + + private record OwnerRows( + int sourceRows, + int associationRows, + int catalogRows, + int runtimeRows, + int launchRows, + String sourceXmin, + String associationXmin, + String catalogXmin, + String runtimeXmin, + String launchXmin) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java index 00cf7984dc..9695e472f7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -28,7 +28,11 @@ import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; -import net.firedevops.firemud.gamesession.repository.CanonicalGameplayBindingRuntimeTestFixtures; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository.PinnedLaunchDescriptorSnapshot; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; @@ -71,6 +75,7 @@ class GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest { private static final String WORKLOAD = "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final String V34_3_RAW_SHA256 = "a".repeat(64); private static final String MIGRATION_LOCATION = "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); private static final JsonMapper JSON = JsonMapper.builder().build(); @@ -96,25 +101,19 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); - var target = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dsl); - String catalogEvidenceBefore = - dsl.fetch( - "SELECT md5(to_jsonb(catalog)::text) FROM game_session_canonical_realm_catalog catalog" - + " WHERE target_namespace = ? AND canonical_tenant_id = ?", - target.targetNamespace(), - target.canonicalTenantId()) - .get(0) - .get(0, String.class); - String launchEvidenceBefore = - dsl.fetch( - "SELECT md5(to_jsonb(launch)::text) FROM game_session_canonical_instance_launch launch" - + " WHERE target_namespace = ? AND control_plane_request_id = ?", - target.targetNamespace(), - target.controlPlaneRequestId()) - .get(0) - .get(0, String.class); - assertThat(catalogEvidenceBefore).isNotBlank(); - assertThat(launchEvidenceBefore).isNotBlank(); + // These rows use the V34.3 predecessor shape and make no current-producer claim. + PriorRuntime target = seedV34_3PriorRuntime(dataSource, dsl); + // Later migrations add nullable columns, so compare all V23/V26 fields plus xmin directly. + PredecessorSnapshot catalogEvidenceBefore = catalogPredecessorSnapshot(dsl, target); + PredecessorSnapshot launchEvidenceBefore = launchPredecessorSnapshot(dsl, target); + String originalLaunchColumnsBefore = launchEvidenceBefore.originalColumns(); + String launchXminBefore = launchEvidenceBefore.xmin(); + String originalCatalogColumnsBefore = catalogEvidenceBefore.originalColumns(); + String catalogXminBefore = catalogEvidenceBefore.xmin(); + assertThat(originalCatalogColumnsBefore).isNotBlank(); + assertThat(catalogXminBefore).isNotBlank(); + assertThat(originalLaunchColumnsBefore).isNotBlank(); + assertThat(launchXminBefore).isNotBlank(); assertThat(dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); assertThat( dsl.fetch( @@ -140,24 +139,12 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr + " ORDER BY installed_rank") .getValues("version", String.class)) .containsExactly("35", "37", "38"); - assertThat( - dsl.fetch( - "SELECT md5(to_jsonb(catalog)::text) FROM game_session_canonical_realm_catalog catalog" - + " WHERE target_namespace = ? AND canonical_tenant_id = ?", - target.targetNamespace(), - target.canonicalTenantId()) - .get(0) - .get(0, String.class)) - .isEqualTo(catalogEvidenceBefore); - assertThat( - dsl.fetch( - "SELECT md5(to_jsonb(launch)::text) FROM game_session_canonical_instance_launch launch" - + " WHERE target_namespace = ? AND control_plane_request_id = ?", - target.targetNamespace(), - target.controlPlaneRequestId()) - .get(0) - .get(0, String.class)) - .isEqualTo(launchEvidenceBefore); + PredecessorSnapshot catalogEvidenceAfter = catalogPredecessorSnapshot(dsl, target); + assertThat(catalogEvidenceAfter.originalColumns()).isEqualTo(originalCatalogColumnsBefore); + assertThat(catalogEvidenceAfter.xmin()).isEqualTo(catalogXminBefore); + PredecessorSnapshot launchEvidenceAfter = launchPredecessorSnapshot(dsl, target); + assertThat(launchEvidenceAfter.originalColumns()).isEqualTo(originalLaunchColumnsBefore); + assertThat(launchEvidenceAfter.xmin()).isEqualTo(launchXminBefore); assertConstraintsReady( dsl, @@ -168,7 +155,8 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr "pk_gs_start_session_operator_attempt", "uq_gs_start_session_operator_attempt_id", "uq_gs_start_session_operator_fence", - "uq_gs_start_session_operator_mutation_id"); + "uq_gs_start_session_operator_mutation_id", + "uq_gs_start_session_operator_namespace_attempt"); assertConstraintsReady( dsl, "game_session_start_session_template_association_pin", @@ -214,6 +202,438 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr } } + private static PredecessorSnapshot catalogPredecessorSnapshot( + DSLContext dsl, PriorRuntime target) { + org.jooq.Record row = + dsl.fetchOne( + "SELECT row_to_json(ROW(catalog.target_namespace, catalog.canonical_tenant_id," + + " catalog.tenant_slug, catalog.world_slug, catalog.realm_id," + + " catalog.realm_slug, catalog.realm_display_name, catalog.visible," + + " catalog.public_production, catalog.state_scope," + + " catalog.playable_state_namespace_id, catalog.character_creation_policy," + + " catalog.catalog_revision, catalog.creation_request_id," + + " catalog.request_digest, catalog.receipt_digest," + + " catalog.source_intake_operation_id, catalog.source_intake_schema_version," + + " catalog.source_intake_request_id, catalog.source_intake_request_digest," + + " catalog.source_intake_receipt_digest, catalog.source_schema_version," + + " catalog.source_registration_request_id, catalog.source_operation_id," + + " catalog.source_request_digest, catalog.source_world_display_name," + + " catalog.source_game_row_id, catalog.source_game_tenant_key," + + " catalog.source_provenance_kind, catalog.source_evidence_digest," + + " catalog.created_at))::text AS original_columns, catalog.xmin::text AS xmin" + + " FROM game_session_canonical_realm_catalog catalog" + + " WHERE target_namespace = ? AND canonical_tenant_id = ?", + target.targetNamespace(), + target.canonicalTenantId()); + Objects.requireNonNull(row, "retained predecessor catalog row"); + return new PredecessorSnapshot( + row.get("original_columns", String.class), row.get("xmin", String.class)); + } + + private static PredecessorSnapshot launchPredecessorSnapshot( + DSLContext dsl, PriorRuntime target) { + org.jooq.Record row = + dsl.fetchOne( + "SELECT row_to_json(ROW(launch.target_namespace, launch.control_plane_request_id," + + " launch.game_session_tenant_id, launch.canonical_tenant_id," + + " launch.tenant_association_operation_id, launch.tenant_association_request_id," + + " launch.tenant_source_schema_version, launch.tenant_source_target_namespace," + + " launch.tenant_source_request_id, launch.tenant_source_canonical_tenant_id," + + " launch.tenant_source_game_row_id, launch.tenant_source_game_tenant_key," + + " launch.tenant_source_provenance_kind, launch.tenant_association_kind," + + " launch.game_instance_id, launch.game_instance_uuid, launch.canonical_realm_id," + + " launch.world_slug, launch.playable_state_namespace_id," + + " launch.playable_state_scope, launch.public_production," + + " launch.captured_starting_row_version, launch.game_template_id," + + " launch.launch_descriptor_id, launch.version_id, launch.release_bundle_id," + + " launch.generation_config_revision, launch.version_state_epoch," + + " launch.complete_launch_binding_evidence, launch.captured_at))::text" + + " AS original_columns, launch.xmin::text AS xmin" + + " FROM game_session_canonical_instance_launch launch" + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + target.targetNamespace(), + target.controlPlaneRequestId()); + Objects.requireNonNull(row, "retained predecessor launch row"); + return new PredecessorSnapshot( + row.get("original_columns", String.class), row.get("xmin", String.class)); + } + + private static PriorRuntime seedV34_3PriorRuntime( + DriverManagerDataSource dataSource, DSLContext dsl) { + String token = UUID.randomUUID().toString().replace("-", ""); + String shortToken = token.substring(0, 10); + String targetNamespace = "fixture-" + shortToken; + UUID canonicalTenantId = UUID.randomUUID(); + String tenantSlug = "tenant-" + shortToken; + String worldSlug = "world-" + shortToken; + String worldDisplayName = "Fixture World " + shortToken; + long sourceGameRowId = 50_023L; + String sourceGameTenantKey = "source-" + shortToken; + UUID sourceRegistrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + UUID sourceIntakeRequestId = UUID.randomUUID(); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + sourceRegistrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + sourceRegistrationRequestId, + sourceOperationId, + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + sourceRegistrationRequestId, + sourceOperationId, + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + IntakeReceipt sourceReceipt = + Objects.requireNonNull( + new TransactionTemplate(new DataSourceTransactionManager(dataSource)) + .execute( + status -> + new GameSessionAuthoredWorldSourceRepository(dsl) + .register(sourceIntakeRequestId, sourceEvidence)), + "registered V34.3 authored-world source through its owner"); + PriorRuntime target = + new PriorRuntime( + targetNamespace, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName, + UUID.randomUUID(), + "main", + "Main Realm", + 1L, + 23L, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + sourceGameRowId, + sourceGameTenantKey, + sourceReceipt.operationId(), + sourceReceipt.intakeRequestId(), + sourceEvidence.registrationRequestId(), + sourceEvidence.operationId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "descriptor-" + shortToken, + "generation-" + shortToken, + "launch-" + token, + "published-release-" + shortToken); + // The V22 source uses its owner above; remaining rows use only deployed V23/V26 columns. + dsl.transaction( + configuration -> { + DSLContext tx = DSL.using(configuration); + seedV34_3SourceAndCatalog(tx, target, sourceEvidence, sourceReceipt); + seedV34_3TenantAssociation(tx, target); + seedV34_3StartingRuntimeAndLaunch(tx, target); + tx.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + }); + return target; + } + + /** Writes only the catalog shape that existed before V35 owner provenance. */ + private static void seedV34_3SourceAndCatalog( + DSLContext tx, + PriorRuntime target, + AuthoredWorldSourceEvidence source, + IntakeReceipt sourceReceipt) { + tx.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace" + + " (tenant_id, playable_state_namespace_id, canonical_tenant_id, target_namespace," + + " source_intake_operation_id, source_intake_schema_version, source_intake_request_id," + + " source_intake_request_digest, source_intake_receipt_digest, source_schema_version," + + " source_registration_request_id, source_operation_id, source_request_digest," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind," + + " source_evidence_digest)" + + " VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', ?)", + target.playableStateNamespaceId(), + target.canonicalTenantId(), + target.targetNamespace(), + sourceReceipt.operationId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.requestDigest(), + sourceReceipt.receiptDigest(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.evidenceDigest()); + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + target.catalogCreationRequestId(), + target.targetNamespace(), + target.canonicalTenantId(), + sourceReceipt.operationId(), + target.realmSlug(), + target.realmDisplayName(), + true, + true, + "SHARED", + "PLAYER_CHOICE", + null, + null); + String catalogRequestDigest = v34_3CatalogRequestDigest(catalogRequest, sourceReceipt); + String catalogReceiptDigest = + v34_3CatalogReceiptDigest( + catalogRequest, + sourceReceipt, + target.realmId(), + target.playableStateNamespaceId(), + 1L, + catalogRequestDigest); + tx.execute( + "INSERT INTO game_session_canonical_realm_catalog" + + " (target_namespace, canonical_tenant_id, tenant_slug, world_slug, realm_id," + + " realm_slug, realm_display_name, visible, public_production, state_scope," + + " playable_state_namespace_id, character_creation_policy, catalog_revision," + + " creation_request_id, request_digest, receipt_digest, source_intake_operation_id," + + " source_intake_schema_version, source_intake_request_id, source_intake_request_digest," + + " source_intake_receipt_digest, source_schema_version, source_registration_request_id," + + " source_operation_id, source_request_digest, source_world_display_name," + + " source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, 'PLAYER_CHOICE', 1, ?, ?, ?," + + " ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + target.targetNamespace(), + target.canonicalTenantId(), + target.tenantSlug(), + target.worldSlug(), + target.realmId(), + target.realmSlug(), + target.realmDisplayName(), + target.playableStateNamespaceId(), + target.catalogCreationRequestId(), + catalogRequestDigest, + catalogReceiptDigest, + target.sourceIntakeOperationId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.requestDigest(), + sourceReceipt.receiptDigest(), + source.schemaVersion(), + source.registrationRequestId(), + source.operationId(), + source.requestDigest(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + } + + private static String v34_3CatalogRequestDigest( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt sourceReceipt) { + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + return CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( + "game-session-canonical-realm-catalog-request/v1", + "1", + request.requestId().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.sourceIntakeOperationId().toString(), + sourceReceipt.intakeRequestId().toString(), + sourceReceipt.requestDigest(), + sourceReceipt.receiptDigest(), + Integer.toString(source.schemaVersion()), + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + request.realmSlug(), + request.realmDisplayName(), + Boolean.toString(request.visible()), + Boolean.toString(request.publicProduction()), + request.stateScope(), + request.characterCreationPolicy(), + "ABSENT", + "ABSENT"); + } + + private static String v34_3CatalogReceiptDigest( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( + "game-session-canonical-realm-catalog-receipt/v1", + "1", + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.requestId().toString(), + requestDigest, + realmId.toString(), + namespaceId.toString(), + Long.toString(revision), + sourceReceipt.operationId().toString(), + sourceReceipt.receiptDigest()); + } + + private static void seedV34_3TenantAssociation(DSLContext tx, PriorRuntime target) { + tx.execute( + "INSERT INTO game_session_tenant_scope_reservation" + + " (game_session_tenant_id, reservation_kind) VALUES (?, 'FRESH_SOURCE_BOUND')", + target.gameSessionTenantId()); + tx.execute( + "INSERT INTO game_session_tenant_canonical_claim" + + " (target_namespace, canonical_tenant_id, legacy_game_session_tenant_id," + + " association_kind, reservation_kind, association_operation_id, association_request_id)" + + " VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", + target.targetNamespace(), + target.canonicalTenantId(), + target.gameSessionTenantId(), + target.tenantAssociationOperationId(), + target.tenantAssociationRequestId()); + tx.execute( + "INSERT INTO game_session_fresh_tenant_association" + + " (association_operation_id, target_namespace, association_request_id," + + " source_schema_version, source_target_namespace, source_request_id," + + " source_canonical_tenant_id, canonical_tenant_id, legacy_game_session_tenant_id," + + " source_game_row_id, source_game_tenant_key, provenance_kind, association_kind)" + + " VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND')", + target.tenantAssociationOperationId(), + target.targetNamespace(), + target.tenantAssociationRequestId(), + target.targetNamespace(), + target.tenantAssociationRequestId(), + target.canonicalTenantId(), + target.canonicalTenantId(), + target.gameSessionTenantId(), + target.sourceGameRowId(), + target.sourceGameTenantKey()); + } + + private static void seedV34_3StartingRuntimeAndLaunch(DSLContext tx, PriorRuntime target) { + tx.execute( + "INSERT INTO game_instances" + + " (id, tenant_id, runtime_version, owner_account_id, status, row_version," + + " game_instance_uuid, game_template_id, launch_descriptor_id, version_id," + + " release_bundle_id, generation_config_revision, version_state_epoch," + + " run_owned_start_request_id, run_owned_start_request_digest," + + " run_owned_start_published_release_bundle_ref, run_owned_start_preparing_epoch," + + " run_owned_start_active_epoch)" + + " VALUES (?, ?, 'fixture-runtime', 99, 'STARTING', 1, ?, 1, ?, 1, 1, ?, 1, ?, ?, ?, 1, 2)", + target.gameInstanceId(), + target.gameSessionTenantId(), + target.gameInstanceUuid(), + target.launchDescriptorId(), + target.generationConfigRevision(), + target.controlPlaneRequestId(), + V34_3_RAW_SHA256, + target.publishedReleaseBundleRef()); + tx.execute( + "INSERT INTO game_session_canonical_instance_launch" + + " (target_namespace, control_plane_request_id, game_session_tenant_id," + + " canonical_tenant_id, tenant_association_operation_id, tenant_association_request_id," + + " tenant_source_schema_version, tenant_source_target_namespace, tenant_source_request_id," + + " tenant_source_canonical_tenant_id, tenant_source_game_row_id," + + " tenant_source_game_tenant_key, tenant_source_provenance_kind, tenant_association_kind," + + " game_instance_id, game_instance_uuid, canonical_realm_id, world_slug," + + " playable_state_namespace_id, playable_state_scope, public_production," + + " captured_starting_row_version, game_template_id, launch_descriptor_id, version_id," + + " release_bundle_id, generation_config_revision, version_state_epoch," + + " complete_launch_binding_evidence)" + + " VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, 'NEW_GAME_ROW', 'FRESH_SOURCE_BOUND'," + + " ?, ?, ?, ?, ?, 'SHARED', TRUE, 1, 1, ?, 1, 1, ?, 1," + + " jsonb_build_object('descriptor', jsonb_build_object('targetNamespace', ?," + + " 'controlPlaneRequestId', ?, 'canonicalTenantId', ?, 'worldSlug', ?," + + " 'gameTemplateId', '1', 'launchDescriptorId', ?, 'versionId', '1'," + + " 'releaseBundleId', '1', 'generationConfigRevision', ?, 'versionStateEpoch', '1'," + + " 'publishedReleaseBundleRef', ?), 'releaseAttestation'," + + " jsonb_build_object('canonicalVersionId', ?)))", + target.targetNamespace(), + target.controlPlaneRequestId(), + target.gameSessionTenantId(), + target.canonicalTenantId(), + target.tenantAssociationOperationId(), + target.tenantAssociationRequestId(), + target.targetNamespace(), + target.tenantAssociationRequestId(), + target.canonicalTenantId(), + target.sourceGameRowId(), + target.sourceGameTenantKey(), + target.gameInstanceId(), + target.gameInstanceUuid(), + target.realmId(), + target.worldSlug(), + target.playableStateNamespaceId(), + target.launchDescriptorId(), + target.generationConfigRevision(), + target.targetNamespace(), + target.controlPlaneRequestId(), + target.canonicalTenantId().toString(), + target.worldSlug(), + target.launchDescriptorId(), + target.generationConfigRevision(), + target.publishedReleaseBundleRef(), + target.canonicalVersionId().toString()); + } + + private record PredecessorSnapshot(String originalColumns, String xmin) {} + + private record PriorRuntime( + String targetNamespace, + UUID canonicalTenantId, + String tenantSlug, + String worldSlug, + String worldDisplayName, + UUID realmId, + String realmSlug, + String realmDisplayName, + long gameSessionTenantId, + long gameInstanceId, + UUID playableStateNamespaceId, + UUID gameInstanceUuid, + UUID canonicalVersionId, + long sourceGameRowId, + String sourceGameTenantKey, + UUID sourceIntakeOperationId, + UUID sourceIntakeRequestId, + UUID sourceRegistrationRequestId, + UUID sourceOperationId, + UUID tenantAssociationOperationId, + UUID tenantAssociationRequestId, + UUID catalogCreationRequestId, + String launchDescriptorId, + String generationConfigRevision, + String controlPlaneRequestId, + String publishedReleaseBundleRef) {} + @Test void oneConcurrentClaimWinsAndExactReplayReturnsOnlyTheOriginalSnapshot() throws Exception { Fixture fixture = fixture(Duration.ofSeconds(30)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java index a7670e1485..2c85d58f8c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java @@ -540,8 +540,7 @@ void initialAssociationInsertRejectsAClaimThatExpiresWhileTheInsertIsBlocked() t int pinBackendPid = waiterPid.get(15, TimeUnit.SECONDS); int blockerBackendPid = blockerPid.get(15, TimeUnit.SECONDS); awaitPostgresLockWait(fixture.dsl, pinBackendPid, blockerBackendPid); - Thread.sleep(5_250L); - assertThat(fixture.leaseExpired(tuple.controlPlaneRequestId())).isTrue(); + awaitOwnerClaimExpiry(fixture, tuple.controlPlaneRequestId()); releaseBlocker.countDown(); RuntimeException failure = waiter.get(15, TimeUnit.SECONDS); @@ -652,6 +651,20 @@ private static void awaitPostgresLockWait(DSLContext observer, int waiterPid, in .isTrue(); } + private static void awaitOwnerClaimExpiry(Fixture fixture, String requestId) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); + while (System.nanoTime() < deadline) { + if (fixture.leaseExpired(requestId)) { + return; + } + Thread.sleep(10L); + } + assertThat(fixture.leaseExpired(requestId)) + .as("original owner claim expires according to its PostgreSQL authority clock") + .isTrue(); + } + private static void awaitOriginalAuthorizationExpiry(Fixture fixture, String expiresAt) throws InterruptedException { long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java index 49b3bf9509..cc145f6f20 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import integration.net.firedevops.firemud.gamesession.repository.CanonicalHumanPublicationOwnerTestFixtures; import java.nio.file.Path; import java.time.Duration; import java.time.Instant; @@ -36,6 +37,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; @@ -100,8 +102,9 @@ class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { fixture.dsl.fetchCount( DSL.table(DSL.name("game_session_canonical_launch_preparation")))) .isZero(); - IntakeReceipt source = java.util.Objects.requireNonNull(fixture.preV24Source); - CanonicalRealmCatalogSnapshot catalog = java.util.Objects.requireNonNull(fixture.preV24Catalog); + fixture.requireHistoricalRowsRetained(); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); assertThat( fixture.sourceRepository.read( source.operationId(), TENANT, source.source().worldSlug(), NAMESPACE)) @@ -158,6 +161,7 @@ class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { RETAINED_TENANT_ID) .get("playable_state_namespace_id", UUID.class)) .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + fixture.requireHistoricalRowsRetained(); verify(syntheticGameDesign, times(1)).resolve(any()); verify(syntheticGameDesign, times(1)).get(any(GetRequest.class)); } @@ -634,27 +638,41 @@ private Fixture fixture( preV24Source = java.util.Objects.requireNonNull( transactions.execute( - status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); - CreateCanonicalRealmCatalogRequest catalogRequest = - new CreateCanonicalRealmCatalogRequest( - CATALOG_REQUEST, - NAMESPACE, - TENANT, - preV24Source.operationId(), - "violet-realm", - "Violet Realm", - true, - true, - "SHARED", - "explicit-policy-v1", - null, - null); - var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); - preV24Catalog = - java.util.Objects.requireNonNull( - transactions.execute( - status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); + status -> sourceRepository.register(uuid(977), historicalSource()))); + preV24Catalog = seedHistoricalCatalog(transactionalDsl, transactions, preV24Source); } + String historicalCatalogBefore = + preV24Catalog == null + ? null + : historicalProjection( + transactionalDsl, + "game_session_canonical_realm_catalog", + "creation_request_id", + preV24Catalog.creationRequestId()); + String historicalSourceBefore = + preV24Source == null + ? null + : historicalProjection( + transactionalDsl, + "game_session_authored_world_source_intake", + "operation_id", + preV24Source.operationId()); + String historicalNamespaceBefore = + preV24Source == null + ? null + : historicalProjection( + transactionalDsl, + "gameplay_tenant_shared_playable_state_namespace", + "canonical_tenant_id", + preV24Source.source().canonicalTenantId()); + String historicalBindingBefore = + preV24Source == null + ? null + : historicalProjection( + transactionalDsl, + "game_session_authored_world_tenant_source_binding", + "canonical_tenant_id", + preV24Source.source().canonicalTenantId()); Flyway.configure() .dataSource(dataSource) @@ -678,7 +696,11 @@ private Fixture fixture( transactionManager, transactions, preV24Source, - preV24Catalog); + preV24Catalog, + historicalCatalogBefore, + historicalSourceBefore, + historicalNamespaceBefore, + historicalBindingBefore); } private static AuthoredWorldSourceEvidence freshSource() { @@ -720,6 +742,190 @@ private static AuthoredWorldSourceEvidence freshSource() { evidenceDigest); } + /** Literal V23 owner rows are retained history, never complete current policy authority. */ + private static AuthoredWorldSourceEvidence historicalSource() { + UUID tenant = uuid(970); + UUID registration = uuid(971); + UUID operation = uuid(972); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registration, + tenant, + "historical-tenant", + "historical-world", + "Historical World"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registration, + operation, + requestDigest, + tenant, + "historical-tenant", + "historical-world", + "Historical World", + 971L, + "historical-gds-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registration, + operation, + requestDigest, + tenant, + "historical-tenant", + "historical-world", + "Historical World", + 971L, + "historical-gds-key", + "NEW_GAME_ROW")); + } + + private static CanonicalRealmCatalogSnapshot seedHistoricalCatalog( + DSLContext dsl, TransactionTemplate transactions, IntakeReceipt intake) { + var source = intake.source(); + UUID request = uuid(976); + UUID realm = uuid(974); + UUID namespace = uuid(973); + String requestDigest = + CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( + "game-session-canonical-realm-catalog-request/v1", + "1", + request.toString(), + NAMESPACE, + source.canonicalTenantId().toString(), + intake.operationId().toString(), + intake.intakeRequestId().toString(), + intake.requestDigest(), + intake.receiptDigest(), + "1", + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + "historical-realm", + "Historical Realm", + "true", + "true", + "SHARED", + "PRESEEDED_ONLY", + "ABSENT", + "ABSENT"); + String receiptDigest = + CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( + "game-session-canonical-realm-catalog-receipt/v1", + "1", + NAMESPACE, + source.canonicalTenantId().toString(), + request.toString(), + requestDigest, + realm.toString(), + namespace.toString(), + "1", + intake.operationId().toString(), + intake.receiptDigest()); + java.util.Map columns = new java.util.LinkedHashMap<>(); + columns.put("target_namespace", NAMESPACE); + columns.put("canonical_tenant_id", source.canonicalTenantId()); + columns.put("tenant_slug", source.tenantSlug()); + columns.put("world_slug", source.worldSlug()); + columns.put("realm_id", realm); + columns.put("realm_slug", "historical-realm"); + columns.put("realm_display_name", "Historical Realm"); + columns.put("visible", true); + columns.put("public_production", true); + columns.put("state_scope", "SHARED"); + columns.put("playable_state_namespace_id", namespace); + columns.put("character_creation_policy", "PRESEEDED_ONLY"); + columns.put("catalog_revision", 1L); + columns.put("creation_request_id", request); + columns.put("request_digest", requestDigest); + columns.put("receipt_digest", receiptDigest); + columns.put("source_intake_operation_id", intake.operationId()); + columns.put("source_intake_schema_version", 1); + columns.put("source_intake_request_id", intake.intakeRequestId()); + columns.put("source_intake_request_digest", intake.requestDigest()); + columns.put("source_intake_receipt_digest", intake.receiptDigest()); + columns.put("source_schema_version", 1); + columns.put("source_registration_request_id", source.registrationRequestId()); + columns.put("source_operation_id", source.operationId()); + columns.put("source_request_digest", source.requestDigest()); + columns.put("source_world_display_name", source.worldDisplayName()); + columns.put("source_game_row_id", source.sourceGameRowId()); + columns.put("source_game_tenant_key", source.sourceGameTenantKey()); + columns.put("source_provenance_kind", source.provenanceKind()); + columns.put("source_evidence_digest", source.evidenceDigest()); + transactions.executeWithoutResult( + status -> { + java.util.Map namespaceColumns = new java.util.LinkedHashMap<>(); + namespaceColumns.put("target_namespace", NAMESPACE); + namespaceColumns.put("canonical_tenant_id", source.canonicalTenantId()); + namespaceColumns.put("playable_state_namespace_id", namespace); + columns.forEach( + (name, value) -> { + if (name.startsWith("source_") && !name.equals("source_world_display_name")) { + namespaceColumns.put(name, value); + } + }); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace (" + + String.join(",", namespaceColumns.keySet()) + + ") VALUES (" + + String.join(",", java.util.Collections.nCopies(namespaceColumns.size(), "?")) + + ")", + namespaceColumns.values().toArray()); + dsl.execute( + "INSERT INTO game_session_canonical_realm_catalog (" + + String.join(",", columns.keySet()) + + ") VALUES (" + + String.join(",", java.util.Collections.nCopies(columns.size(), "?")) + + ")", + columns.values().toArray()); + }); + return new CanonicalRealmCatalogSnapshot( + NAMESPACE, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + realm, + "historical-realm", + "Historical Realm", + true, + true, + "SHARED", + namespace, + "PRESEEDED_ONLY", + 1L, + request, + requestDigest, + receiptDigest, + intake); + } + + private static String historicalProjection( + DSLContext dsl, String table, String selector, UUID identity) { + return requiredRecord( + dsl, + "SELECT xmin::text || '/' || (to_jsonb(owner_row) " + + "- 'complete_policy_set_evidence' - 'fixture_policy_request_bytes' - 'fixture_policy_seal_operation_id' " + + "- 'fixture_policy_seal_request_digest' - 'fixture_policy_seal_evidence_digest')::text AS retained " + + "FROM " + + table + + " owner_row WHERE " + + selector + + " = ?", + identity) + .get("retained", String.class); + } + private static Record requiredRecord(DSLContext dsl, String sql, Object... bindings) { return java.util.Objects.requireNonNull( dsl.fetchOne(sql, bindings), "Expected owner evidence row is missing"); @@ -742,7 +948,59 @@ private record Fixture( DataSourceTransactionManager transactionManager, TransactionTemplate transactions, IntakeReceipt preV24Source, - CanonicalRealmCatalogSnapshot preV24Catalog) { + CanonicalRealmCatalogSnapshot preV24Catalog, + String historicalCatalogBefore, + String historicalSourceBefore, + String historicalNamespaceBefore, + String historicalBindingBefore) { + void requireHistoricalRowsRetained() { + java.util.Objects.requireNonNull( + preV24Catalog, "fixture was created without historical V23 owner rows"); + java.util.Objects.requireNonNull( + preV24Source, "fixture was created without historical V23 owner rows"); + assertThat( + historicalProjection( + dsl, + "game_session_canonical_realm_catalog", + "creation_request_id", + preV24Catalog.creationRequestId())) + .isEqualTo(historicalCatalogBefore); + assertThat( + historicalProjection( + dsl, + "game_session_authored_world_source_intake", + "operation_id", + preV24Source.operationId())) + .isEqualTo(historicalSourceBefore); + assertThat( + historicalProjection( + dsl, + "gameplay_tenant_shared_playable_state_namespace", + "canonical_tenant_id", + preV24Source.source().canonicalTenantId())) + .isEqualTo(historicalNamespaceBefore); + assertThat( + historicalProjection( + dsl, + "game_session_authored_world_tenant_source_binding", + "canonical_tenant_id", + preV24Source.source().canonicalTenantId())) + .isEqualTo(historicalBindingBefore); + assertThat( + requiredRecord( + dsl, + "SELECT complete_policy_set_evidence FROM " + + "game_session_canonical_realm_catalog WHERE creation_request_id = ?", + preV24Catalog.creationRequestId()) + .get("complete_policy_set_evidence", byte[].class)) + .isNull(); + assertThatThrownBy( + () -> catalogRepository.readByRequest(NAMESPACE, preV24Catalog.creationRequestId())) + .isInstanceOf( + GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException.class) + .hasMessage("Exactly one complete catalog policy provenance required"); + } + IntakeReceipt registerFreshSource() { IntakeReceipt receipt = transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); @@ -761,10 +1019,29 @@ CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { true, true, "SHARED", - "explicit-policy-v1", + "PRESEEDED_ONLY", null, null); - var prepared = catalogRepository.prepareInitialPublicProduction(request); + transactions.execute( + status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + uuid(980), + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source()))); + var policy = + CanonicalHumanPublicationOwnerTestFixtures.publishedSet( + request, + source.source(), + uuid(981), + 515L, + "controlled-publish-launch-preparation", + "synthetic-published-release-616", + "generation-config-1", + 4L); + var prepared = catalogRepository.prepareInitialPublicProduction(request, policy); CanonicalRealmCatalogSnapshot created = transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); return java.util.Objects.requireNonNull(created); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java index 5c288a8cd3..2f8218fc17 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -26,7 +26,8 @@ class CrossServiceAppHarnessTest { private static final StartSessionRequest REQUEST = - new StartSessionRequest(41L, 810L, "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd", 1001L); + new StartSessionRequest( + 41L, 810L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 1001L); private static final AuthoredWorldSourceEvidence SOURCE_EVIDENCE = sourceEvidence(); private static final RunOwnedInitialAdmissionLaunchEvidence LAUNCH_EVIDENCE = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create(REQUEST, SOURCE_EVIDENCE); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java new file mode 100644 index 0000000000..9794f218fd --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java @@ -0,0 +1,145 @@ +package net.firedevops.firemud.gamesession.client; + +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.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.gamedesign.v1.TenantIdentityServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; + +class GameDesignFreshTenantCreationClientTest { + private static final String NAMESPACE = "dev"; + private static final String WRONG_PEER_URI = "spiffe://firemud/ns/other/sa/game-design-service"; + + @Test + void requiresFileBackedMtlsBeforeCreatingAChannel(@TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + CommonGrpcClientProperties plaintext = tls(directory); + plaintext.setPlaintext(true); + + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload mTLS"); + + verifyNoInteractions(channelFactory); + } + + @Test + void resolveRequiresExplicitInitializationBeforeAnyChannelUse(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + GameDesignFreshTenantCreationClient client = newClient(tls(directory), channelFactory); + try { + assertThatThrownBy(() -> client.resolveCreation(null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } finally { + client.close(); + } + } + + @Test + void rejectsInvalidWorkloadNamespaceBeforeChannelCreation(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + assertThatThrownBy( + () -> + new GameDesignFreshTenantCreationClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + + verifyNoInteractions(channelFactory); + } + + @Test + void exactPeerCredentialsRejectWrongNamespaceBeforeApplyingRequestMetadata( + @TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + any(), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + GameDesignFreshTenantCreationClient client = newClient(tls(directory), channelFactory); + try { + client.init(); + TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub stub = initializedStub(client); + assertThat(stub.getCallOptions().getCredentials()) + .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + + SSLSession sslSession = mock(SSLSession.class); + var peerCertificate = mock(java.security.cert.X509Certificate.class); + when(peerCertificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, WRONG_PEER_URI))); + when(sslSession.getPeerCertificates()) + .thenReturn(new java.security.cert.Certificate[] {peerCertificate}); + CallCredentials.RequestInfo requestInfo = mock(CallCredentials.RequestInfo.class); + when(requestInfo.getTransportAttrs()) + .thenReturn( + Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build()); + CallCredentials.MetadataApplier applier = mock(CallCredentials.MetadataApplier.class); + + stub.getCallOptions() + .getCredentials() + .applyRequestMetadata(requestInfo, Runnable::run, applier); + + ArgumentCaptor failure = ArgumentCaptor.forClass(Status.class); + verify(applier).fail(failure.capture()); + assertThat(failure.getValue().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + verify(applier, never()).apply(any(Metadata.class)); + } finally { + client.close(); + } + } + + private static GameDesignFreshTenantCreationClient newClient( + CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory) { + return new GameDesignFreshTenantCreationClient( + new ServiceEndpointsProperties(), tlsProperties, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + Path certificate = Files.writeString(directory.resolve("client.crt"), "certificate"); + Path privateKey = Files.writeString(directory.resolve("client.key"), "private key"); + Path caCertificate = Files.writeString(directory.resolve("ca.crt"), "CA certificate"); + CommonGrpcClientProperties properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caCertificate.toString()); + return properties; + } + + @SuppressWarnings("unchecked") + private static TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub initializedStub( + GameDesignFreshTenantCreationClient client) throws Exception { + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + return (TenantIdentityServiceGrpc.TenantIdentityServiceBlockingStub) stubField.get(client); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java new file mode 100644 index 0000000000..7e4d15a63e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java @@ -0,0 +1,654 @@ +package net.firedevops.firemud.gamesession.data; + +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.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +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 io.grpc.Context; +import java.nio.file.Path; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.v1.ArtifactState; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; +import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.FixtureCanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.FixtureCanonicalRealmCatalog; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.MockedStatic; + +class RunOwnedCanonicalLaunchPreparationOwnerTest { + private static final String RUN_ID = "compose-smoke-fixture-20261014"; + private static final String PROJECT_NAME = "firemud-smoke-compose-fixture-20261014"; + private static final String CAPABILITY_PATH = "fixture/capability.json"; + private static final String SOURCE_RECEIPT_PATH = "fixture/source-receipt.json"; + private static final String CLAIM_DIGEST = "d".repeat(64); + private static final String OPERATION_ID = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, RUN_ID, PROJECT_NAME, "a".repeat(64), "b".repeat(64)) + .toString(); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + private static final UUID CREATION_REQUEST_ID = + UUID.fromString("57341fb9-55ee-42f4-842e-6e6305c22411"); + private static final UUID CREATION_OPERATION_ID = + UUID.fromString("d156e17a-d759-4db5-a456-c082b5d74419"); + private static final UUID ASSOCIATION_OPERATION_ID = + UUID.fromString("a6fb2f17-747f-423e-a7cc-e8c577b6d44e"); + private static final UUID INTAKE_OPERATION_ID = + UUID.fromString("a05f8aae-b4dd-4e11-8a92-0271c60ec6c0"); + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("ce432a95-d19a-47bc-9266-874158e5990c"); + private static final UUID REALM_ID = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); + private static final UUID NAMESPACE_ID = UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); + private static final UUID GAME_INSTANCE_UUID = + UUID.fromString("7556e829-d531-4c61-b8d4-350c8514c4f1"); + + @Test + void commitsExactStartingOwnerAllocationThenPerformsSeparateIndependentReadback() { + Fixture fixture = fixture(true); + + var result = + fixture.coordinator.prepareVerifiedFixtureLaunch(fixture.capability, fixture.sourceReceipt); + + assertThat(result.launchEvidence().sourceEvidence()) + .isEqualTo(fixture.sourceReceipt.sourceEvidence()); + assertThat(result.launchEvidence().creationEvidence()) + .isEqualTo(fixture.sourceReceipt.creationEvidence()); + assertThat(result.launchEvidence().fixturePolicySeal()) + .isEqualTo(fixture.sourceReceipt.fixturePolicySeal()); + assertThat(result.launchEvidence().fixtureCapability().gameSessionLeafSha256()) + .isEqualTo(fixture.capability.gameSessionLeafSha256()); + assertThat(result.launchEvidence().fixtureCapability().worldManagementLeafSha256()) + .isEqualTo(fixture.capability.worldManagementLeafSha256()); + assertThat(result.launchEvidence().fixtureCapability().caCertificateSha256()) + .isEqualTo(fixture.capability.caCertificateSha256()); + assertThat(result.launch()).isEqualTo(fixture.allocation); + assertThat(result.launch().status()).isEqualTo(CurrentGameInstanceStatus.STARTING); + assertThat(result.launch().gameInstanceId()).isPositive(); + assertThat(result.launch().gameInstanceUuid()).isEqualTo(GAME_INSTANCE_UUID); + assertThat(result.launch().catalog().snapshot().tenantId()).isEqualTo(CANONICAL_TENANT_ID); + assertThat(result.launch().catalog().snapshot().realmId()).isEqualTo(REALM_ID); + assertThat(result.launch().catalog().snapshot().playableStateNamespaceId()) + .isEqualTo(NAMESPACE_ID); + assertThat(result.launch().catalog().association().gameSessionTenantId()).isEqualTo(71L); + assertThat(result.launch().catalog().association().gameSessionTenantId()).isNotEqualTo(1L); + assertThat(fixture.capability.tenantId()).isEqualTo(1L); + assertThat(result.launchEvidence().sourceEvidence().sourceGameTenantKey()).isEqualTo("1"); + assertThat(result.launchEvidence().creationEvidence().sourceGameTenantKey()).isEqualTo("1"); + + ArgumentCaptor evidenceCaptor = + ArgumentCaptor.forClass(RunOwnedInitialAdmissionLaunchEvidence.class); + InOrder order = inOrder(fixture.launchOwner); + order.verify(fixture.launchOwner).createVerifiedFixtureStartingLaunch(evidenceCaptor.capture()); + RunOwnedInitialAdmissionLaunchEvidence evidence = evidenceCaptor.getValue(); + order.verify(fixture.launchOwner).readVerifiedFixtureLaunch(same(evidence)); + } + + @Test + void explicitPreparationLoadsFixedVerifiedReceiptBeforeOwnerWrite() { + Fixture fixture = fixture(true); + + try (MockedStatic loader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + stubFixtureLoaders(loader, fixture, fixture.sourceReceipt); + var result = fixture.coordinator.prepareFixedVerifiedFixtureLaunch(); + + assertThat(result.launch()).isEqualTo(fixture.allocation); + assertThat(result.launchEvidence().sourceEvidence()) + .isEqualTo(fixture.sourceReceipt.sourceEvidence()); + assertThat(result.launchEvidence().fixturePolicySeal()) + .isEqualTo(fixture.sourceReceipt.fixturePolicySeal()); + } + + InOrder order = inOrder(fixture.launchOwner); + order.verify(fixture.launchOwner).createVerifiedFixtureStartingLaunch(any()); + order.verify(fixture.launchOwner).readVerifiedFixtureLaunch(any()); + } + + @Test + void exactReplayUsesTheSameOperationAndReturnsTheSameStartingAllocation() { + Fixture fixture = fixture(true); + + var first = + fixture.coordinator.prepareVerifiedFixtureLaunch(fixture.capability, fixture.sourceReceipt); + var replay = + fixture.coordinator.prepareVerifiedFixtureLaunch(fixture.capability, fixture.sourceReceipt); + + assertThat(replay.launch()).isEqualTo(first.launch()); + assertThat(replay.launchEvidence().sourceEvidence()) + .isEqualTo(first.launchEvidence().sourceEvidence()); + assertThat(replay.launchEvidence().fixtureCapability().operationId()).isEqualTo(OPERATION_ID); + verify(fixture.launchOwner, times(2)).createVerifiedFixtureStartingLaunch(any()); + verify(fixture.launchOwner, times(2)).readVerifiedFixtureLaunch(any()); + } + + @Test + void rejectsChangedPrivateAllocationAndChangedLifecycleStatus() { + Fixture changedIdentity = fixture(true); + FixtureCanonicalInstanceLaunch differentIdentity = + new FixtureCanonicalInstanceLaunch( + changedIdentity.allocation.gameInstanceId(), + UUID.fromString("bb76a459-f249-4a9d-9045-7c748d2e2b1f"), + changedIdentity.allocation.catalog(), + changedIdentity.allocation.status(), + changedIdentity.allocation.rowVersion()); + when(changedIdentity.launchOwner.readVerifiedFixtureLaunch(any())) + .thenReturn(differentIdentity); + + assertThatThrownBy( + () -> + changedIdentity.coordinator.prepareVerifiedFixtureLaunch( + changedIdentity.capability, changedIdentity.sourceReceipt)) + .isInstanceOf(IllegalStateException.class); + + Fixture changedStatus = fixture(true); + FixtureCanonicalInstanceLaunch running = + new FixtureCanonicalInstanceLaunch( + changedStatus.allocation.gameInstanceId(), + changedStatus.allocation.gameInstanceUuid(), + changedStatus.allocation.catalog(), + CurrentGameInstanceStatus.RUNNING, + changedStatus.allocation.rowVersion()); + when(changedStatus.launchOwner.readVerifiedFixtureLaunch(any())).thenReturn(running); + + assertThatThrownBy( + () -> + changedStatus.coordinator.prepareVerifiedFixtureLaunch( + changedStatus.capability, changedStatus.sourceReceipt)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsReceiptWithChangedFixturePolicySealBeforeOwnerWrite() { + Fixture fixture = fixture(true); + var originalSeal = fixture.sourceReceipt.fixturePolicySeal(); + var changedSeal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + originalSeal.schema(), + originalSeal.ownerService(), + originalSeal.operationId(), + "sha256:" + "e".repeat(64), + "sha256:" + "f".repeat(64)); + var changedReceipt = + new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( + fixture.sourceReceipt.schema(), + fixture.sourceReceipt.runId(), + fixture.sourceReceipt.composeProjectName(), + fixture.sourceReceipt.fixtureOperationId(), + fixture.sourceReceipt.ownerService(), + fixture.sourceReceipt.gameSessionUriSan(), + fixture.sourceReceipt.gameSessionLeafSha256(), + fixture.sourceReceipt.caCertificateSha256(), + fixture.sourceReceipt.worldManagementUriSan(), + fixture.sourceReceipt.worldManagementLeafSha256(), + fixture.sourceReceipt.sourceEvidence(), + fixture.sourceReceipt.launchReadEvidence(), + fixture.sourceReceipt.creationEvidence(), + changedSeal); + + assertThatThrownBy( + () -> + fixture.coordinator.prepareVerifiedFixtureLaunch( + fixture.capability, changedReceipt)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(fixture.launchOwner); + } + + @Test + void fixedEvidenceReadRejectsChangedReceiptIdentityAcrossReads() { + Fixture fixture = fixture(true); + var changedReceipt = sourceReceipt(fixture.capability, 30L); + try (MockedStatic loader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + stubFixtureLoaders(loader, fixture, fixture.sourceReceipt, changedReceipt); + assertThat(fixture.coordinator.loadFixedVerifiedEvidence().sourceEvidence()) + .isEqualTo(fixture.sourceReceipt.sourceEvidence()); + assertThatThrownBy(fixture.coordinator::loadFixedVerifiedEvidence) + .isInstanceOf(IllegalStateException.class); + } + verifyNoInteractions(fixture.launchOwner); + } + + @Test + void disabledOwnerDoesNotReadFixturePathsOrWriteLaunchOwner() { + Fixture fixture = fixture(false); + + try (MockedStatic loader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + assertThatThrownBy(fixture.coordinator::loadFixedVerifiedEvidence) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(fixture.coordinator::prepareFixedVerifiedFixtureLaunch) + .isInstanceOf(IllegalStateException.class); + + loader.verify( + () -> RunOwnedInitialAdmissionFixtureCapability.load(any(), any(), any(), any()), + never()); + loader.verify( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(), any(), any(), any(), any()), + never()); + } + + verifyNoInteractions(fixture.launchOwner); + } + + @Test + void fixedEvidenceReadRequiresTheExactWorldPeerAndRetainedWorldLeafBeforeDecodingSelectors() { + SessionContext.clear(); + Fixture fixture = fixture(true); + GrpcPeerCertificateEvidence certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn(fixture.capability.worldManagementLeafSha256()); + GrpcPeerIdentity worldPeer = + GrpcPeerIdentity.parseUri( + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN) + .orElseThrow(); + Context worldContext = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, worldPeer) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + + try (MockedStatic loader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + stubFixtureLoaders(loader, fixture, fixture.sourceReceipt); + Context previous = worldContext.attach(); + try { + var evidence = fixture.coordinator.loadFixedVerifiedEvidenceForWorldPeer(); + assertThat(evidence.fixtureCapability().operationId()).isEqualTo(OPERATION_ID); + + when(certificate.leafSha256()).thenReturn("d".repeat(64)); + assertThatThrownBy(fixture.coordinator::loadFixedVerifiedEvidenceForWorldPeer) + .isInstanceOf(AdminAuthorizationException.class); + + when(certificate.leafSha256()).thenReturn(fixture.capability.worldManagementLeafSha256()); + Context wrongWorldContext = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/other/sa/world-management-service") + .orElseThrow()) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + Context worldPrevious = wrongWorldContext.attach(); + try { + assertThatThrownBy(fixture.coordinator::loadFixedVerifiedEvidenceForWorldPeer) + .isInstanceOf(AdminAuthorizationException.class); + } finally { + wrongWorldContext.detach(worldPrevious); + } + } finally { + worldContext.detach(previous); + SessionContext.clear(); + } + } + } + + private static Fixture fixture(boolean enabled) { + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + RunOwnedInitialAdmissionFixtureCapability capability = capability(); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt = + sourceReceipt(capability, 29L); + FixtureCanonicalInstanceLaunch allocation = allocation(capability, receipt); + GameSessionCanonicalInstanceLaunchRepository launchOwner = + mock(GameSessionCanonicalInstanceLaunchRepository.class); + when(launchOwner.createVerifiedFixtureStartingLaunch(any())).thenReturn(allocation); + when(launchOwner.readVerifiedFixtureLaunch(any())).thenReturn(allocation); + RunOwnedCanonicalLaunchPreparationOwner coordinator = + new RunOwnedCanonicalLaunchPreparationOwner( + enabled, + CAPABILITY_PATH, + SOURCE_RECEIPT_PATH, + RUN_ID, + PROJECT_NAME, + grpc, + launchOwner, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE); + return new Fixture(coordinator, capability, receipt, grpc, launchOwner, allocation); + } + + private static void stubFixtureLoaders( + MockedStatic loader, + Fixture fixture, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt... receipts) { + loader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + AtomicInteger index = new AtomicInteger(); + loader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenAnswer(invocation -> receipts[Math.min(index.getAndIncrement(), receipts.length - 1)]); + loader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.toWireCapability( + any(RunOwnedInitialAdmissionFixtureCapability.class))) + .thenCallRealMethod(); + } + + private static RunOwnedInitialAdmissionFixtureCapability capability() { + return new RunOwnedInitialAdmissionFixtureCapability( + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + 1L, + 17L, + 27L, + RunOwnedInitialAdmissionFixtureCapability.WORLD_SLUG, + RunOwnedInitialAdmissionFixtureCapability.WORLD_DISPLAY_NAME, + RunOwnedInitialAdmissionFixtureCapability.REALM_SLUG, + RunOwnedInitialAdmissionFixtureCapability.REALM_DISPLAY_NAME, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "a".repeat(64), + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + "b".repeat(64), + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + "c".repeat(64), + CLAIM_DIGEST); + } + + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, long sourceGameRowId) { + String targetNamespace = RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE; + String tenantSlug = "fixture-tenant"; + String sourceGameTenantKey = "1"; + String provenanceKind = "NEW_GAME_ROW"; + UUID registrationRequestId = UUID.fromString(capability.operationId()); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, + registrationRequestId, + CANONICAL_TENANT_ID, + tenantSlug, + capability.worldSlug(), + capability.worldDisplayName()); + AuthoredWorldSourceEvidence sourceEvidence = + new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + registrationRequestId, + SOURCE_OPERATION_ID, + sourceRequestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + capability.worldSlug(), + capability.worldDisplayName(), + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + registrationRequestId, + SOURCE_OPERATION_ID, + sourceRequestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + capability.worldSlug(), + capability.worldDisplayName(), + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + String creationRequestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, + CREATION_REQUEST_ID, + sourceGameTenantKey, + capability.worldDisplayName(), + null); + FreshTenantCreationEvidence creationEvidence = + new FreshTenantCreationEvidence( + 1, + targetNamespace, + CREATION_REQUEST_ID, + CREATION_OPERATION_ID, + creationRequestDigest, + CANONICAL_TENANT_ID, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + CREATION_REQUEST_ID, + CREATION_OPERATION_ID, + creationRequestDigest, + CANONICAL_TENANT_ID, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + var launchRead = launchReadEvidence(capability, sourceEvidence); + var wireLaunchRead = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + launchRead.schema(), + launchRead.gameTemplateId(), + launchRead.publishedReleaseBundle(), + launchRead.versionAssetArtifactState(), + launchRead.versionState(), + launchRead.launchDescriptor()); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + RunOwnedInitialAdmissionFixtureCapability.toWireCapability(capability), + creationEvidence, + sourceEvidence, + wireLaunchRead); + var seal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + registrationRequestId, + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + registrationRequestId, policyRequestDigest)); + return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, + capability.runId(), + capability.composeProjectName(), + capability.operationId(), + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + capability.gameSessionUriSan(), + capability.gameSessionLeafSha256(), + capability.caCertificateSha256(), + capability.worldManagementUriSan(), + capability.worldManagementLeafSha256(), + sourceEvidence, + launchRead, + creationEvidence, + seal); + } + + private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence launchReadEvidence( + RunOwnedInitialAdmissionFixtureCapability capability, + AuthoredWorldSourceEvidence sourceEvidence) { + String manifestHash = "sha256:" + "a".repeat(64); + String artifactDigest = "sha256:" + "b".repeat(64); + PublishedReleaseBundle bundle = + PublishedReleaseBundle.newBuilder() + .setId(77L) + .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setPublishWorkflowId("publish-11") + .setManifestHash(manifestHash) + .addRequiredManifestAssetKeys("manifest.json") + .setGenerationConfigRevision("genrev-11") + .setPublishedAt("2026-04-15T10:00:00") + .setPublishedReleaseBundleRef("prb:7:11:77") + .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") + .setManifestSchemaVersion(1) + .addArtifactDigests( + net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() + .setUsageKey("manifest.json") + .setArtifactKind("manifest") + .setImmutableObjectKey("artifacts/sha256/" + artifactDigest.substring(7)) + .setContentDigest(artifactDigest) + .setContentType("application/json") + .setArtifactSchemaVersion(1) + .build()) + .build(); + VersionAssetArtifactState artifactState = + VersionAssetArtifactState.newBuilder() + .setTenantId(Long.toString(capability.tenantId())) + .setVersionId(11L) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setStateEpoch(2L) + .setManifestHash(manifestHash) + .setUpdatedAt("2026-04-15T10:00:00") + .addExportedManifestAssetKeys("manifest.json") + .setExportedVersionNumber(1) + .build(); + VersionStateSnapshot versionState = + VersionStateSnapshot.newBuilder() + .setTenantId(Long.toString(capability.tenantId())) + .setVersionId(11L) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionStateEpoch(77L) + .setUpdatedAt("2026-04-15T10:00:00") + .build(); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + capability.operationId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + capability.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + var descriptorEvidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "launch-descriptor-fixture-11", + bundle.getVersionId(), + false, + null, + "{}", + bundle.getGenerationConfigRevision(), + versionState.getVersionStateEpoch(), + bundle.getId(), + bundle.getPublishedReleaseBundleRef(), + false, + null); + LaunchDescriptor descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); + return new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureCapability.LAUNCH_READ_EVIDENCE_SCHEMA, + capability.gameTemplateId(), + bundle, + artifactState, + versionState, + descriptor); + } + + private static FixtureCanonicalInstanceLaunch allocation( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { + AuthoredWorldSourceEvidence source = receipt.sourceEvidence(); + FreshTenantCreationEvidence creation = receipt.creationEvidence(); + String intakeRequestDigest = + net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest + .requestDigest(INTAKE_REQUEST_ID, source); + IntakeReceipt intakeReceipt = + new IntakeReceipt( + INTAKE_OPERATION_ID, + INTAKE_REQUEST_ID, + intakeRequestDigest, + source, + net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest + .receiptDigest(INTAKE_OPERATION_ID, intakeRequestDigest, source.evidenceDigest())); + CanonicalRealmCatalogSnapshot snapshot = + new CanonicalRealmCatalogSnapshot( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + REALM_ID, + capability.realmSlug(), + capability.realmDisplayName(), + capability.visible(), + capability.publicProductionRealm(), + capability.stateScope(), + NAMESPACE_ID, + capability.characterCreationPolicy(), + 1L, + creation.creationRequestId(), + "sha256:" + "e".repeat(64), + "sha256:" + "f".repeat(64), + intakeReceipt); + FreshTenantAssociation association = + new FreshTenantAssociation( + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + source.canonicalTenantId(), + 71L, + ASSOCIATION_OPERATION_ID, + creation); + return new FixtureCanonicalInstanceLaunch( + 42L, + GAME_INSTANCE_UUID, + new FixtureCanonicalRealmCatalog(snapshot, association), + CurrentGameInstanceStatus.STARTING, + 0L); + } + + private record Fixture( + RunOwnedCanonicalLaunchPreparationOwner coordinator, + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt, + CommonGrpcClientProperties grpcProperties, + GameSessionCanonicalInstanceLaunchRepository launchOwner, + FixtureCanonicalInstanceLaunch allocation) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index b830e55c74..9226864629 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -18,11 +18,14 @@ import java.util.List; import java.util.Set; import java.util.UUID; +import java.util.function.Supplier; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapability.CertificatePins; import org.junit.jupiter.api.Test; @@ -34,7 +37,11 @@ class RunOwnedInitialAdmissionFixtureCapabilityTest { private static final String RUN_ID = "compose-smoke-2939"; private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; - private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final String CLAIM_DIGEST = "d".repeat(64); + private static final String OPERATION_ID = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, RUN_ID, PROJECT_NAME, "a".repeat(64), "b".repeat(64)) + .toString(); private static final String SOURCE_OPERATION_ID = "3f773701-e812-44f5-8ae0-7268d543beed"; private static final String LEAF_SHA = "a".repeat(64); private static final String WORLD_LEAF_SHA = "c".repeat(64); @@ -52,6 +59,16 @@ void parsesExactCapabilityAndBindsRunProjectSelectorsAndTlsPins() { assertThat(capability.runId()).isEqualTo(RUN_ID); assertThat(capability.composeProjectName()).isEqualTo(PROJECT_NAME); assertThat(capability.operationId()).isEqualTo(OPERATION_ID); + assertThat(capability.claimDigest()).isEqualTo(CLAIM_DIGEST); + assertThat(capability.operationId()) + .isEqualTo( + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + capability.claimDigest(), + capability.runId(), + capability.composeProjectName(), + capability.gameSessionLeafSha256(), + capability.caCertificateSha256()) + .toString()); assertThat(capability.tenantId()).isEqualTo(7L); assertThat(capability.gameTemplateId()).isEqualTo(17L); assertThat(capability.ownerAccountId()).isEqualTo(27L); @@ -127,10 +144,13 @@ void parsesExactSourceReceiptAndReconstructsTheFullEvidenceRecord() { assertThat(receipt.ownerService()) .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE); assertThat(receipt.sourceEvidence()).isEqualTo(sourceEvidence()); + assertThat(receipt.creationEvidence()).isEqualTo(creationEvidence(sourceEvidence())); + assertThat(receipt.fixturePolicySeal().operationId()).isEqualTo(UUID.fromString(OPERATION_ID)); + assertThat(receipt.fixturePolicySeal().requestDigest()).matches("sha256:[0-9a-f]{64}"); assertThat(receipt.sourceEvidence().registrationRequestId()) .isEqualTo(UUID.fromString(OPERATION_ID)); assertThat(receipt.sourceEvidence().operationId()) - .isNotEqualTo(receipt.sourceEvidence().registrationRequestId()); + .isEqualTo(UUID.fromString(SOURCE_OPERATION_ID)); assertThat(receipt.launchReadEvidence().schema()) .isEqualTo(RunOwnedInitialAdmissionLaunchEvidence.SCHEMA); assertThat(receipt.launchReadEvidence().gameTemplateId()).isEqualTo(17L); @@ -183,30 +203,26 @@ void rejectsOpenDuplicateMismatchedAndMalformedSourceReceiptFields() { assertInvalidSourceReceipt(json.replace(canonicalBundle, nonCanonicalBundle)); assertInvalidSourceReceipt(json.replace(canonicalBundle, encode(new byte[] {10, 5}))); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", launchBundle().toBuilder() .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") - .build())); + .build() + .toByteArray())); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setArtifactStateValue(999).build(), - launchVersionState())); + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder().setArtifactStateValue(999).build().toByteArray())); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setVersionStateValue(999).build())); + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder().setVersionStateValue(999).build().toByteArray())); } @Test void rejectsLaunchDescriptorThatDoesNotMatchOwnerReadSnapshots() { var source = sourceEvidence(); var bundle = launchBundle(); - var artifactState = launchArtifactState(); var versionState = launchVersionState(); var mismatchedDescriptor = launchDescriptor( @@ -217,7 +233,8 @@ void rejectsLaunchDescriptorThatDoesNotMatchOwnerReadSnapshots() { .build()); assertInvalidSourceReceipt( - validSourceReceiptJson(source, bundle, artifactState, versionState, mismatchedDescriptor)); + sourceReceiptWithLaunchReadEvidenceProto( + "launchDescriptorBase64", mismatchedDescriptor.toByteArray())); } @Test @@ -226,62 +243,66 @@ void rejectsOwnerReadProjectionScopeAndStateMismatches() { var unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder().addField(99, unknownField).build(); var invalidReceipts = - List.of( - validSourceReceiptJson().replace("\"gameTemplateId\":17", "\"gameTemplateId\":18"), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setTenantId("8").build(), - launchVersionState()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setVersionId(12L).build(), - launchVersionState()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setStateEpoch(0L).build(), - launchVersionState()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder() - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState - .ARTIFACT_STATE_TOMBSTONED) - .build(), - launchVersionState()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder() - .setManifestHash("sha256:" + "c".repeat(64)) - .build(), - launchVersionState()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setTenantId("8").build()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setVersionId(12L).build()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle().toBuilder().setCanonicalVersionId("not-a-canonical-uuid").build()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setUnknownFields(unknownFields).build(), - launchVersionState()), - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setUnknownFields(unknownFields).build())); + List.>of( + () -> + validSourceReceiptJson().replace("\"gameTemplateId\":17", "\"gameTemplateId\":18"), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder().setTenantId("8").build().toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder().setVersionId(12L).build().toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder().setStateEpoch(0L).build().toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder() + .setArtifactState( + net.firedevops.firemud.gamedesign.v1.ArtifactState + .ARTIFACT_STATE_TOMBSTONED) + .build() + .toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder() + .setManifestHash("sha256:" + "c".repeat(64)) + .build() + .toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder().setTenantId("8").build().toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder().setVersionId(12L).build().toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", + launchBundle().toBuilder() + .setCanonicalVersionId("not-a-canonical-uuid") + .build() + .toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder() + .setUnknownFields(unknownFields) + .build() + .toByteArray()), + () -> + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder() + .setUnknownFields(unknownFields) + .build() + .toByteArray())); invalidReceipts.forEach( RunOwnedInitialAdmissionFixtureCapabilityTest::assertInvalidSourceReceipt); @@ -289,18 +310,10 @@ void rejectsOwnerReadProjectionScopeAndStateMismatches() { @Test void rejectsNonpositiveVersionStateSnapshotEpochFromRawMalformedReceiptEvidence() { - var source = sourceEvidence(); - var bundle = launchBundle(); - var artifactState = launchArtifactState(); - var versionState = launchVersionState().toBuilder().setVersionStateEpoch(0L).build(); - assertInvalidSourceReceipt( - validSourceReceiptJson( - source, - bundle, - artifactState, - versionState, - rawLaunchDescriptorForMalformedVersionStateSnapshot(source, bundle, versionState))); + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder().setVersionStateEpoch(0L).build().toByteArray())); } @Test @@ -319,7 +332,8 @@ void rejectsArtifactSnapshotMissingTheBundlesRequiredManifestKey() { assertThat(bundle.getRequiredManifestAssetKeysList()).containsExactly("manifest.json"); assertThat(missingKeys.getExportedManifestAssetKeysList()).isEmpty(); assertInvalidSourceReceipt( - validSourceReceiptJson(sourceEvidence(), bundle, missingKeys, launchVersionState())); + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", missingKeys.toByteArray())); } @Test @@ -335,7 +349,9 @@ void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { .setUnknownFields(unknownFields) .build()) .build(); - assertInvalidSourceReceipt(validSourceReceiptJson(sourceEvidence(), nestedUnknownBundle)); + assertInvalidSourceReceipt( + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", nestedUnknownBundle.toByteArray())); var nestedUnknownParticipant = launchBundle().toBuilder() .addParticipantDigests( @@ -343,10 +359,13 @@ void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { .setUnknownFields(unknownFields) .build()) .build(); - assertInvalidSourceReceipt(validSourceReceiptJson(sourceEvidence(), nestedUnknownParticipant)); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), launchBundle().toBuilder().setUnknownFields(unknownFields).build())); + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", nestedUnknownParticipant.toByteArray())); + assertInvalidSourceReceipt( + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", + launchBundle().toBuilder().setUnknownFields(unknownFields).build().toByteArray())); } @Test @@ -494,38 +513,13 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { } private static String validSourceReceiptJson() { - return validSourceReceiptJson(sourceEvidence()); - } - - private static String validSourceReceiptJson(AuthoredWorldSourceEvidence source) { - return validSourceReceiptJson(source, launchBundle()); - } - - private static String validSourceReceiptJson( - AuthoredWorldSourceEvidence source, - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle) { - return validSourceReceiptJson(source, bundle, launchArtifactState(), launchVersionState()); - } - - private static String validSourceReceiptJson( - AuthoredWorldSourceEvidence source, - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState) { - return validSourceReceiptJson( - source, - bundle, - artifactState, - versionState, - launchDescriptor(source, bundle, versionState)); - } - - private static String validSourceReceiptJson( - AuthoredWorldSourceEvidence source, - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, - LaunchDescriptor descriptor) { + AuthoredWorldSourceEvidence source = sourceEvidence(); + var bundle = launchBundle(); + var artifactState = launchArtifactState(); + var versionState = launchVersionState(); + LaunchDescriptor descriptor = launchDescriptor(source, bundle, versionState); + FreshTenantCreationEvidence creation = creationEvidence(source); + var seal = fixturePolicySeal(source, bundle, artifactState, versionState, descriptor, creation); String sourceJson = """ {%n\ @@ -558,6 +552,31 @@ private static String validSourceReceiptJson( source.sourceGameTenantKey(), source.provenanceKind(), source.evidenceDigest()); + String creationJson = + """ + {"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"}%n\ + """ + .formatted( + creation.schemaVersion(), + creation.targetNamespace(), + creation.creationRequestId(), + creation.operationId(), + creation.requestDigest(), + creation.canonicalTenantId(), + creation.sourceGameRowId(), + creation.sourceGameTenantKey(), + creation.provenanceKind(), + creation.evidenceDigest()); + String sealJson = + """ + {"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}%n\ + """ + .formatted( + seal.schema(), + seal.ownerService(), + seal.operationId(), + seal.requestDigest(), + seal.evidenceDigest()); return """ {%n\ "schema": "%s",%n\ @@ -571,7 +590,9 @@ private static String validSourceReceiptJson( "worldManagementUriSan": "%s",%n\ "worldManagementLeafSha256": "%s",%n\ "sourceEvidence": %s,%n\ - "launchReadEvidence": %s%n\ + "launchReadEvidence": %s,%n\ + "creationEvidence": %s,%n\ + "fixturePolicySeal": %s%n\ }%n\ """ .formatted( @@ -586,7 +607,72 @@ private static String validSourceReceiptJson( RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, WORLD_LEAF_SHA, sourceJson, - launchReadEvidenceJson(source, bundle, artifactState, versionState, descriptor)); + launchReadEvidenceJson(source, bundle, artifactState, versionState, descriptor), + creationJson, + sealJson); + } + + private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID creationRequestId = UUID.fromString("e1757a48-21ac-4c09-8a8a-f65c397b0c01"); + UUID operationId = UUID.fromString("605221c7-5a99-4e8e-bef1-56cfac690c53"); + String sourceGameTenantKey = source.sourceGameTenantKey(); + String requestDigest = + GameTenantCreationDigest.requestDigest( + source.targetNamespace(), + creationRequestId, + sourceGameTenantKey, + source.worldDisplayName(), + null); + return new FreshTenantCreationEvidence( + 1, + source.targetNamespace(), + creationRequestId, + operationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + sourceGameTenantKey, + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + creationRequestId, + operationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + sourceGameTenantKey, + source.provenanceKind())); + } + + private static RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixturePolicySeal( + AuthoredWorldSourceEvidence source, + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, + net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, + LaunchDescriptor descriptor, + FreshTenantCreationEvidence creation) { + var capability = + RunOwnedInitialAdmissionFixtureWireCodec.parseCapability( + validJson().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + var launchReadEvidence = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + capability.gameTemplateId(), + bundle, + artifactState, + versionState, + descriptor); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launchReadEvidence); + UUID fixtureOperationId = UUID.fromString(capability.operationId()); + return new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + fixtureOperationId, + requestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + fixtureOperationId, requestDigest)); } private static String validLaunchReadEvidenceJson() { @@ -594,6 +680,21 @@ private static String validLaunchReadEvidenceJson() { sourceEvidence(), launchBundle(), launchArtifactState(), launchVersionState()); } + private static String sourceReceiptWithLaunchReadEvidenceProto( + String fieldName, byte[] replacementBytes) { + String validReceipt = validSourceReceiptJson(); + String fieldPrefix = "\"" + fieldName + "\":\""; + int valueStart = validReceipt.indexOf(fieldPrefix); + assertThat(valueStart).isGreaterThanOrEqualTo(0); + valueStart += fieldPrefix.length(); + int valueEnd = validReceipt.indexOf('"', valueStart); + assertThat(valueEnd).isGreaterThanOrEqualTo(valueStart); + assertThat(validReceipt.indexOf(fieldPrefix, valueEnd + 1)).isEqualTo(-1); + return validReceipt.substring(0, valueStart) + + encode(replacementBytes) + + validReceipt.substring(valueEnd); + } + private static String launchReadEvidenceJson( AuthoredWorldSourceEvidence source, net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, @@ -662,19 +763,6 @@ private static LaunchDescriptor launchDescriptor( return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence); } - private static LaunchDescriptor rawLaunchDescriptorForMalformedVersionStateSnapshot( - AuthoredWorldSourceEvidence source, - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState) { - LaunchDescriptor canonicalDescriptor = launchDescriptor(source, bundle, launchVersionState()); - return canonicalDescriptor.toBuilder() - .setAuthoredWorldBinding( - canonicalDescriptor.getAuthoredWorldBinding().toBuilder() - .setVersionStateEpoch(versionState.getVersionStateEpoch()) - .build()) - .build(); - } - private static net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle launchBundle() { String canonicalTenantId = sourceEvidence().canonicalTenantId().toString(); String artifactDigest = "sha256:" + "b".repeat(64); @@ -759,7 +847,8 @@ private static String validJson() { "gameSessionUriSan": "%s",%n\ "caCertificateSha256": "%s",%n\ "worldManagementUriSan": "%s",%n\ - "worldManagementLeafSha256": "%s"%n\ + "worldManagementLeafSha256": "%s",%n\ + "claimDigest": "%s"%n\ }%n\ """ .formatted( @@ -771,7 +860,8 @@ private static String validJson() { RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, CA_SHA, RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, - WORLD_LEAF_SHA); + WORLD_LEAF_SHA, + CLAIM_DIGEST); } private static X509Certificate certificate(String san, byte[] der, int basicConstraints) @@ -803,6 +893,16 @@ private static void assertInvalidSourceReceipt(String json) { assertInvalidSourceReceiptBytes(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); } + private static void assertInvalidSourceReceipt(Supplier receiptJson) { + byte[] bytes = receiptJson.get().getBytes(java.nio.charset.StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + bytes, RUN_ID, PROJECT_NAME, capability(), pins())) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + } + private static void assertInvalidSourceReceiptBytes(byte[] bytes) { assertThatThrownBy( () -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index d384b13ca3..c7dcb6a6c0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -28,6 +28,8 @@ import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.WorldManagementClient; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; @@ -60,7 +62,18 @@ class RunOwnedInitialAdmissionFixtureCoordinatorTest { private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; private static final String CAPABILITY_PATH = "fixture/capability.json"; private static final String SOURCE_RECEIPT_PATH = "fixture/source-receipt.json"; - private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final String CLAIM_DIGEST = "d".repeat(64); + private static final String GAME_SESSION_LEAF_SHA256 = "a".repeat(64); + private static final String CA_CERTIFICATE_SHA256 = "b".repeat(64); + private static final String WORLD_MANAGEMENT_LEAF_SHA256 = "c".repeat(64); + private static final String OPERATION_ID = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, RUN_ID, PROJECT_NAME, GAME_SESSION_LEAF_SHA256, CA_CERTIFICATE_SHA256) + .toString(); + private static final UUID CREATION_REQUEST_ID = + UUID.fromString("57341fb9-55ee-42f4-842e-6e6305c22411"); + private static final UUID CREATION_OPERATION_ID = + UUID.fromString("d156e17a-d759-4db5-a456-c082b5d74419"); private static final UUID SOURCE_OPERATION_ID = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); private static final UUID REALM_ID = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); @@ -91,6 +104,10 @@ void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsy .startRunOwnedInitialLaunch(any(), launchEvidence.capture()); assertThat(launchEvidence.getValue().sourceEvidence()) .isEqualTo(fixture.sourceReceipt.sourceEvidence()); + assertThat(launchEvidence.getValue().creationEvidence()) + .isEqualTo(fixture.sourceReceipt.creationEvidence()); + assertThat(launchEvidence.getValue().fixturePolicySeal()) + .isEqualTo(fixture.sourceReceipt.fixturePolicySeal()); assertThat(launchEvidence.getValue().publishedReleaseBundle()) .isEqualTo(fixture.sourceReceipt.launchReadEvidence().publishedReleaseBundle()); assertThat(launchEvidence.getValue().launchDescriptor()) @@ -361,7 +378,8 @@ void changedOwnerReadEvidenceAcrossRetriesIsRejectedBeforeSecondLaunch() { .when(fixture.ownerService) .registerPublicSharedFixtureCatalog(any()); var changedReceipt = - withPublishedReleaseBundleRef(fixture.sourceReceipt, "owner-release-ref-changed"); + withPublishedReleaseBundleRef( + fixture.capability, fixture.sourceReceipt, "owner-release-ref-changed"); try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { capabilityLoader @@ -657,11 +675,12 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { false, "SHARED", "ALLOW_NEW", - "a".repeat(64), + GAME_SESSION_LEAF_SHA256, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - "b".repeat(64), + CA_CERTIFICATE_SHA256, RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64)); + WORLD_MANAGEMENT_LEAF_SHA256, + CLAIM_DIGEST); RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = sourceReceipt(capability, 29L); GameInstanceDto target = @@ -868,6 +887,31 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec sourceGameRowId, sourceGameTenantKey, provenanceKind)); + var launchRead = launchReadEvidence(capability, evidence); + String creationRequestDigest = + GameTenantCreationDigest.requestDigest( + targetNamespace, CREATION_REQUEST_ID, sourceGameTenantKey, worldDisplayName, null); + FreshTenantCreationEvidence creationEvidence = + new FreshTenantCreationEvidence( + 1, + targetNamespace, + CREATION_REQUEST_ID, + CREATION_OPERATION_ID, + creationRequestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + GameTenantCreationDigest.evidenceDigest( + targetNamespace, + CREATION_REQUEST_ID, + CREATION_OPERATION_ID, + creationRequestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + var policySeal = fixturePolicySeal(capability, creationEvidence, evidence, launchRead); return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, capability.runId(), @@ -880,12 +924,16 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec capability.worldManagementUriSan(), capability.worldManagementLeafSha256(), evidence, - launchReadEvidence(capability, evidence)); + launchRead, + creationEvidence, + policySeal); } private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt withPublishedReleaseBundleRef( - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt, String bundleRef) { + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt, + String bundleRef) { var original = receipt.launchReadEvidence(); var changedBundle = original.publishedReleaseBundle().toBuilder() @@ -904,6 +952,9 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec original.versionState(), original.gameTemplateId(), receipt.fixtureOperationId())); + var changedPolicySeal = + fixturePolicySeal( + capability, receipt.creationEvidence(), receipt.sourceEvidence(), changedReadEvidence); return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( receipt.schema(), receipt.runId(), @@ -916,7 +967,38 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec receipt.worldManagementUriSan(), receipt.worldManagementLeafSha256(), receipt.sourceEvidence(), - changedReadEvidence); + changedReadEvidence, + receipt.creationEvidence(), + changedPolicySeal); + } + + private static RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixturePolicySeal( + RunOwnedInitialAdmissionFixtureCapability capability, + FreshTenantCreationEvidence creationEvidence, + AuthoredWorldSourceEvidence sourceEvidence, + RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence launchReadEvidence) { + var wireLaunchRead = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + launchReadEvidence.schema(), + launchReadEvidence.gameTemplateId(), + launchReadEvidence.publishedReleaseBundle(), + launchReadEvidence.versionAssetArtifactState(), + launchReadEvidence.versionState(), + launchReadEvidence.launchDescriptor()); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + RunOwnedInitialAdmissionFixtureCapability.toWireCapability(capability), + creationEvidence, + sourceEvidence, + wireLaunchRead); + UUID fixtureOperationId = UUID.fromString(capability.operationId()); + return new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, + fixtureOperationId, + requestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + fixtureOperationId, requestDigest)); } private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence launchReadEvidence( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java index 05970d7289..98b317b2c9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java @@ -36,7 +36,7 @@ void captureRequiresAWritableOwnerTransactionBeforeReadingAnyRuntimeRow() { var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); var tenant = freshTenant(); - assertThatThrownBy(() -> repository.capture(tenant, 92L, null)) + assertThatThrownBy(() -> repository.capture(tenant, 92L, null, null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable owner transaction"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java index 64fbccd3a4..d067390ddf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryTest.java @@ -35,18 +35,27 @@ void clearTransactionContext() { } @Test - void reserveRejectsAnIdentityBeyondTheV28IntentWidthBeforeOwnerReads() { + void selectorsAcceptV34_3WidthAndRejectBeyond128BeforeOwnerReads() { DSLContext dsl = mock(DSLContext.class); var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); var launch = mock(CanonicalGameInstanceLaunchAssociationRepository.class); var repository = new CanonicalInitialAdmissionIntentRepository(dsl, catalog, launch); - String requestId = "r".repeat(121); - assertThatThrownBy(() -> repository.reserve(holdRequest(requestId), lifecycleRequest())) + assertThat(repository.read(NAMESPACE, "r".repeat(121))).isEmpty(); + assertThat(repository.read(NAMESPACE, "r".repeat(128))).isEmpty(); + verifyNoInteractions(catalog, launch); + + DSLContext overflowDsl = mock(DSLContext.class); + var overflowCatalog = mock(GameSessionCanonicalRealmCatalogRepository.class); + var overflowLaunch = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var overflowRepository = + new CanonicalInitialAdmissionIntentRepository(overflowDsl, overflowCatalog, overflowLaunch); + + assertThatThrownBy(() -> overflowRepository.read(NAMESPACE, "r".repeat(129))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("120-character intent column"); + .hasMessageContaining("128-character intent column"); - verifyNoInteractions(dsl, catalog, launch); + verifyNoInteractions(overflowDsl, overflowCatalog, overflowLaunch); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java index a5f3d585fd..9285325c9e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java @@ -2,16 +2,88 @@ 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 java.sql.Connection; +import java.sql.SQLException; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.jdbc.datasource.AbstractDataSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; class CanonicalInitialAdmissionRepositoryTest { + @Test + void incompleteHumanReserveCommitAndAbortDenyBeforeAnyOwnerStorageInteraction() { + var dsl = mock(DSLContext.class); + var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); + var pointers = mock(GameSessionCanonicalAdmissionPointerRepository.class); + var repository = new CanonicalInitialAdmissionRepository(dsl, catalog, pointers); + var request = canonicalRequest(); + var world = worldProof(request); + assertThatThrownBy(() -> repository.reserve(request)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); + assertThatThrownBy(() -> repository.commit(request, world)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); + assertThatThrownBy(() -> repository.abort(request, "Missing protection")) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class); + verifyNoInteractions(dsl, catalog, pointers); + } + + @Test + void proxiedHumanDenialsDoNotAcquireTransactionOrDatabaseConnection() { + var dsl = mock(DSLContext.class); + var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); + var pointers = mock(GameSessionCanonicalAdmissionPointerRepository.class); + var repository = new CanonicalInitialAdmissionRepository(dsl, catalog, pointers); + var dataSource = new RefusingDataSource(); + var transactionManager = new DataSourceTransactionManager(dataSource); + var proxyFactory = new ProxyFactory(repository); + proxyFactory.addAdvice( + new TransactionInterceptor(transactionManager, new AnnotationTransactionAttributeSource())); + var proxied = (CanonicalInitialAdmissionRepository) proxyFactory.getProxy(); + var request = canonicalRequest(); + var world = worldProof(request); + + assertThatThrownBy(() -> proxied.reserve(request)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class); + assertThatThrownBy(() -> proxied.commit(request, world)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class); + assertThatThrownBy(() -> proxied.abort(request, "Missing protection")) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class); + + assertThat(dataSource.connectionAttempts()).isZero(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + verifyNoInteractions(dsl, catalog, pointers); + } + @Test void pointerAndAuditVersionsUseValueEqualityBeyondLongCache() { Long attemptVersion = Long.valueOf(129L); @@ -102,7 +174,7 @@ private static Map validOpenFields() { fields.put("canonical_game_instance_id", uuid(4)); fields.put("canonical_version_id", uuid(5)); fields.put("initial_admission_request_id", "initial-admission-request"); - fields.put("initial_admission_request_digest", "a".repeat(64)); + fields.put("initial_admission_request_digest", requestDigest()); fields.put("initial_admission_origin_kind", "NO_PRIOR_POINTER"); fields.put("initial_admission_prior_pointer_version", null); fields.put("initial_admission_active_epoch", 82L); @@ -115,11 +187,92 @@ private static Map validOpenFields() { return fields; } + private static CanonicalInitialAdmissionRequest canonicalRequest() { + CanonicalInitialAdmissionOwnerProof proof = committedProof(); + return new CanonicalInitialAdmissionRequest( + proof.targetNamespace(), + proof.canonicalTenantId(), + proof.worldSlug(), + proof.realmId(), + proof.playableStateNamespaceId(), + proof.playableStateScope(), + proof.canonicalGameInstanceId(), + proof.canonicalVersionId(), + proof.activeLifecycleEpoch(), + proof.expectedCatalogRevision(), + proof.originKind(), + proof.expectedPriorPointerVersion(), + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.holdId(), + proof.holdFence(), + proof.holdBindingDigest()); + } + + private static CanonicalInitialAdmissionWorldProof worldProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionWorldProof( + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + "ACTIVE", + request.activeLifecycleEpoch(), + request.originKind(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + } + + private static final class RefusingDataSource extends AbstractDataSource { + private final AtomicInteger connectionAttempts = new AtomicInteger(); + + @Override + public Connection getConnection() throws SQLException { + connectionAttempts.incrementAndGet(); + throw new SQLException("Human admission denial must not acquire a database connection"); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + return getConnection(); + } + + int connectionAttempts() { + return connectionAttempts.get(); + } + } + + private static String requestDigest() { + return CanonicalInitialAdmissionRequest.computeRequestDigest( + "gameplay", + uuid(1), + "demo-world", + uuid(2), + uuid(3), + "SHARED", + uuid(4), + uuid(5), + 82L, + 41L, + OriginKind.NO_PRIOR_POINTER, + null, + "initial-admission-request"); + } + private static CanonicalInitialAdmissionOwnerProof committedProof() { return new CanonicalInitialAdmissionOwnerProof( CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, "initial-admission-request", - "a".repeat(64), + requestDigest(), "gameplay", uuid(1), "demo-world", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java index b1d81169f7..c72dea5c2a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -2,6 +2,8 @@ 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 java.util.UUID; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; @@ -9,6 +11,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; class GameSessionCanonicalRealmCatalogRepositoryTest { @@ -18,6 +21,22 @@ class GameSessionCanonicalRealmCatalogRepositoryTest { private static final UUID INTAKE_REQUEST_ID = uuid(3); private static final UUID CREATE_REQUEST_ID = uuid(4); + @Test + void fixturePublicMethodsRejectLegacyDslOnlyCompositionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionCanonicalRealmCatalogRepository repository = + new GameSessionCanonicalRealmCatalogRepository(dsl); + + assertThatThrownBy(() -> repository.establishVerifiedFixtureRealm(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Explicit owner transaction composition"); + assertThatThrownBy(() -> repository.readVerifiedFixtureRealm(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Explicit owner transaction composition"); + + verifyNoInteractions(dsl); + } + @Test void explicitPublicRequestPreservesRealmSelectorAndOpaqueOwnerPolicyExactly() { CreateCanonicalRealmCatalogRequest request = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java index cc4523e186..9154552204 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryTest.java @@ -25,7 +25,7 @@ void ownerWriteRequiresWritableTransactionBeforeAnyDatabaseRead() { DSLContext dsl = mock(DSLContext.class); var repository = new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE); - assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null)) + assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null, null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable owner transaction"); @@ -39,7 +39,7 @@ void refusesReadOnlyOwnerTransactionBeforeAnyOwnerLookup() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); - assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null)) + assertThatThrownBy(() -> repository.createStarting(null, null, null, null, null, null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable owner transaction"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java index d003c5c09e..67904e3e17 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; +import java.util.UUID; import org.jooq.DSLContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; @@ -21,7 +22,7 @@ void doesNotReadOrWriteOutsideTheWritableOwnerTransaction() { GameSessionFreshTenantAssociationRepository repository = new GameSessionFreshTenantAssociationRepository(dsl); - assertThatThrownBy(() -> repository.associateFresh(null, null, null)) + assertThatThrownBy(() -> repository.associateFresh(null, null, null, null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable owner transaction"); @@ -36,10 +37,23 @@ void rejectsReadOnlyOwnerTransactionBeforeTouchingStorage() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); - assertThatThrownBy(() -> repository.associateFresh(null, null, null)) + assertThatThrownBy(() -> repository.associateFresh(null, null, null, null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable owner transaction"); verifyNoInteractions(dsl); } + + @Test + void canonicalTenantReadRejectsLegacyDslOnlyCompositionBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + GameSessionFreshTenantAssociationRepository repository = + new GameSessionFreshTenantAssociationRepository(dsl); + + assertThatThrownBy(() -> repository.readByCanonicalTenantId(UUID.randomUUID())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Explicit owner transaction composition"); + + verifyNoInteractions(dsl); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java index 08f92fe291..c3288fa3a5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java @@ -118,6 +118,7 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { assertThat(configured) .containsExactly( "game_session.v1.GameSessionService/Ping", + "game_session.v1.GameSessionControlPlaneService/GetRunOwnedFixtureLaunchAssociation", METHOD, "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead", "game_session.v1.GameSessionService/AuthorizeStartSession") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java index 9d5bd453e3..e12fc8a02f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java @@ -124,6 +124,7 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { assertThat(configured) .containsExactly( "game_session.v1.GameSessionService/Ping", + "game_session.v1.GameSessionControlPlaneService/GetRunOwnedFixtureLaunchAssociation", "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", METHOD, "game_session.v1.GameSessionService/AuthorizeStartSession") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java new file mode 100644 index 0000000000..76c3bd0b98 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java @@ -0,0 +1,64 @@ +package net.firedevops.firemud.gamesession.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import net.firedevops.firemud.gamesession.v1.CanonicalInitialAdmissionOwnerProofReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GameSessionServiceGrpc; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class ProtectedGameSessionLoginGrpcInterceptorTest { + @Test + void passesActualDedicatedTerminalProofMethodToItsOwnerGuard() { + verifyBoundary( + CanonicalInitialAdmissionOwnerProofReadServiceGrpc + .getGetCanonicalInitialAdmissionOwnerProofMethod(), + true); + } + + @Test + void deniesUndeclaredControlPlaneAliasAndPlayerStartMethod() { + verifyBoundary( + CanonicalInitialAdmissionOwnerProofReadServiceGrpc + .getGetCanonicalInitialAdmissionOwnerProofMethod() + .toBuilder() + .setFullMethodName( + "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof") + .build(), + false); + verifyBoundary(GameSessionServiceGrpc.getStartSessionMethod(), false); + } + + @SuppressWarnings("unchecked") + private static void verifyBoundary( + MethodDescriptor method, boolean allowed) { + ServerCall call = mock(ServerCall.class); + ServerCallHandler handler = mock(ServerCallHandler.class); + Metadata headers = new Metadata(); + when(call.getMethodDescriptor()).thenReturn(method); + ServerCall.Listener expected = new ServerCall.Listener<>() {}; + when(handler.startCall(call, headers)).thenReturn(expected); + var result = + new ProtectedGameSessionLoginGrpcInterceptor().interceptCall(call, headers, handler); + if (allowed) { + assertThat(result).isSameAs(expected); + verify(call, never()).close(any(), any()); + verify(handler).startCall(call, headers); + } else { + verify(handler, never()).startCall(any(), any()); + ArgumentCaptor status = ArgumentCaptor.forClass(Status.class); + verify(call).close(status.capture(), any()); + assertThat(status.getValue().getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java index dce51a8bcd..c941080381 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java @@ -3,28 +3,23 @@ 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.never; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; -import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import java.util.stream.Stream; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.Request; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.IntentState; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionIntentSnapshot.SourceBinding; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; import net.firedevops.firemud.gamesession.service.impl.CanonicalInitialAdmissionHoldPreparation; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.DefaultTransactionStatus; @@ -47,192 +42,26 @@ void clearTransactionContext() { TransactionSynchronizationManager.clear(); } - @Test - void commitsIntentBeforeWorldAndAttachesInASeparateWritableReadCommittedTransaction() - throws Exception { - List events = new ArrayList<>(); - Fixtures fixtures = new Fixtures(events); - HoldIdentity identity = identity(HOLD_REQUEST, 7); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenAnswer( - invocation -> { - assertWritableTransaction(); - events.add("reserve"); - return snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST); - }); - when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - events.add("world"); - return identity; - }); - when(fixtures.repository.attach(HOLD_REQUEST, identity)) - .thenAnswer( - invocation -> { - assertWritableTransaction(); - events.add("attach"); - return snapshot(IntentState.HOLD_ATTACHED, identity, HOLD_REQUEST, LIFECYCLE_REQUEST); - }); - - CanonicalInitialAdmissionIntentSnapshot result = - fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST); - - assertThat(result.state()).isEqualTo(IntentState.HOLD_ATTACHED); - assertThat(events) - .containsExactly("begin", "reserve", "commit", "world", "begin", "attach", "commit"); - assertThat(fixtures.transactionManager.transactionDefinitions) - .allSatisfy( - definition -> { - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.isReadOnly()).isFalse(); - }); - } - - @Test - void reserveFailurePreventsWorldAcquisition() throws Exception { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenThrow(new IllegalStateException("reserve failed")); - - assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .hasMessage("reserve failed"); - - verifyNoInteractions(fixtures.worldClient); - verify(fixtures.repository, never()) - .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); - } - - @Test - void reserveCommitFailurePreventsWorldAcquisitionAndAttachment() throws Exception { - Fixtures fixtures = new Fixtures(new ArrayList<>(), true); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); - - assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("reserve commit failed"); - - verifyNoInteractions(fixtures.worldClient); - verify(fixtures.repository, never()) - .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); - assertThat(fixtures.transactionManager.transactionDefinitions).hasSize(1); + @ParameterizedTest + @MethodSource("humanRequestAndLifecycleVariants") + void humanRequestVariantsDenyBeforeOwnerAccessOrTransaction( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request lifecycle) { + assertHumanUnavailable(new Fixtures(), request, lifecycle); } - @Test - void remoteFailureLeavesPendingIntentAndRetryUsesTheSameExactRequest() throws Exception { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - HoldIdentity identity = identity(HOLD_REQUEST, 8); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); - when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenThrow(new IllegalStateException("World unavailable")) - .thenReturn(identity); - when(fixtures.repository.attach(HOLD_REQUEST, identity)) - .thenReturn(snapshot(IntentState.HOLD_ATTACHED, identity, HOLD_REQUEST, LIFECYCLE_REQUEST)); - - assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .hasMessage("World unavailable"); - assertThat(fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST).state()) - .isEqualTo(IntentState.HOLD_ATTACHED); - - verify(fixtures.repository, org.mockito.Mockito.times(2)) - .reserve(HOLD_REQUEST, LIFECYCLE_REQUEST); - verify(fixtures.worldClient, org.mockito.Mockito.times(2)) - .acquire(HOLD_REQUEST, LIFECYCLE_REQUEST); - verify(fixtures.repository).attach(HOLD_REQUEST, identity); + private static Stream humanRequestAndLifecycleVariants() { + return Stream.of( + Arguments.of(HOLD_REQUEST, LIFECYCLE_REQUEST), + Arguments.of(holdRequest("different-request"), LIFECYCLE_REQUEST), + Arguments.of(HOLD_REQUEST, lifecycleRequestWithChangedIdentity()), + Arguments.of( + holdRequest("closed-origin-request", InitialAdmissionOrigin.EXPECT_CLOSED, 1L), + LIFECYCLE_REQUEST)); } - @Test - void attachFailurePropagatesWithoutReplacingRequestOrCallingAnyCompensation() throws Exception { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - HoldIdentity identity = identity(HOLD_REQUEST, 9); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); - when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(identity); - when(fixtures.repository.attach(HOLD_REQUEST, identity)) - .thenThrow(new IllegalStateException("attach changed")); - - assertThatThrownBy(() -> fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .hasMessage("attach changed"); - - verify(fixtures.worldClient).acquire(HOLD_REQUEST, LIFECYCLE_REQUEST); - verify(fixtures.repository).attach(HOLD_REQUEST, identity); - verify(fixtures.repository, never()) - .reserve( - org.mockito.ArgumentMatchers.argThat(r -> r != HOLD_REQUEST), - org.mockito.ArgumentMatchers.any()); - } - - @Test - void exactAttachedOrTerminalReplayReturnsHistoricalSnapshotWithoutWorldCall() throws Exception { - for (IntentState state : List.of(IntentState.HOLD_ATTACHED, IntentState.TERMINAL)) { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - HoldIdentity retained = identity(HOLD_REQUEST, 10); - CanonicalInitialAdmissionIntentSnapshot historical = - snapshot(state, retained, HOLD_REQUEST, LIFECYCLE_REQUEST); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(historical); - - assertThat(fixtures.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .isSameAs(historical); - - verifyNoInteractions(fixtures.worldClient); - verify(fixtures.repository, never()) - .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); - } - } - - @Test - void wrongWorldIdentityAndChangedSnapshotTupleAreDenied() throws Exception { - Fixtures wrongIdentity = new Fixtures(new ArrayList<>()); - when(wrongIdentity.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); - when(wrongIdentity.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn(identity(holdRequest("different-request"), 11)); - - assertThatThrownBy(() -> wrongIdentity.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("did not echo"); - verify(wrongIdentity.repository, never()) - .attach(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); - - Fixtures changedSnapshot = new Fixtures(new ArrayList<>()); - when(changedSnapshot.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn( - snapshot( - IntentState.PENDING_HOLD, - null, - HOLD_REQUEST, - lifecycleRequestWithChangedIdentity())); - assertThatThrownBy(() -> changedSnapshot.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("changed the exact request tuple"); - verifyNoInteractions(changedSnapshot.worldClient); - - Fixtures changedAttach = new Fixtures(new ArrayList<>()); - HoldIdentity acquired = identity(HOLD_REQUEST, 12); - when(changedAttach.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn(snapshot(IntentState.PENDING_HOLD, null, HOLD_REQUEST, LIFECYCLE_REQUEST)); - when(changedAttach.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(acquired); - when(changedAttach.repository.attach(HOLD_REQUEST, acquired)) - .thenReturn( - snapshot( - IntentState.HOLD_ATTACHED, - identity(HOLD_REQUEST, 14), - HOLD_REQUEST, - LIFECYCLE_REQUEST)); - assertThatThrownBy(() -> changedAttach.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("exact World hold identity"); - } - - @Test - void ambientTransactionOrSynchronizationDeniesBeforeRepositoryOrWorldAccess() throws Exception { - Fixtures transaction = new Fixtures(new ArrayList<>()); + @org.junit.jupiter.api.Test + void ambientTransactionOrSynchronizationDeniesBeforeRepositoryOrWorldAccess() { + Fixtures transaction = new Fixtures(); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy(() -> transaction.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) .isInstanceOf(IllegalStateException.class) @@ -240,7 +69,7 @@ void ambientTransactionOrSynchronizationDeniesBeforeRepositoryOrWorldAccess() th verifyNoInteractions(transaction.repository, transaction.worldClient); TransactionSynchronizationManager.clear(); - Fixtures synchronization = new Fixtures(new ArrayList<>()); + Fixtures synchronization = new Fixtures(); TransactionSynchronizationManager.initSynchronization(); assertThatThrownBy(() -> synchronization.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) .isInstanceOf(IllegalStateException.class) @@ -248,56 +77,25 @@ void ambientTransactionOrSynchronizationDeniesBeforeRepositoryOrWorldAccess() th verifyNoInteractions(synchronization.repository, synchronization.worldClient); } - private static void assertWritableTransaction() { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + private static void assertHumanUnavailable( + Fixtures fixtures, + Request request, + WorldCanonicalInstanceLifecycleEvidence.Request lifecycle) { + assertThatThrownBy(() -> fixtures.preparation.prepare(request, lifecycle)) + .isInstanceOf( + net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); + verifyNoInteractions(fixtures.repository, fixtures.worldClient); + assertThat(fixtures.transactionManager.transactionDefinitions).isEmpty(); } - private static CanonicalInitialAdmissionIntentSnapshot snapshot( - IntentState state, - HoldIdentity identity, - Request holdRequest, - WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { - return new CanonicalInitialAdmissionIntentSnapshot( - holdRequest, - lifecycleRequest, - state, - identity, - new SourceBinding( - NAMESPACE, - TENANT, - "world", - REALM, - PLAYABLE_NAMESPACE, - "SHARED", - true, - true, - 1L, - uuid(20), - SHA256, - SHA256, - uuid(21), - 1L, - INSTANCE, - 1L, - VERSION, - 1L, - "control-request-1", - "launch-descriptor-1", - 1L, - 1L, - SHA256, - SHA256, - SHA256), - java.time.Instant.parse("2026-01-01T00:00:00Z"), - java.time.Instant.parse("2026-01-01T00:00:00Z"), - state == IntentState.TERMINAL ? java.time.Instant.parse("2026-01-01T00:01:00Z") : null); + private static Request holdRequest(String requestId) { + return holdRequest(requestId, InitialAdmissionOrigin.NO_PRIOR_POINTER, null); } - private static Request holdRequest(String requestId) { + private static Request holdRequest( + String requestId, InitialAdmissionOrigin origin, Long priorPointerVersion) { String requestDigest = CanonicalInitialAdmissionRequest.computeRequestDigest( NAMESPACE, @@ -310,8 +108,8 @@ private static Request holdRequest(String requestId) { VERSION, 2L, 1L, - CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, - null, + CanonicalInitialAdmissionRequest.OriginKind.valueOf(origin.name()), + priorPointerVersion, requestId); return new Request( NAMESPACE, @@ -325,9 +123,9 @@ private static Request holdRequest(String requestId) { 2L, requestId, requestDigest, - InitialAdmissionOrigin.NO_PRIOR_POINTER, + origin, 1L, - null); + priorPointerVersion); } private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest() { @@ -367,10 +165,6 @@ private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest( SHA256); } - private static HoldIdentity identity(Request request, int id) { - return new WorldCanonicalInitialAdmissionHold.HoldIdentity(request, uuid(id), uuid(id + 1)); - } - private static UUID uuid(int value) { return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); } @@ -383,12 +177,8 @@ private static final class Fixtures { private final RecordingTransactionManager transactionManager; private final CanonicalInitialAdmissionHoldPreparation preparation; - private Fixtures(List events) { - this(events, false); - } - - private Fixtures(List events, boolean failFirstCommit) { - this.transactionManager = new RecordingTransactionManager(events, failFirstCommit); + private Fixtures() { + this.transactionManager = new RecordingTransactionManager(); this.preparation = new CanonicalInitialAdmissionHoldPreparation(repository, worldClient, transactionManager); } @@ -396,15 +186,9 @@ private Fixtures(List events, boolean failFirstCommit) { private static final class RecordingTransactionManager extends AbstractPlatformTransactionManager { - private final List events; private final List transactionDefinitions = new ArrayList<>(); - private final boolean failFirstCommit; - private int commitCount; - private RecordingTransactionManager(List events, boolean failFirstCommit) { - this.events = events; - this.failFirstCommit = failFirstCommit; - } + private RecordingTransactionManager() {} @Override protected Object doGetTransaction() { @@ -414,21 +198,12 @@ protected Object doGetTransaction() { @Override protected void doBegin(Object transaction, TransactionDefinition definition) { transactionDefinitions.add(definition); - events.add("begin"); } @Override - protected void doCommit(DefaultTransactionStatus status) { - commitCount++; - events.add("commit"); - if (failFirstCommit && commitCount == 1) { - throw new IllegalStateException("reserve commit failed"); - } - } + protected void doCommit(DefaultTransactionStatus status) {} @Override - protected void doRollback(DefaultTransactionStatus status) { - events.add("rollback"); - } + protected void doRollback(DefaultTransactionStatus status) {} } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java index a953c225ed..9a827925d6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java @@ -2,9 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -18,7 +16,6 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; -import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; @@ -38,8 +35,7 @@ class DatabaseCanonicalInitialAdmissionServiceTest { mock(GameSessionCanonicalAdmissionPointerRepository.class); private final CanonicalInitialAdmissionWorldVerifier worldVerifier = mock(CanonicalInitialAdmissionWorldVerifier.class); - private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(0); - private int readbackCount; + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); private final DatabaseCanonicalInitialAdmissionService service = new DatabaseCanonicalInitialAdmissionService( repository, pointerRepository, worldVerifier, transactionManager); @@ -49,140 +45,6 @@ void clearTransaction() { TransactionSynchronizationManager.clear(); } - @Test - void bindUsesWritableReadCommittedTransactionsAndKeepsRemoteAndReadbackOutside() { - CanonicalInitialAdmissionRequest request = request(); - CanonicalInitialAdmissionOwnerProof pending = pendingProof(request); - CanonicalInitialAdmissionOwnerProof committed = committedProof(request); - CanonicalInitialAdmissionWorldProof worldProof = worldProof(request); - - doAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - return null; - }) - .when(repository) - .reserve(request); - doAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - return null; - }) - .when(repository) - .commit(request, worldProof, null); - when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(); - return Optional.of(readbackCount++ == 0 ? pending : committed); - }); - when(worldVerifier.verify(request)) - .thenAnswer( - invocation -> { - assertOutsideTransaction(); - return worldProof; - }); - - assertThat(service.bind(request)).isEqualTo(committed); - - verify(repository).reserve(request); - verify(repository).commit(request, worldProof, null); - verify(repository, times(2)) - .read(request.targetNamespace(), request.initialAdmissionRequestId()); - verify(worldVerifier).verify(request); - verifyNoInteractions(pointerRepository); - assertThat(transactionManager.settings) - .containsExactly(writableReadCommittedRequiresNew(), writableReadCommittedRequiresNew()); - assertThat(transactionManager.commitCount).isEqualTo(2); - assertThat(transactionManager.rollbackCount).isZero(); - } - - @Test - void abortUsesWritableReadCommittedTransactionsAndReadsTerminalProofAfterCommit() { - CanonicalInitialAdmissionRequest request = request(); - CanonicalInitialAdmissionOwnerProof pending = pendingProof(request); - CanonicalInitialAdmissionOwnerProof aborted = abortedProof(request); - - doAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - return null; - }) - .when(repository) - .reserve(request); - doAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - return null; - }) - .when(repository) - .abort(request, null, "test abort"); - when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(); - return Optional.of(readbackCount++ == 0 ? pending : aborted); - }); - - assertThat(service.abort(request, "test abort")).isEqualTo(aborted); - - verify(repository).reserve(request); - verify(repository).abort(request, null, "test abort"); - verify(repository, times(2)) - .read(request.targetNamespace(), request.initialAdmissionRequestId()); - verifyNoInteractions(pointerRepository, worldVerifier); - assertThat(transactionManager.settings) - .containsExactly(writableReadCommittedRequiresNew(), writableReadCommittedRequiresNew()); - assertThat(transactionManager.commitCount).isEqualTo(2); - assertThat(transactionManager.rollbackCount).isZero(); - } - - @Test - void bindDoesNotReturnSuccessWhenOwnerCommitFails() { - transactionManager.failOnCommitNumber = 2; - CanonicalInitialAdmissionRequest request = request(); - CanonicalInitialAdmissionOwnerProof pending = pendingProof(request); - CanonicalInitialAdmissionWorldProof worldProof = worldProof(request); - - doAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - return null; - }) - .when(repository) - .reserve(request); - doAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - return null; - }) - .when(repository) - .commit(request, worldProof, null); - when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(); - return Optional.of(pending); - }); - when(worldVerifier.verify(request)) - .thenAnswer( - invocation -> { - assertOutsideTransaction(); - return worldProof; - }); - - assertThatThrownBy(() -> service.bind(request)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("simulated transaction commit failure"); - - verify(repository).reserve(request); - verify(repository).commit(request, worldProof, null); - verify(repository, times(1)) - .read(request.targetNamespace(), request.initialAdmissionRequestId()); - verify(worldVerifier).verify(request); - assertThat(transactionManager.commitCount).isEqualTo(2); - } - @Test void bindRejectsWritableAmbientTransactionBeforeAnyCollaboratorAccess() { assertAmbientTransactionRejected(false, () -> service.bind(request())); @@ -204,22 +66,31 @@ void abortRejectsReadOnlyAmbientTransactionBeforeAnyCollaboratorAccess() { } @Test - void committedReplayReturnsStoredOwnerProofWithoutWorldVerification() { + void humanBindAndAbortDenyBeforeReservationTransactionOrWorldAccess() { + assertThatThrownBy(() -> service.bind(request())) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); + assertThatThrownBy(() -> service.abort(request(), "Human abort")) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class); + verifyNoInteractions(repository, pointerRepository, worldVerifier); + assertThat(transactionManager.settings).isEmpty(); + } + + @Test + void explicitHumanOwnerReadReturnsStoredProofWithoutMutationOrWorldVerification() { CanonicalInitialAdmissionRequest request = request(); CanonicalInitialAdmissionOwnerProof committed = committedProof(request); when(repository.read(request.targetNamespace(), request.initialAdmissionRequestId())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(); - return Optional.of(committed); - }); - - assertThat(service.bind(request)).isEqualTo(committed); - - verify(repository).reserve(request); + .thenReturn(Optional.of(committed)); + assertThat(service.read(request.targetNamespace(), request.initialAdmissionRequestId())) + .isEqualTo(committed); verify(repository).read(request.targetNamespace(), request.initialAdmissionRequestId()); verifyNoInteractions(pointerRepository, worldVerifier); - assertThat(transactionManager.settings).containsExactly(writableReadCommittedRequiresNew()); + assertThat(transactionManager.settings).isEmpty(); } private void assertAmbientTransactionRejected(boolean readOnly, Runnable operation) { @@ -234,25 +105,6 @@ private void assertAmbientTransactionRejected(boolean readOnly, Runnable operati assertThat(transactionManager.settings).isEmpty(); } - private static void assertWritableReadCommittedTransaction() { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - } - - private static void assertOutsideTransaction() { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - } - - private static TransactionSettings writableReadCommittedRequiresNew() { - return new TransactionSettings( - TransactionDefinition.PROPAGATION_REQUIRES_NEW, - TransactionDefinition.ISOLATION_READ_COMMITTED, - false); - } - private static CanonicalInitialAdmissionRequest request() { String targetNamespace = "initial-admission-test"; UUID tenantId = uuid("11111111-1111-4111-8111-111111111111"); @@ -302,34 +154,6 @@ private static CanonicalInitialAdmissionRequest request() { "sha256:" + "a".repeat(64)); } - private static CanonicalInitialAdmissionOwnerProof pendingProof( - CanonicalInitialAdmissionRequest request) { - return new CanonicalInitialAdmissionOwnerProof( - Outcome.PENDING, - request.initialAdmissionRequestId(), - request.requestDigest(), - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - request.realmId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - request.canonicalGameInstanceId(), - request.canonicalVersionId(), - request.activeLifecycleEpoch(), - request.expectedCatalogRevision(), - request.originKind(), - request.expectedPriorPointerVersion(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest(), - null, - null, - null, - false, - null); - } - private static CanonicalInitialAdmissionOwnerProof committedProof( CanonicalInitialAdmissionRequest request) { return new CanonicalInitialAdmissionOwnerProof( @@ -358,57 +182,6 @@ private static CanonicalInitialAdmissionOwnerProof committedProof( Instant.parse("2026-10-10T00:00:00Z")); } - private static CanonicalInitialAdmissionOwnerProof abortedProof( - CanonicalInitialAdmissionRequest request) { - return new CanonicalInitialAdmissionOwnerProof( - Outcome.ABORTED, - request.initialAdmissionRequestId(), - request.requestDigest(), - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - request.realmId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - request.canonicalGameInstanceId(), - request.canonicalVersionId(), - request.activeLifecycleEpoch(), - request.expectedCatalogRevision(), - request.originKind(), - request.expectedPriorPointerVersion(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest(), - null, - null, - "sha256:" + "c".repeat(64), - true, - Instant.parse("2026-10-10T00:00:00Z")); - } - - private static CanonicalInitialAdmissionWorldProof worldProof( - CanonicalInitialAdmissionRequest request) { - return new CanonicalInitialAdmissionWorldProof( - request.initialAdmissionRequestId(), - request.requestDigest(), - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - request.realmId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - request.canonicalGameInstanceId(), - request.canonicalVersionId(), - "ACTIVE", - request.activeLifecycleEpoch(), - request.originKind(), - request.expectedCatalogRevision(), - request.expectedPriorPointerVersion(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest()); - } - private static UUID uuid(String value) { return UUID.fromString(value); } @@ -417,13 +190,6 @@ private record TransactionSettings(int propagation, int isolation, boolean readO private static final class RecordingTransactionManager implements PlatformTransactionManager { private final List settings = new ArrayList<>(); - private int commitCount; - private int rollbackCount; - private int failOnCommitNumber; - - private RecordingTransactionManager(int failOnCommitNumber) { - this.failOnCommitNumber = failOnCommitNumber; - } @Override public TransactionStatus getTransaction(TransactionDefinition definition) { @@ -442,16 +208,11 @@ public TransactionStatus getTransaction(TransactionDefinition definition) { @Override public void commit(TransactionStatus status) { - commitCount++; TransactionSynchronizationManager.clear(); - if (commitCount == failOnCommitNumber) { - throw new IllegalStateException("simulated transaction commit failure"); - } } @Override public void rollback(TransactionStatus status) { - rollbackCount++; TransactionSynchronizationManager.clear(); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 81fc275ae3..bd16af4c2b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -225,7 +225,8 @@ void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority(String l @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000001", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); configureRunOwnedWorld(request); var first = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); @@ -250,7 +251,8 @@ void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActiv @Test void runOwnedLaunchUsesOpaqueOwnerReferenceWithoutCallingDeniedReadRpcs() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000010", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); String opaqueBundleRef = "gds:owner-ref:immutable-release-77"; runOwnedBundleRefOverride = opaqueBundleRef; configureRunOwnedWorld(request); @@ -286,7 +288,8 @@ void runOwnedLaunchUsesOpaqueOwnerReferenceWithoutCallingDeniedReadRpcs() { @Test void runOwnedLaunchRejectsDifferentValidResolveDescriptorBeforeMutation() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000012", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); var ownerEvidence = launchEvidence(request); runOwnedDescriptorOverride = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( @@ -317,7 +320,8 @@ request, sourceEvidence(request), "gds:owner-ref:different-release") @Test void runOwnedLaunchRejectsOwnerVersionEpochMismatchBeforeWorldPreparation() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000013", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); var original = launchEvidence(request); var changed = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( @@ -343,7 +347,8 @@ void runOwnedLaunchRejectsOwnerVersionEpochMismatchBeforeWorldPreparation() { @Test void runOwnedLaunchRejectsUnrecognizedOwnerVersionStateBeforeWorldPreparation() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000015", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); var original = launchEvidence(request); var unchecked = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.createUncheckedForServicePreflightTests( @@ -370,7 +375,8 @@ void runOwnedLaunchRejectsUnrecognizedOwnerVersionStateBeforeWorldPreparation() @Test void runOwnedLaunchRejectsOwnerVersionIdentityMismatchBeforeWorldPreparation() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000014", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); var original = launchEvidence(request); var changed = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( @@ -399,7 +405,8 @@ void runOwnedLaunchRejectsOwnerVersionIdentityMismatchBeforeWorldPreparation() { @Test void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000002", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); AtomicReference worldState = configureRunOwnedWorld(request); service.startRunOwnedInitialLaunch(request, launchEvidence(request)); clearInvocations(stateService, worldManagementClient); @@ -428,7 +435,8 @@ void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutatio @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000003", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); AtomicReference worldState = configureRunOwnedWorld(request); AtomicInteger prepareCalls = new AtomicInteger(); when(worldManagementClient.prepareWorldInstance( @@ -498,7 +506,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { @Test void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000004", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); AtomicReference worldState = configureRunOwnedWorld(request); doThrow(new IllegalStateException("activation response timed out")) .when(worldManagementClient) @@ -530,7 +539,8 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() @Test void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); configureRunOwnedWorld(request); service.startRunOwnedInitialLaunch(request, launchEvidence(request)); @@ -538,15 +548,21 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 43L), + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 43L), launchEvidence(request))); assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L), + new StartSessionRequest( + 1L, 4L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L), launchEvidence( - new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L)))); + new StartSessionRequest( + 1L, + 4L, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + 42L)))); assertEquals(1, store.size()); assertEquals(10L, store.get(10L).getId()); @@ -570,7 +586,8 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { @Test void runOwnedInitialLaunchRequestIdConflictsOnChangedAuthoredWorldSource() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000008", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); configureRunOwnedWorld(request); service.startRunOwnedInitialLaunch(request, launchEvidence(request)); @@ -610,7 +627,8 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedAuthoredWorldSource() { @Test void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerReadSnapshot() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000009", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); configureRunOwnedWorld(request); var original = launchEvidence(request); service.startRunOwnedInitialLaunch(request, original); @@ -648,7 +666,8 @@ void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerReadSnapshot() { @Test void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000006", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); AtomicReference worldState = configureRunOwnedWorld(request); doAnswer( invocation -> @@ -679,7 +698,8 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { @Test void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000007", 42L); + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); AtomicReference worldState = configureRunOwnedWorld(request); worldState.set( runOwnedWorldSnapshot( @@ -697,7 +717,8 @@ void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { assertEquals(1, store.size()); assertEquals( - "10000000-0000-4000-8000-000000000007", store.get(10L).getRunOwnedStartRequestId()); + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + store.get(10L).getRunOwnedStartRequestId()); assertEquals("STARTING", store.get(10L).getStatus()); verify(worldManagementClient, never()) .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java new file mode 100644 index 0000000000..ed0d110277 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java @@ -0,0 +1,434 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.UUID; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.FixtureCanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.FixtureCanonicalRealmCatalog; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.FreshTenantAssociation; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +class GameSessionFixtureLaunchAssociationReadGrpcServiceTest { + private static final String TARGET_NAMESPACE = "dev"; + private static final String WORLD_URI = "spiffe://firemud/ns/dev/sa/world-management-service"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + private static final UUID INTAKE_OPERATION_ID = + UUID.fromString("a05f8aae-b4dd-4e11-8a92-0271c60ec6c0"); + private static final UUID INTAKE_REQUEST_ID = + UUID.fromString("ce432a95-d19a-47bc-9266-874158e5990c"); + private static final UUID ASSOCIATION_OPERATION_ID = + UUID.fromString("a6fb2f17-747f-423e-a7cc-e8c577b6d44e"); + private static final UUID REALM_ID = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); + private static final UUID PLAYABLE_NAMESPACE_ID = + UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); + private static final UUID GAME_INSTANCE_UUID = + UUID.fromString("7556e829-d531-4c61-b8d4-350c8514c4f1"); + private static final String READ_REQUEST_ID = "90a5e6ef-12f4-49b4-8b07-00fa123d6f55"; + + @AfterEach + void tearDown() { + SessionContext.clear(); + } + + @Test + void returnsTheExactStartingCatalogPrivateKeysCreationSourceAndSeal() { + Fixture fixture = fixture(true, true); + RecordingObserver observer = + invoke(fixture, request(fixture.evidence), exactWorldContext(fixture.evidence)); + + assertNull(observer.failure); + assertTrue(observer.completed); + GetRunOwnedFixtureLaunchAssociationResponse response = observer.response; + assertNotNull(response); + var evidence = fixture.evidence; + var capability = evidence.fixtureCapability(); + var source = evidence.sourceEvidence(); + var creation = evidence.creationEvidence(); + var seal = evidence.fixturePolicySeal(); + assertEquals(READ_REQUEST_ID, response.getReadRequestId()); + assertEquals(TARGET_NAMESPACE, response.getTargetNamespace()); + assertEquals(capability.operationId(), response.getFixtureOperationId()); + assertEquals(seal.evidenceDigest(), response.getExpectedFixturePolicyEvidenceDigest()); + assertEquals(71L, response.getGameSessionTenantId()); + assertEquals(808L, response.getGameInstanceId()); + assertEquals(CANONICAL_TENANT_ID.toString(), response.getCanonicalTenantId()); + assertEquals(GAME_INSTANCE_UUID.toString(), response.getGameInstanceUuid()); + assertEquals( + evidence.publishedReleaseBundle().getCanonicalVersionId(), + response.getCanonicalVersionId()); + assertEquals(REALM_ID.toString(), response.getCanonicalRealmId()); + assertEquals(PLAYABLE_NAMESPACE_ID.toString(), response.getPlayableStateNamespaceId()); + assertEquals( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + response.getPlayableStateScope()); + assertEquals(1L, response.getCatalogRevision()); + assertEquals("STARTING", response.getCurrentGameInstanceStatus()); + assertEquals(0L, response.getCurrentRowVersion()); + assertEquals( + ByteString.copyFrom(evidence.fixturePolicyRequestBytes()), + response.getFixturePolicyRequestBytes()); + assertEquals(seal.operationId().toString(), response.getFixturePolicySealOperationId()); + assertEquals(seal.requestDigest(), response.getFixturePolicySealRequestDigest()); + assertEquals(seal.evidenceDigest(), response.getFixturePolicySealEvidenceDigest()); + assertEquals("1", source.sourceGameTenantKey()); + assertEquals(source.sourceGameTenantKey(), creation.sourceGameTenantKey()); + + InOrder order = inOrder(fixture.coordinator); + order.verify(fixture.coordinator).loadFixedVerifiedEvidenceForWorldPeer(); + order.verify(fixture.coordinator).readFixedFixtureLaunch(same(evidence)); + } + + @Test + void loadsFixedWorldEvidenceBeforeRejectingUnknownRequestFieldsWithoutReadingLaunchOwner() { + Fixture fixture = fixture(true, true); + var malformed = + request(fixture.evidence).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + + RecordingObserver observer = + invoke(fixture, malformed, exactWorldContext(fixture.evidence)); + + assertEquals(Status.Code.INVALID_ARGUMENT, status(observer.failure)); + assertNull(observer.response); + verify(fixture.coordinator).loadFixedVerifiedEvidenceForWorldPeer(); + verify(fixture.coordinator, never()).readFixedFixtureLaunch(any()); + } + + @Test + void rejectsNullRequestAfterAuthorizationAndDefaultOffChecksBeforeLoadingEvidence() { + Fixture fixture = fixture(true, true); + + RecordingObserver observer = + invoke(fixture, null, exactWorldContext(fixture.evidence)); + + assertEquals(Status.Code.INVALID_ARGUMENT, status(observer.failure)); + assertNull(observer.response); + verifyNoInteractions(fixture.coordinator); + } + + @Test + void rejectsChangedSelectorAfterLoadingFixedEvidenceAndBeforeLaunchOwnerRead() { + Fixture fixture = fixture(true, true); + GetRunOwnedFixtureLaunchAssociationRequest changed = + request(fixture.evidence).toBuilder() + .setFixtureOperationId("8dc28d55-1321-4661-82c6-13436df05468") + .build(); + + RecordingObserver observer = + invoke(fixture, changed, exactWorldContext(fixture.evidence)); + + assertEquals(Status.Code.INVALID_ARGUMENT, status(observer.failure)); + verify(fixture.coordinator).loadFixedVerifiedEvidenceForWorldPeer(); + verify(fixture.coordinator, never()).readFixedFixtureLaunch(any()); + } + + @Test + void mapsRetainedFixtureOwnerStateFailureToFailedPrecondition() { + Fixture fixture = fixture(true, true); + org.mockito.Mockito.doThrow( + new IllegalArgumentException("retained fixture evidence is invalid")) + .when(fixture.coordinator) + .loadFixedVerifiedEvidenceForWorldPeer(); + + RecordingObserver observer = + invoke(fixture, request(fixture.evidence), exactWorldContext(fixture.evidence)); + + assertEquals(Status.Code.FAILED_PRECONDITION, status(observer.failure)); + assertNull(observer.response); + verify(fixture.coordinator, never()).readFixedFixtureLaunch(any()); + } + + @Test + void rejectsWrongWorldIdentityOrRetainedLeafBeforeLaunchOwnerRead() { + Fixture fixture = fixture(true, true); + var request = request(fixture.evidence); + var wrongNamespace = + context( + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/other/sa/world-management-service") + .orElseThrow(), + fixture.evidence.fixtureCapability().worldManagementLeafSha256()); + RecordingObserver namespaceObserver = + invoke(fixture, request, wrongNamespace); + assertEquals(Status.Code.PERMISSION_DENIED, status(namespaceObserver.failure)); + + var wrongService = + context( + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/dev/sa/game-session-service") + .orElseThrow(), + fixture.evidence.fixtureCapability().worldManagementLeafSha256()); + RecordingObserver serviceObserver = + invoke(fixture, request, wrongService); + assertEquals(Status.Code.PERMISSION_DENIED, status(serviceObserver.failure)); + verifyNoInteractions(fixture.coordinator); + + var wrongLeaf = context(worldPeer(), "d".repeat(64)); + RecordingObserver leafObserver = + invoke(fixture, request, wrongLeaf); + assertEquals(Status.Code.PERMISSION_DENIED, status(leafObserver.failure)); + verify(fixture.coordinator).loadFixedVerifiedEvidenceForWorldPeer(); + verify(fixture.coordinator, never()).readFixedFixtureLaunch(any()); + } + + @Test + void defaultOffAndMissingCoordinatorFailWithoutFixedOrOwnerReads() { + Fixture disabled = fixture(false, true); + RecordingObserver disabledObserver = + invoke(disabled, request(disabled.evidence), exactWorldContext(disabled.evidence)); + assertEquals(Status.Code.FAILED_PRECONDITION, status(disabledObserver.failure)); + verifyNoInteractions(disabled.coordinator); + + Fixture missing = fixture(true, false); + RecordingObserver missingObserver = + invoke(missing, request(missing.evidence), exactWorldContext(missing.evidence)); + assertEquals(Status.Code.FAILED_PRECONDITION, status(missingObserver.failure)); + } + + private static Fixture fixture(boolean enabled, boolean withCoordinator) { + RunOwnedInitialAdmissionLaunchEvidence evidence = evidence(); + FixtureCanonicalInstanceLaunch launch = launch(evidence); + RunOwnedCanonicalLaunchPreparationOwner coordinator = + withCoordinator ? mock(RunOwnedCanonicalLaunchPreparationOwner.class) : null; + if (coordinator != null) { + when(coordinator.loadFixedVerifiedEvidenceForWorldPeer()) + .thenAnswer( + invocation -> { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + GrpcPeerCertificateEvidence certificate = GrpcPeerCertificateEvidence.current(); + if (peer == null + || !TARGET_NAMESPACE.equals(peer.namespace()) + || !"world-management-service".equals(peer.service()) + || !WORLD_URI.equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext() + || certificate == null + || !evidence + .fixtureCapability() + .worldManagementLeafSha256() + .equals(certificate.leafSha256())) { + throw new AdminAuthorizationException( + "Fixed fixture read requires the exact World workload peer and leaf"); + } + return evidence; + }); + when(coordinator.readFixedFixtureLaunch(same(evidence))).thenReturn(launch); + } + + GameSessionControlPlaneGrpcService service = + new GameSessionControlPlaneGrpcService( + mock(GameSessionCommandControlPlaneService.class), + mock(GameSessionRemoteControlPlaneService.class), + mock(GameSessionRuntimeControlPlaneReadService.class), + mock(GameSessionAdmissionPointerControlPlaneService.class), + mock(GameSessionOperatorControlPlaneService.class), + mock(GameSessionVersionUpgradeControlPlaneService.class), + new SimpleMeterRegistry()); + service.configureRunOwnedFixtureLaunchAssociationReadBoundary( + coordinator, enabled, TARGET_NAMESPACE); + return new Fixture(service, coordinator, evidence, launch); + } + + private static RunOwnedInitialAdmissionLaunchEvidence evidence() { + String operationId = RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(); + StartSessionRequest start = new StartSessionRequest(1L, 17L, operationId, 27L); + UUID requestId = UUID.fromString(operationId); + String tenantSlug = "fixture-tenant"; + String worldSlug = "demo"; + String worldDisplayName = "Demo World"; + long sourceGameRowId = 29L; + String sourceGameTenantKey = "1"; + String provenanceKind = "NEW_GAME_ROW"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + TARGET_NAMESPACE, + requestId, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + TARGET_NAMESPACE, + requestId, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + AuthoredWorldSourceDigest.evidenceDigest( + TARGET_NAMESPACE, + requestId, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)); + return RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create(start, source); + } + + private static FixtureCanonicalInstanceLaunch launch( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + var source = evidence.sourceEvidence(); + var creation = evidence.creationEvidence(); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST_ID, source); + IntakeReceipt intakeReceipt = + new IntakeReceipt( + INTAKE_OPERATION_ID, + INTAKE_REQUEST_ID, + intakeRequestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + INTAKE_OPERATION_ID, intakeRequestDigest, source.evidenceDigest())); + var capability = evidence.fixtureCapability(); + CanonicalRealmCatalogSnapshot snapshot = + new CanonicalRealmCatalogSnapshot( + TARGET_NAMESPACE, + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + REALM_ID, + capability.realmSlug(), + capability.realmDisplayName(), + capability.visible(), + capability.publicProductionRealm(), + capability.stateScope(), + PLAYABLE_NAMESPACE_ID, + capability.characterCreationPolicy(), + 1L, + creation.creationRequestId(), + "sha256:" + "e".repeat(64), + "sha256:" + "f".repeat(64), + intakeReceipt); + FreshTenantAssociation association = + new FreshTenantAssociation( + TARGET_NAMESPACE, source.canonicalTenantId(), 71L, ASSOCIATION_OPERATION_ID, creation); + return new FixtureCanonicalInstanceLaunch( + 808L, + GAME_INSTANCE_UUID, + new FixtureCanonicalRealmCatalog(snapshot, association), + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, + 0L); + } + + private static GetRunOwnedFixtureLaunchAssociationRequest request( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + return GetRunOwnedFixtureLaunchAssociationRequest.newBuilder() + .setReadRequestId(READ_REQUEST_ID) + .setTargetNamespace(TARGET_NAMESPACE) + .setFixtureOperationId(evidence.fixtureCapability().operationId()) + .setExpectedFixturePolicyEvidenceDigest(evidence.fixturePolicySeal().evidenceDigest()) + .build(); + } + + private static RecordingObserver invoke( + Fixture fixture, GetRunOwnedFixtureLaunchAssociationRequest request, Context callerContext) { + RecordingObserver observer = + new RecordingObserver<>(); + SessionContext.clear(); + Context previous = callerContext.attach(); + try { + fixture.service.getRunOwnedFixtureLaunchAssociation(request, observer); + } finally { + callerContext.detach(previous); + } + return observer; + } + + private static Context exactWorldContext(RunOwnedInitialAdmissionLaunchEvidence evidence) { + return context(worldPeer(), evidence.fixtureCapability().worldManagementLeafSha256()); + } + + private static GrpcPeerIdentity worldPeer() { + return GrpcPeerIdentity.parseUri(WORLD_URI).orElseThrow(); + } + + private static Context context(GrpcPeerIdentity peer, String leafSha256) { + GrpcPeerCertificateEvidence certificate = mock(GrpcPeerCertificateEvidence.class); + when(certificate.leafSha256()).thenReturn(leafSha256); + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); + } + + private static Status.Code status(Throwable failure) { + assertNotNull(failure); + return Status.fromThrowable(failure).getCode(); + } + + private static final class RecordingObserver implements StreamObserver { + private T response; + private Throwable failure; + private boolean completed; + + @Override + public void onNext(T value) { + response = value; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable).asRuntimeException(); + } + + @Override + public void onCompleted() { + completed = true; + } + } + + private record Fixture( + GameSessionControlPlaneGrpcService service, + RunOwnedCanonicalLaunchPreparationOwner coordinator, + RunOwnedInitialAdmissionLaunchEvidence evidence, + FixtureCanonicalInstanceLaunch launch) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java similarity index 57% rename from services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java rename to services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java index 53852edc3e..edd3a7fc27 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java @@ -2,10 +2,15 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.v1.ArtifactState; import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; @@ -13,8 +18,9 @@ import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import tools.jackson.databind.ObjectMapper; -/** Test-only builder that obtains the run-owned carrier through the closed receipt parser. */ +/** Controlled test-only owner inputs parsed into the verified run-owned fixture carrier. */ public final class RunOwnedInitialAdmissionLaunchEvidenceTestFixture { private static final String RUN_ID = "fixture-evidence-test"; private static final String PROJECT_NAME = "firemud-smoke-fixture-evidence-test"; @@ -22,9 +28,20 @@ public final class RunOwnedInitialAdmissionLaunchEvidenceTestFixture { private static final String WORLD_LEAF_SHA = "c".repeat(64); private static final String CA_SHA = "b".repeat(64); private static final String CANONICAL_VERSION_ID = "10000000-0000-4000-8000-000000000011"; + private static final String CLAIM_DIGEST = "d".repeat(64); + private static final String OPERATION_ID = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, RUN_ID, PROJECT_NAME, LEAF_SHA, CA_SHA) + .toString(); + private static final ObjectMapper JSON = new ObjectMapper(); private RunOwnedInitialAdmissionLaunchEvidenceTestFixture() {} + /** Derived control-plane operation used by service tests that consume this fixed test fixture. */ + public static String operationId() { + return OPERATION_ID; + } + public static RunOwnedInitialAdmissionLaunchEvidence create( StartSessionRequest request, AuthoredWorldSourceEvidence sourceEvidence) { return create( @@ -53,6 +70,9 @@ public static RunOwnedInitialAdmissionLaunchEvidence create( PublishedReleaseBundle bundle, VersionAssetArtifactState artifactState, VersionStateSnapshot versionState) { + if (!OPERATION_ID.equals(request.controlPlaneRequestId())) { + throw new IllegalArgumentException("Test fixture request must use its derived operation ID"); + } var capability = RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( capabilityJson(request).getBytes(StandardCharsets.UTF_8), RUN_ID, PROJECT_NAME, pins()); @@ -144,22 +164,34 @@ private static VersionStateSnapshot defaultVersionState(long tenantId) { } private static String capabilityJson(StartSessionRequest request) { - return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"}%n\ - """ - .formatted( - RunOwnedInitialAdmissionFixtureCapability.CAPABILITY_SCHEMA, - RUN_ID, - PROJECT_NAME, - request.controlPlaneRequestId(), - request.tenantId(), - request.gameTemplateId(), - request.ownerAccountId(), - LEAF_SHA, - RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - CA_SHA, - RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, - WORLD_LEAF_SHA); + return json(wireCapability(request)); + } + + private static RunOwnedInitialAdmissionFixtureWireCodec.Capability wireCapability( + StartSessionRequest request) { + return new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + request.controlPlaneRequestId(), + request.tenantId(), + request.gameTemplateId(), + request.ownerAccountId(), + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_SLUG, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_DISPLAY_NAME, + RunOwnedInitialAdmissionFixtureWireCodec.REALM_SLUG, + RunOwnedInitialAdmissionFixtureWireCodec.REALM_DISPLAY_NAME, + true, + true, + false, + RunOwnedInitialAdmissionFixtureWireCodec.STATE_SCOPE, + RunOwnedInitialAdmissionFixtureWireCodec.CHARACTER_CREATION_POLICY, + LEAF_SHA, + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + CA_SHA, + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, + WORLD_LEAF_SHA, + CLAIM_DIGEST); } private static String sourceReceiptJson( @@ -168,39 +200,96 @@ private static String sourceReceiptJson( PublishedReleaseBundle bundle, VersionAssetArtifactState artifactState, VersionStateSnapshot versionState) { - return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":%d,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}}%n\ - """ - .formatted( - RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, - RUN_ID, - PROJECT_NAME, - request.controlPlaneRequestId(), - RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, - RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - LEAF_SHA, - CA_SHA, - RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, - WORLD_LEAF_SHA, - source.schemaVersion(), + var capability = wireCapability(request); + FreshTenantCreationEvidence creation = creationEvidence(source); + LaunchDescriptor descriptor = launchDescriptor(request, source, bundle, versionState); + var launchReadEvidence = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + request.gameTemplateId(), + bundle, + artifactState, + versionState, + descriptor); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launchReadEvidence); + UUID operationId = UUID.fromString(capability.operationId()); + var policySeal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + operationId, + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + operationId, policyRequestDigest)); + + Map launchReadJson = new LinkedHashMap<>(); + launchReadJson.put("schema", launchReadEvidence.schema()); + launchReadJson.put("gameTemplateId", launchReadEvidence.gameTemplateId()); + launchReadJson.put( + "publishedReleaseBundleBase64", + encode(launchReadEvidence.publishedReleaseBundle().toByteArray())); + launchReadJson.put( + "versionAssetArtifactStateBase64", + encode(launchReadEvidence.versionAssetArtifactState().toByteArray())); + launchReadJson.put( + "versionStateBase64", encode(launchReadEvidence.versionState().toByteArray())); + launchReadJson.put( + "launchDescriptorBase64", encode(launchReadEvidence.launchDescriptor().toByteArray())); + + Map receipt = new LinkedHashMap<>(); + receipt.put("schema", RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA); + receipt.put("runId", capability.runId()); + receipt.put("composeProjectName", capability.composeProjectName()); + receipt.put("fixtureOperationId", capability.operationId()); + receipt.put( + "ownerService", RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE); + receipt.put("gameSessionUriSan", capability.gameSessionUriSan()); + receipt.put("gameSessionLeafSha256", capability.gameSessionLeafSha256()); + receipt.put("caCertificateSha256", capability.caCertificateSha256()); + receipt.put("worldManagementUriSan", capability.worldManagementUriSan()); + receipt.put("worldManagementLeafSha256", capability.worldManagementLeafSha256()); + receipt.put("sourceEvidence", source); + receipt.put("launchReadEvidence", launchReadJson); + receipt.put("creationEvidence", creation); + receipt.put("fixturePolicySeal", policySeal); + return json(receipt); + } + + private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID creationRequestId = UUID.fromString("945cc1d0-1e69-4532-b1c3-7dcde16c9256"); + UUID creationOperationId = UUID.fromString("e05352ce-7f61-4436-ac61-508edfe45e8a"); + String requestDigest = + GameTenantCreationDigest.requestDigest( source.targetNamespace(), - source.registrationRequestId(), - source.operationId(), - source.requestDigest(), - source.canonicalTenantId(), - source.tenantSlug(), - source.worldSlug(), + creationRequestId, + source.sourceGameTenantKey(), source.worldDisplayName(), + null); + return new FreshTenantCreationEvidence( + 1, + source.targetNamespace(), + creationRequestId, + creationOperationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + creationRequestId, + creationOperationId, + requestDigest, + source.canonicalTenantId(), source.sourceGameRowId(), source.sourceGameTenantKey(), - source.provenanceKind(), - source.evidenceDigest(), - RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, - request.gameTemplateId(), - encode(bundle.toByteArray()), - encode(artifactState.toByteArray()), - encode(versionState.toByteArray()), - encode(launchDescriptor(request, source, bundle, versionState).toByteArray())); + source.provenanceKind())); + } + + private static String json(Object value) { + return JSON.writeValueAsString(value); } private static LaunchDescriptor launchDescriptor( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java index 981e4f1438..42762880a4 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java @@ -55,8 +55,11 @@ import net.firedevops.firemud.common.security.GrpcClientAuth; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.gamedesign.v1.ArtifactState; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; @@ -99,7 +102,7 @@ class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { private static final String RUN_ID = "world-mtls-fixture-test"; private static final String PROJECT = "firemud-world-mtls-fixture-test"; - private static final String OPERATION_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; + private static final String CLAIM_DIGEST = sha256Hex("controlled-world-mtls-fixture-claim-v1"); private static final String GS_URI = "spiffe://firemud/ns/dev/sa/game-session-service"; private static final String WORLD_URI = "spiffe://firemud/ns/dev/sa/world-management-service"; private static final String GDS_URI = "spiffe://firemud/ns/dev/sa/game-design-service"; @@ -251,7 +254,7 @@ public void activatePreparedWorldInstance( .setTenantId("42") .setGameInstanceId("101") .setGameTemplateId("17") - .setControlPlaneRequestId(OPERATION_ID) + .setControlPlaneRequestId(fixture.operationId()) .setLaunchDescriptorId("launch-descriptor-fixture-11") .setVersionId("11") .setRuntimeFlagsJson("{}") @@ -272,7 +275,7 @@ public void activatePreparedWorldInstance( .setTenantId("42") .setGameInstanceId("101") .setGameTemplateId("17") - .setControlPlaneRequestId(OPERATION_ID) + .setControlPlaneRequestId(fixture.operationId()) .setLaunchDescriptorId("launch-descriptor-fixture-11") .setVersionId("11") .setRuntimeFlagsJson("{}") @@ -325,7 +328,7 @@ public void activatePreparedWorldInstance( .isEqualTo(fixture.descriptorEvidence().request().canonicalTenantId().toString()); assertThat(requestAtOwner.get().getWorldSlug()) .isEqualTo(fixture.descriptorEvidence().worldSlug()); - assertThat(requestAtOwner.get().getControlPlaneRequestId()).isEqualTo(OPERATION_ID); + assertThat(requestAtOwner.get().getControlPlaneRequestId()).isEqualTo(fixture.operationId()); assertThat(requestAtOwner.get().getExpectedRequestDigest()) .isEqualTo(fixture.descriptorEvidence().requestDigest()); assertThat(requestAtOwner.get().getExpectedResultDigest()) @@ -479,7 +482,7 @@ public void activatePreparedWorldInstance( .setTenantId("42") .setGameInstanceId("202") .setGameTemplateId("17") - .setControlPlaneRequestId(OPERATION_ID) + .setControlPlaneRequestId(fixture.operationId()) .setLaunchDescriptorId("launch-descriptor-fixture-11") .setVersionId("11") .setRuntimeFlagsJson("{}") @@ -667,9 +670,9 @@ public void getLaunchDescriptor( .canonicalTenantId() .toString() .equals(request.getCanonicalTenantId()) - || !isExpectedReadRequestId(request.getRequestId()) + || !isExpectedReadRequestId(request.getRequestId(), fixture.operationId()) || !fixture.descriptorEvidence().worldSlug().equals(request.getWorldSlug()) - || !OPERATION_ID.equals(request.getControlPlaneRequestId()) + || !fixture.operationId().equals(request.getControlPlaneRequestId()) || !fixture .descriptorEvidence() .requestDigest() @@ -753,9 +756,9 @@ private ManagedChannel channelWithoutClientIdentity(String host, int port) throw .build(); } - private static boolean isExpectedReadRequestId(String requestId) { + private static boolean isExpectedReadRequestId(String requestId, String operationId) { try { - return !OPERATION_ID.equals(UUID.fromString(requestId).toString()); + return !operationId.equals(UUID.fromString(requestId).toString()); } catch (RuntimeException malformed) { return false; } @@ -877,6 +880,7 @@ public void rollback(TransactionStatus status) {} return commandService; } + /** Controlled closed local evidence; the launch descriptor is checked against the TLS owner. */ private static final class Fixture { private final TestPki pki; private final Path directory; @@ -892,13 +896,22 @@ private static final class Fixture { private final VersionStateSnapshot version; private final LaunchDescriptor launchDescriptor; private final AuthoredWorldLaunchDescriptorEvidence descriptorEvidence; + private final String operationId; private Fixture(Path parent, TestPki pki) throws Exception { this.pki = pki; directory = Files.createDirectories(parent.resolve("world-fixture-" + UUID.randomUUID())); capabilityPath = directory.resolve("capability.json"); receiptPath = directory.resolve("source-receipt.json"); - source = sourceEvidence(); + operationId = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, + RUN_ID, + PROJECT, + fingerprint(pki.gameSessionClient().certificate()), + fingerprint(pki.caCertificateValue())) + .toString(); + source = sourceEvidence(operationId); bundle = publishedBundle(source); artifact = artifactState(); version = versionState(); @@ -907,8 +920,38 @@ private Fixture(Path parent, TestPki pki) throws Exception { source, bundle, version); launchDescriptor = AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); - capabilityJson = capabilityJson(pki); - receiptJson = receiptJson(source, bundle, artifact, version, launchDescriptor, pki); + var capability = capability(pki, operationId); + var creationEvidence = creationEvidence(source); + var launchReadEvidence = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, + bundle, + artifact, + version, + launchDescriptor); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creationEvidence, source, launchReadEvidence); + var policySeal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(operationId), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(operationId), policyRequestDigest)); + capabilityJson = capabilityJson(capability); + receiptJson = + receiptJson( + source, + bundle, + artifact, + version, + launchDescriptor, + creationEvidence, + policySeal, + pki); originalCapabilityJson = capabilityJson; originalReceiptJson = receiptJson; writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); @@ -939,6 +982,10 @@ AuthoredWorldLaunchDescriptorEvidence descriptorEvidence() { return descriptorEvidence; } + String operationId() { + return operationId; + } + void reset() throws IOException { capabilityJson = originalCapabilityJson; receiptJson = originalReceiptJson; @@ -976,8 +1023,8 @@ private static String replaceField(String json, String fieldName, String replace } } - private static AuthoredWorldSourceEvidence sourceEvidence() { - UUID registrationId = UUID.fromString(OPERATION_ID); + private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { + UUID registrationId = UUID.fromString(operationId); UUID tenant = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); String requestDigest = AuthoredWorldSourceDigest.requestDigest( @@ -1063,7 +1110,7 @@ private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( AuthoredWorldSourceEvidence source) { return new AuthoredWorldLaunchDescriptorEvidence.Request( "dev", - OPERATION_ID, + source.registrationRequestId().toString(), source.canonicalTenantId(), source.worldSlug(), source.operationId(), @@ -1098,19 +1145,92 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( null); } - private static String capabilityJson(TestPki pki) throws Exception { + private static RunOwnedInitialAdmissionFixtureWireCodec.Capability capability( + TestPki pki, String operationId) throws Exception { + return new RunOwnedInitialAdmissionFixtureWireCodec.Capability( + RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT, + operationId, + 42L, + 17L, + 9L, + "demo", + "Demo World", + "production", + "Live Realm", + true, + true, + false, + "SHARED", + "ALLOW_NEW", + fingerprint(pki.gameSessionClient().certificate()), + GS_URI, + fingerprint(pki.caCertificateValue()), + WORLD_URI, + fingerprint(pki.worldManagement().certificate()), + CLAIM_DIGEST); + } + + private static String capabilityJson( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { return """ - {"schema":"firemud.run-owned-initial-admission-fixture.v1","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":42,"gameTemplateId":17,"ownerAccountId":9,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s"}\ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"%s","worldDisplayName":"%s","realmSlug":"%s","realmDisplayName":"%s","visible":%s,"publicProductionRealm":%s,"requiresCharacterSelection":%s,"stateScope":"%s","characterCreationPolicy":"%s","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ """ .formatted( - RUN_ID, - PROJECT, - OPERATION_ID, - fingerprint(pki.gameSessionClient().certificate()), - GS_URI, - fingerprint(pki.caCertificateValue()), - WORLD_URI, - fingerprint(pki.worldManagement().certificate())); + capability.schema(), + capability.runId(), + capability.composeProjectName(), + capability.operationId(), + capability.tenantId(), + capability.gameTemplateId(), + capability.ownerAccountId(), + capability.worldSlug(), + capability.worldDisplayName(), + capability.realmSlug(), + capability.realmDisplayName(), + capability.visible(), + capability.publicProductionRealm(), + capability.requiresCharacterSelection(), + capability.stateScope(), + capability.characterCreationPolicy(), + capability.gameSessionLeafSha256(), + capability.gameSessionUriSan(), + capability.caCertificateSha256(), + capability.worldManagementUriSan(), + capability.worldManagementLeafSha256(), + capability.claimDigest()); + } + + private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID requestId = UUID.fromString("21a3b51a-444e-4c08-bbd5-31d40f643ba2"); + UUID operationId = UUID.fromString("3a78e019-c907-49ba-a80a-6d132aeb2135"); + String requestDigest = + GameTenantCreationDigest.requestDigest( + source.targetNamespace(), + requestId, + source.sourceGameTenantKey(), + source.worldDisplayName(), + null); + return new FreshTenantCreationEvidence( + 1, + source.targetNamespace(), + requestId, + operationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + requestId, + operationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); } private static String receiptJson( @@ -1119,15 +1239,17 @@ private static String receiptJson( VersionAssetArtifactState artifact, VersionStateSnapshot version, LaunchDescriptor descriptor, + FreshTenantCreationEvidence creation, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal policySeal, TestPki pki) throws Exception { return """ - {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}}\ + {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}\ """ .formatted( RUN_ID, PROJECT, - OPERATION_ID, + source.registrationRequestId(), GS_URI, fingerprint(pki.gameSessionClient().certificate()), fingerprint(pki.caCertificateValue()), @@ -1147,7 +1269,22 @@ private static String receiptJson( encode(bundle.toByteArray()), encode(artifact.toByteArray()), encode(version.toByteArray()), - encode(descriptor.toByteArray())); + encode(descriptor.toByteArray()), + creation.schemaVersion(), + creation.targetNamespace(), + creation.creationRequestId(), + creation.operationId(), + creation.requestDigest(), + creation.canonicalTenantId(), + creation.sourceGameRowId(), + creation.sourceGameTenantKey(), + creation.provenanceKind(), + creation.evidenceDigest(), + policySeal.schema(), + policySeal.ownerService(), + policySeal.operationId(), + policySeal.requestDigest(), + policySeal.evidenceDigest()); } private static String encode(byte[] bytes) { @@ -1159,6 +1296,16 @@ private static String fingerprint(X509Certificate certificate) throws Exception .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); } + private static String sha256Hex(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is required", exception); + } + } + private static void writeReadonly(Path path, byte[] value) throws IOException { if (Files.exists(path)) { Files.setPosixFilePermissions( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java index 986c04e93c..bbc0dd999e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java @@ -89,6 +89,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + // Controlled evidence inputs keep this proof focused on the real PostgreSQL lifecycle/CAS. @MockitoBean private RunOwnedWorldLaunchEvidenceProvider fixtureProvider; @MockitoBean private RunOwnedWorldLaunchEvidence fixtureEvidence; @MockitoBean private GameDesignClient gameDesignClient; diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java index 54482bc578..05f602cc9d 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java @@ -31,7 +31,11 @@ @ExtendWith(OutputCaptureExtension.class) class RunOwnedWorldLaunchEvidenceProviderTest { - private static final String OPERATION_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; + private static final String CLAIM_DIGEST = "d".repeat(64); + private static final String OPERATION_ID = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "b".repeat(64)) + .toString(); private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; @TempDir Path temporaryDirectory; @@ -292,19 +296,28 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { PublishedReleaseBundle.newBuilder() .setId(77L) .setVersionId(11L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v1") + .setCanonicalTenantId(canonicalTenantId.toString()) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") .setPublishedReleaseBundleRef(RELEASE_REF) .setGenerationConfigRevision("genrev-11") .setManifestHash(manifestHash) .build(); var artifact = VersionAssetArtifactState.newBuilder() + .setTenantId("42") .setVersionId(11L) + .setStateEpoch(2L) + .setExportedVersionNumber(1) .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) .setManifestHash(manifestHash) .build(); var version = VersionStateSnapshot.newBuilder() + .setTenantId("42") .setVersionId(11L) + .setUpdatedAt("2026-10-15T03:00:00") .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) .setVersionStateEpoch(77L) .build(); @@ -330,7 +343,53 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, "b".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64)); + "c".repeat(64), + CLAIM_DIGEST); + UUID creationRequestId = UUID.fromString(OPERATION_ID); + UUID creationOperationId = UUID.fromString("b2af0092-07d6-433b-93ae-21120d88dd51"); + String creationRequestDigest = + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, "42", "Demo World", null); + var creation = + new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( + 1, + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + 29L, + "42", + "NEW_GAME_ROW", + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.evidenceDigest( + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + 29L, + "42", + "NEW_GAME_ROW")); + var launchRead = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, + bundle, + artifact, + version, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toLaunchDescriptorMessage(descriptor)); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launchRead); + var seal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(OPERATION_ID), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(OPERATION_ID), policyRequestDigest)); var receipt = new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, @@ -344,14 +403,9 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, "c".repeat(64), source, - new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( - RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, - 17L, - bundle, - artifact, - version, - net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec - .toLaunchDescriptorMessage(descriptor))); + launchRead, + creation, + seal); return new RunOwnedWorldLaunchEvidence( capability, receipt,