From 1fc27b3dbd0dc3c1fdea1950e5739257b240291b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:17:59 +1300 Subject: [PATCH 01/26] Implement canonical fixture policy and STARTING launch owners --- .../game-design-service/api-contracts.md | 8 +- .../game-session-service/api-contracts.md | 10 +- .../world-management-service/api-contracts.md | 4 +- .../system-architecture-testing.md | 22 +- design/project-management/ai-observations.md | 5 + ...ame-authoring-publishing-and-activation.md | 6 + ...e-session-runtime-and-tick-coordination.md | 12 +- .../world-runtime-and-movement.md | 4 + .../v1/game_session_service.proto | 33 + .../RealmPolicyPublishedEvidence.java | 320 ++++ .../RealmPolicyPublishedEvidenceCodec.java | 334 ++++ ...alGameInstanceLaunchAssociationClient.java | 36 + ...InstanceLaunchAssociationReadEvidence.java | 139 ++ ...nstanceLaunchAssociationReadGrpcCodec.java | 195 ++- ...GrpcServerPeerIdentityCallCredentials.java | 18 +- ...pcServerPeerIdentityClientInterceptor.java | 24 +- ...OwnedInitialAdmissionFixtureWireCodec.java | 286 +++- ...nceLaunchAssociationReadGrpcCodecTest.java | 6 + ...rverPeerIdentityClientInterceptorTest.java | 33 +- ...dInitialAdmissionFixtureWireCodecTest.java | 267 +++- .../data/RunOwnedFixtureLaunchReadback.java | 19 + .../data/RunOwnedFixturePolicyProducer.java | 217 +++ .../gamedesign/data/TestDataSeeder.java | 114 +- .../RealmPolicyPublicationRepository.java | 6 + ...1__run_owned_fixture_policy_owner_seal.sql | 292 ++++ .../data/TestDataSeederIntegrationTest.java | 245 ++- ...icyPublicationPostgresIntegrationTest.java | 106 +- .../gamedesign/data/TestDataSeederTest.java | 69 + .../GameDesignFreshTenantCreationClient.java | 184 +++ ...calInitialAdmissionOwnerConfiguration.java | 21 + ...wnedInitialAdmissionFixtureCapability.java | 20 +- ...nedInitialAdmissionFixtureCoordinator.java | 652 +++----- ...unOwnedInitialAdmissionLaunchEvidence.java | 108 ++ ...nonicalInitialAdmissionIntentSnapshot.java | 4 +- ...meInstanceLaunchAssociationRepository.java | 292 +++- ...nicalInitialAdmissionIntentRepository.java | 61 +- .../CanonicalInitialAdmissionRepository.java | 328 +--- ...sionCanonicalInstanceLaunchRepository.java | 544 +++++++ ...essionCanonicalRealmCatalogRepository.java | 591 ++++++- ...onCanonicalStartingInstanceRepository.java | 94 +- ...ssionFreshTenantAssociationRepository.java | 702 ++++++-- ...tectedGameSessionLoginGrpcInterceptor.java | 1 + .../CanonicalPlayerRouteReadService.java | 5 - ...onicalInitialAdmissionHoldPreparation.java | 72 +- ...abaseCanonicalInitialAdmissionService.java | 72 +- .../service/impl/GameInstanceServiceImpl.java | 721 +-------- .../GameSessionControlPlaneGrpcService.java | 125 ++ .../src/main/resources/application.yml | 1 + ...resh_tenant_complete_creation_evidence.sql | 71 + ...nical_catalog_complete_policy_evidence.sql | 30 + ...anonical_launch_exact_catalog_identity.sql | 68 + ..._initial_admission_terminal_protection.sql | 559 +++++++ ...al_run_owned_fixture_launch_provenance.sql | 140 ++ ...ingInventoryRepositoryIntegrationTest.java | 66 +- ...calGameplayBindingRuntimeTestFixtures.java | 566 ++++--- ...ayDecisionRuntimeFenceIntegrationTest.java | 10 +- ...tentRequestIdMigrationIntegrationTest.java | 209 ++- ...icalHumanPublicationOwnerTestFixtures.java | 1049 ++++++++++++ ...issionIntentRepositoryIntegrationTest.java | 295 ++-- ...ialAdmissionRepositoryIntegrationTest.java | 1406 ++++++++++------- ...RealmCatalogRepositoryIntegrationTest.java | 115 +- ...tingInstanceRepositoryIntegrationTest.java | 201 +-- ...tAssociationRepositoryIntegrationTest.java | 94 +- ...SessionAssociationReadIntegrationTest.java | 157 +- ...unchRepositoryPostgresIntegrationTest.java | 507 ++++++ ...ratorAttemptRepositoryIntegrationTest.java | 547 ++++++- ...eAssociationRepositoryIntegrationTest.java | 17 +- ...unchPreparationServiceIntegrationTest.java | 340 +++- .../CrossServiceAppHarnessTest.java | 3 +- ...InitialAdmissionFixtureCapabilityTest.java | 147 +- ...nitialAdmissionFixtureCoordinatorTest.java | 1330 ++++++---------- ...lInitialAdmissionIntentRepositoryTest.java | 19 +- ...nonicalInitialAdmissionRepositoryTest.java | 102 +- ...nonicalStartingInstanceRepositoryTest.java | 4 +- ...ayRosterOwnerReadInterceptorChainTest.java | 1 + ...signmentOwnerReadInterceptorChainTest.java | 1 + ...alInitialAdmissionHoldPreparationTest.java | 196 +-- ...eCanonicalInitialAdmissionServiceTest.java | 168 +- .../impl/GameInstanceServiceImplTest.java | 518 +----- ...eLaunchAssociationReadGrpcServiceTest.java | 404 +++++ ...ialAdmissionLaunchEvidenceTestFixture.java | 181 ++- .../data/RunOwnedWorldLaunchEvidence.java | 72 +- .../RunOwnedWorldLaunchEvidenceProvider.java | 129 +- .../worldmanagement/data/TestDataSeeder.java | 8 + .../WorldLifecycleCommandServiceImpl.java | 123 +- ...orldLaunchEvidenceMtlsIntegrationTest.java | 1034 +++++------- ...LaunchEvidencePostgresIntegrationTest.java | 309 ++-- ...nOwnedWorldLaunchEvidenceProviderTest.java | 171 +- .../data/TestDataSeederTest.java | 15 + .../WorldLifecycleCommandServiceImplTest.java | 253 +-- 90 files changed, 12972 insertions(+), 6091 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java create mode 100644 services/game-design-service/src/main/resources/db/migration/V1031__run_owned_fixture_policy_owner_seal.sql create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1003__fresh_tenant_complete_creation_evidence.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1004__canonical_catalog_complete_policy_evidence.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1005__canonical_launch_exact_catalog_identity.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1006__canonical_initial_admission_terminal_protection.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V1010__canonical_run_owned_fixture_launch_provenance.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java rename services/game-session-service/src/{test/java/unit => testFixtures/java}/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionLaunchEvidenceTestFixture.java (57%) 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..b6998f71a7 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 bounded run-owned owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. Under the existing default-off fixture configuration, the coordinator prepares the actual canonical Game Session fresh association, catalog and `STARTING` launch, then compares an independent committed owner readback. Game Design source keys and Game Session's allocated private tenant/runtime keys are separate. The earlier numeric fixture allocator is removed. The fixture lifecycle method refuses the unavailable World continuation before owner effects; it returns no active or 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#run-owned-canonical-source-handoff). + +World materialization, activation, holds and the later first-`OPEN` phase remain unavailable in this stage. The coordinator's completed launch-preparation phase is not a completed admission. 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). +The run-owned Compose coordinator currently completes only canonical `STARTING` launch preparation and its independent owner readback under the existing default-off fixture configuration. The later World materialization, activation, initial-bind intent, hold and first-`OPEN` phases remain unavailable. Fixture bootstrap refuses those phases before effects and returns no completed admission. 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 45ab4d5d03..53d203163c 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 bounded canonical fixture launch successor reads the exact authenticated Game Session `STARTING` allocation as source evidence. World fixture bootstrap and prepare/activate refuse before repository effects while source/Version materialization, canonical World association and holds are unavailable. Ordinary demo topology remains under its existing separate configuration. This read neither adopts numeric source keys nor supplies an `ACTIVE` state, first admission bind, Entity placement or operational-region authority. The guarded graph owner's stored and capture states remain unverified; [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records physical proof and remaining phases. + 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). This 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. An unpublished component-owner candidate now includes graph capture and the ordinary schema-3 digest writer; its checkpoint producer and focused proof remain incomplete, as recorded in the tracker. 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). This 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. The published guarded owner stage includes graph capture and the ordinary schema-3 digest writer with bounded local unit/PostgreSQL storage proof; its authenticated complete-checkpoint producer and runtime qualification remain incomplete, as recorded in the tracker. 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. diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index 2c30986069..f6b4bb721b 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. +Current bounded implementation stops after the closed Game Design producer and independently read canonical Game Session `STARTING` allocation. The existing fixture configuration selects those owners without a second launch flag. Authenticated allocation readback is source evidence only; World bootstrap and fixture prepare/activate refuse before effects while materialization and holds are unavailable. 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. -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 trusted data-package coordinator validates this complete fixed capability and receipt before creating the typed fixture carrier. Preflight exact-compares authenticated `ResolveLaunchDescriptor` with the retained projections without invoking the three production release/version/artifact read RPCs. 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#run-owned-canonical-source-handoff) 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 45ff1b14bc..fdfdb3479b 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -270,3 +270,8 @@ Entry format: - Observation: the upload consumed the matrix job's 20-minute budget, cancelling the job and making the required Validation Gate red despite passing source checks. Metadata callbacks used a separate concurrency group and did not cause this cancellation; the slow upload's underlying cause remains unknown. - 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. The database still reported the lease live, 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. 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 4244057987..c387dd9567 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 @@ -8,6 +8,12 @@ This is a non-normative implementation tracker for game authoring, publishing, a 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). + ### 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..2414e2f3a6 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,6 +6,12 @@ This is a non-normative implementation tracker for Game Session runtime and tick ## Current Status +### Canonical fixture launch owner stage + +The successor to the guarded World owner stage prepares the closed Game Design fixture-policy receipt and actual Game Session fresh association, catalog and canonical `STARTING` launch. The scheduler completes only that independently read owner phase. Its authenticated fixed World read echoes the original policy request/seal and owner-allocated private identities; it neither writes an admission pointer nor reports an active World. + +The obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the same existing default-off fixture configuration. World materialization, holds, first `OPEN`, packaged producer-to-consumer execution and all four genuine handoffs remain open. Current-stage formatting, affected whole service checks and physical PostgreSQL proof are pending; earlier full-carrier unit/native results do not qualify these authored postimages. The canonical receipt and phase ordering remain in [Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence). + ### 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. @@ -28,7 +34,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. The fixture coordinator completes only canonical `STARTING` allocation/readback; materialization, activation, holds 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 +67,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/intent and retained pointer/audit components plus typed owner-proof reads are wired locally. The opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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.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 +210,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 run-owned local Compose path prepares an opt-in canonical STARTING allocation with exact replay/readback; its later World and first OPEN phases remain unavailable, 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 b34797bc5c..8cfe26a3cd 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,10 @@ This is a non-normative implementation tracker for world runtime and movement. C ## Current Status +### Canonical fixture launch receiving boundary + +The canonical launch-owner successor adds authenticated fixed Game Session `STARTING` allocation readback. World bootstrap and fixture prepare/activate refuse before owner effects until actual World materialization and holds are composed. That source read grants no World lifecycle, first admission, Entity or operational-region authority. The successor World whole-service check, formatting, static analysis and documentation checks passed on parent `b41a1f8c9853e87592e09f0b4194dca8965b2cc0`. Its 65 freshly executed service integration cases comprise 63 PostgreSQL-backed cases and two controlled mTLS socket tests; 271 unit cases retained their preceding execution attribution. The socket tests qualify authentication and exact echo against controlled remote handlers, while the database cases qualify before-effects refusal and independent passive storage, retained rows and constraints. They do not establish a live remote Game Session producer, complete-commit producer, World activation or packaged runtime. The preceding guarded graph owner's proof retains its own published-source attribution. All four genuine 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. diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 3f4a39b31d..792771a2d4 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; + string 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..469da3a7ce 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,42 @@ 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)); + var result = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse(request, response); + 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..bd897d68ba 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,110 @@ 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("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) || !"SHARED".equals(response.getPlayableStateScope())) { + 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 +138,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 +256,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 +308,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..99101b0a72 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,221 @@ 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()) + || !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 +660,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 +886,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 +902,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/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..f30175fbfd 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( @@ -143,6 +171,135 @@ void rejectsRecursiveUnknownProtoFieldsAndDescriptorProjectionMismatches() { bundle().getVersionId(), bundle().getId(), "different-owner-release-ref"))); } + @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( + validSourceReceiptJson() + .replace(receipt.fixturePolicySeal().evidenceDigest(), "sha256:" + "0".repeat(64))); + assertInvalidReceipt( + 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().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() { return parseCapability(validCapabilityJson()); } @@ -178,7 +335,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 +346,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() { @@ -203,38 +361,83 @@ private static String sourceReceiptJson( 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(), + launchDescriptor()); + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability(), creationEvidence(), sourceEvidence(), 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() { 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..20b0a98459 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 @@ -52,6 +52,10 @@ public class RunOwnedFixtureLaunchReadback { private final VersionAssetArtifactService artifactService; private final LaunchDescriptorService launchDescriptorService; + @org.springframework.beans.factory.annotation.Autowired + private net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = @@ -115,6 +119,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..de329a7415 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java @@ -0,0 +1,217 @@ +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 +final class RunOwnedFixturePolicyProducer { + private static final String SCHEMA = "firemud.run-owned-fixture-policy-seal.v1"; + private static final String OWNER = "game-design-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..c8b36019b6 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 @@ -84,6 +84,13 @@ public class TestDataSeeder implements ApplicationRunner { private final RunOwnedFixtureLaunchReadback launchReadback; private final ObjectMapper objectMapper; + @org.springframework.beans.factory.annotation.Autowired + private net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + creationRepository; + + @org.springframework.beans.factory.annotation.Autowired + private RunOwnedFixturePolicyProducer fixturePolicyProducer; + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") private boolean initialAdmissionFixtureEnabled; @@ -139,6 +146,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 +261,7 @@ public void run(ApplicationArguments args) { } if (initialAdmissionFixtureEnabled) { - registerRunOwnedAuthoredWorldSource(game, template, version); + registerRunOwnedAuthoredWorldSource(game, template, version, verifiedCapability, creation); } } @@ -469,8 +487,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 +524,7 @@ private void registerRunOwnedAuthoredWorldSource( new TransactionSynchronization() { @Override public void afterCommit() { - publishCommittedSourceReceipt(capability, captured); + publishCommittedSourceReceipt(capability, creation, captured); } }); } @@ -557,11 +578,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 +613,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 +668,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 +700,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 +853,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..c0066cc8a3 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,6 +161,24 @@ 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 { @@ -191,7 +215,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 +230,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 +250,89 @@ 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); + 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 +652,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 +685,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()))) @@ -824,14 +955,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 +1011,32 @@ 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(); + 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 +1366,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 = 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..9d39fbb03a 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 @@ -288,6 +288,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)); + ReflectionTestUtils.setField(readback, "creationRepository", 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 = 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..9157338eed --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClient.java @@ -0,0 +1,184 @@ +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.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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; + + 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 void init() throws SSLException, IOException { + initReloadingClient(); + } + + @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) { + return TenantIdentityServiceGrpc.newBlockingStub( + ClientInterceptors.intercept(channel, serverPeerIdentityInterceptor)) + .withCompression("gzip"); + } + + /** + * 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) { + 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 = + stub() + .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) { + if (tlsProperties == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require Game Session workload mTLS"); + } + if (!hasText(tlsProperties.getCertChain()) + || !hasText(tlsProperties.getPrivateKey()) + || !hasText(tlsProperties.getCaCert())) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require Game Session certificate, key, and CA files"); + } + if (tlsProperties.getCertChain().trim().startsWith("classpath:") + || tlsProperties.getPrivateKey().trim().startsWith("classpath:") + || tlsProperties.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Fresh tenant identity reads require file-backed Game Session workload mTLS"); + } + return tlsProperties; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } +} 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..1680bee762 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 @@ -3,6 +3,7 @@ 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; @@ -10,6 +11,7 @@ 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; @@ -43,3 +45,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/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/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java index 2c59a056a7..2387428f7d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -1,48 +1,37 @@ package net.firedevops.firemud.gamesession.data; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; 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.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamesession.client.WorldManagementClient; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; -import net.firedevops.firemud.gamesession.dto.StartSessionRequest; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; -import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; -import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; +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.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -/** Bounded, internal-only bootstrap for an explicitly claimed run-owned Compose fixture. */ +/** + * Bounded, internal-only launch preparation for an explicitly claimed run-owned Compose fixture. + */ @Component public final class RunOwnedInitialAdmissionFixtureCoordinator { private static final Logger logger = LoggerFactory.getLogger(RunOwnedInitialAdmissionFixtureCoordinator.class); private static final int MAX_ATTEMPTS = 12; private static final long RETRY_INTERVAL_MS = 5_000L; - private static final String RUNNING = "RUNNING"; - private static final String DIGEST_DOMAIN = "firemud.run-owned-initial-admission-bind.v1"; private final boolean enabled; private final String capabilityPath; @@ -50,9 +39,9 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { private final String runId; private final String composeProjectName; private final CommonGrpcClientProperties grpcProperties; - private final GameInstanceService gameInstanceService; - private final InitialAdmissionBindOwnerService ownerService; - private final WorldManagementClient worldManagementClient; + private final ObjectProvider configuredLaunchOwners; + private final String workloadNamespace; + private final GameSessionCanonicalInstanceLaunchRepository fixedLaunchOwner; private final AtomicInteger attempts = new AtomicInteger(); private final AtomicBoolean inProgress = new AtomicBoolean(); private final AtomicBoolean finished = new AtomicBoolean(); @@ -61,6 +50,7 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { private final AtomicReference acceptedSourceReceipt = new AtomicReference<>(); + @Autowired public RunOwnedInitialAdmissionFixtureCoordinator( @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, @@ -68,19 +58,60 @@ public RunOwnedInitialAdmissionFixtureCoordinator( @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, CommonGrpcClientProperties grpcProperties, - GameInstanceService gameInstanceService, - InitialAdmissionBindOwnerService ownerService, - WorldManagementClient worldManagementClient) { + ObjectProvider configuredLaunchOwners, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this( + enabled, + capabilityPath, + sourceReceiptPath, + runId, + composeProjectName, + grpcProperties, + configuredLaunchOwners, + workloadNamespace, + null); + } + + RunOwnedInitialAdmissionFixtureCoordinator( + 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 RunOwnedInitialAdmissionFixtureCoordinator( + 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.gameInstanceService = Objects.requireNonNull(gameInstanceService, "gameInstanceService"); - this.ownerService = Objects.requireNonNull(ownerService, "ownerService"); - this.worldManagementClient = - Objects.requireNonNull(worldManagementClient, "worldManagementClient"); + this.configuredLaunchOwners = configuredLaunchOwners; + this.workloadNamespace = workloadNamespace; + this.fixedLaunchOwner = fixedLaunchOwner; } @Scheduled(initialDelay = RETRY_INTERVAL_MS, fixedDelay = RETRY_INTERVAL_MS) @@ -97,50 +128,40 @@ void retryRunOwnedFixtureBootstrap() { try { RunOwnedInitialAdmissionFixtureCapability capability = - RunOwnedInitialAdmissionFixtureCapability.load( - declaredCapabilityPath(), runId, composeProjectName, grpcProperties); - RunOwnedInitialAdmissionFixtureCapability firstCapability = - acceptedCapability.updateAndGet(existing -> existing == null ? capability : existing); - if (!firstCapability.equals(capability)) { - throw unresolved(); - } + acceptCapability( + RunOwnedInitialAdmissionFixtureCapability.load( + declaredCapabilityPath(), runId, composeProjectName, grpcProperties)); RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - declaredSourceReceiptPath(), runId, composeProjectName, capability, grpcProperties); - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt firstSourceReceipt = - acceptedSourceReceipt.updateAndGet( - existing -> existing == null ? sourceReceipt : existing); - if (!firstSourceReceipt.equals(sourceReceipt)) { - throw unresolved(); - } - BootstrapResult result = coordinate(capability, sourceReceipt); - if (result == BootstrapResult.COMMITTED) { - finished.set(true); - logger.info( - "Run-owned initial-admission fixture committed; World hold reconciliation remains" - + " asynchronous."); - } else if (result == BootstrapResult.ABORTED) { - finished.set(true); - logger.warn( - "Run-owned initial-admission fixture has a durable abort; World retains ownership of" - + " hold reconciliation."); - } + acceptSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + declaredSourceReceiptPath(), + runId, + composeProjectName, + capability, + grpcProperties)); + CommittedFixtureLaunchOwnerEvidence result = coordinate(capability, sourceReceipt); + finished.set(true); + logger.info( + "Run-owned fixture launch preparation reached independent Game Session STARTING owner" + + " readback; firstOPEN and World materialization remain unavailable." + + " ownerStatus={}", + result.launch().status()); } catch (RuntimeException exception) { SafeDiagnostic diagnostic = safeDiagnostic(exception); if (attempt >= MAX_ATTEMPTS) { finished.set(true); logger.error( - "Run-owned initial-admission fixture did not reach a verified terminal result after" - + " the bounded retry budget; World hold state remains owner-controlled." - + " exceptionType={} errorCode={} message={}", + "Run-owned fixture launch preparation did not reach independent STARTING owner" + + " readback after the bounded retry budget; firstOPEN and World materialization" + + " remain unavailable. exceptionType={} errorCode={} message={}", diagnostic.exceptionType(), diagnostic.errorCode(), diagnostic.message()); } else { logger.warn( - "Run-owned initial-admission fixture attempt {}/{} remains unresolved; the same" - + " stable operation identity will be retried. exceptionType={} errorCode={}" - + " message={}", + "Run-owned fixture launch preparation attempt {}/{} remains unresolved; the same" + + " fixed operation identity will be retried. firstOPEN and World materialization" + + " remain unavailable. exceptionType={} errorCode={} message={}", attempt, MAX_ATTEMPTS, diagnostic.exceptionType(), @@ -152,88 +173,115 @@ void retryRunOwnedFixtureBootstrap() { } } - BootstrapResult coordinate( + CommittedFixtureLaunchOwnerEvidence coordinate( RunOwnedInitialAdmissionFixtureCapability capability, RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { Objects.requireNonNull(capability, "capability"); requireExactSourceReceipt(capability, sourceReceipt); RunOwnedInitialAdmissionLaunchEvidence launchEvidence = RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt(capability, sourceReceipt); - RunOwnedInitialLaunchResult launch = - gameInstanceService.startRunOwnedInitialLaunch( - new StartSessionRequest( - capability.tenantId(), - capability.gameTemplateId(), - capability.operationId(), - capability.ownerAccountId()), - launchEvidence); - GameInstanceDto target = requireExactRunningTarget(launch, capability); + 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); + } - InitialAdmissionBindCatalogDescriptor descriptor = - new InitialAdmissionBindCatalogDescriptor( - capability.tenantId(), - capability.gameTemplateId(), - capability.worldSlug(), - capability.worldDisplayName(), - capability.realmSlug(), - capability.realmDisplayName(), - capability.requiresCharacterSelection()); - InitialAdmissionBindCatalog catalog = - ownerService.registerPublicSharedFixtureCatalog(descriptor); - requireExactCatalog(catalog, descriptor); + /** Loads only the fixed, independently verified fixture source; it performs no owner writes. */ + public RunOwnedInitialAdmissionLaunchEvidence loadFixedVerifiedEvidence() { + if (!enabled) { + throw unresolved(); + } + RunOwnedInitialAdmissionFixtureCapability capability = + acceptCapability( + RunOwnedInitialAdmissionFixtureCapability.load( + declaredCapabilityPath(), runId, composeProjectName, grpcProperties)); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = + acceptSourceReceipt( + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + declaredSourceReceiptPath(), + runId, + composeProjectName, + capability, + grpcProperties)); + return RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt( + capability, sourceReceipt); + } - long gameInstanceId = target.id(); - long versionId = target.versionId(); - long activeLifecycleEpoch = launch.activeLifecycleEpoch(); - String requestDigest = - requestDigest(capability, catalog, gameInstanceId, versionId, activeLifecycleEpoch); - InitialAdmissionBindRequest request = - new InitialAdmissionBindRequest( - capability.tenantId(), - capability.worldSlug(), - capability.realmSlug(), - capability.operationId(), - requestDigest, - gameInstanceId, - versionId, - activeLifecycleEpoch); - InitialAdmissionBindAttempt attempt = ownerService.beginIntent(request); - requireExactAttempt(attempt, request, catalog, null, null); + /** 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; + } - AcquireInitialAdmissionBindHoldResponse response = - worldManagementClient.acquireInitialAdmissionBindHold( - capability.tenantId(), - gameInstanceId, - versionId, - activeLifecycleEpoch, - capability.operationId(), - requestDigest, - catalog.realmId(), - catalog.playableStateNamespaceId(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - catalog.catalogRevision()); - if (response == null || response.hasError() || !response.hasHold()) { + /** Reads the actual coordinator-owned launch allocation through its canonical owner. */ + public FixtureCanonicalInstanceLaunch readFixedFixtureLaunch( + RunOwnedInitialAdmissionLaunchEvidence evidence) { + Objects.requireNonNull(evidence, "evidence").requireVerifiedFixture(); + if (!Objects.equals(workloadNamespace, evidence.sourceEvidence().targetNamespace())) { throw unresolved(); } - InitialAdmissionBindHold hold = response.getHold(); - InitialAdmissionBindHoldBinding binding = - requireExactHold(hold, request, catalog, gameInstanceId, versionId, activeLifecycleEpoch); + return launchOwner().readVerifiedFixtureLaunch(evidence); + } - if (isTerminalHoldStatus(hold.getStatus())) { - return resultFromProof( - ownerService.read(binding), binding, attempt, request.initialAdmissionRequestId()); + private RunOwnedInitialAdmissionFixtureCapability acceptCapability( + RunOwnedInitialAdmissionFixtureCapability capability) { + RunOwnedInitialAdmissionFixtureCapability first = + acceptedCapability.updateAndGet(existing -> existing == null ? capability : existing); + if (!Objects.equals(first, capability)) { + throw unresolved(); } - if (!isRetryableHoldStatus(hold.getStatus())) { + 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; + } - InitialAdmissionBindAttempt attached = ownerService.attachHold(binding); - requireExactAttempt(attached, request, catalog, binding.holdId(), binding.holdFence()); - InitialAdmissionBindOwnerProof proof = - attached.status() == InitialAdmissionBindAttempt.Status.PENDING - ? ownerService.commit(binding) - : ownerService.read(binding); - return resultFromProof(proof, binding, attached, request.initialAdmissionRequestId()); + 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() { @@ -258,6 +306,45 @@ private Path declaredSourceReceiptPath() { } } + 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) { @@ -273,9 +360,29 @@ static void requireExactSourceReceipt( || !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( @@ -292,273 +399,8 @@ static void requireExactSourceReceipt( } } - private static GameInstanceDto requireExactRunningTarget( - RunOwnedInitialLaunchResult launch, RunOwnedInitialAdmissionFixtureCapability capability) { - if (launch == null || launch.gameInstance() == null || launch.activeLifecycleEpoch() <= 0L) { - throw unresolved(); - } - GameInstanceDto target = launch.gameInstance(); - if (target.id() == null - || target.id() <= 0L - || target.tenantId() == null - || target.tenantId() != capability.tenantId() - || target.gameTemplateId() == null - || target.gameTemplateId() != capability.gameTemplateId() - || target.ownerAccountId() == null - || target.ownerAccountId() != capability.ownerAccountId() - || target.versionId() == null - || target.versionId() <= 0L - || target.launchDescriptorId() == null - || target.launchDescriptorId().isBlank() - || !RUNNING.equals(target.status())) { - throw unresolved(); - } - return target; - } - - private static void requireExactCatalog( - InitialAdmissionBindCatalog catalog, InitialAdmissionBindCatalogDescriptor descriptor) { - if (catalog == null - || catalog.realmId() == null - || catalog.playableStateNamespaceId() == null - || catalog.tenantId() != descriptor.tenantId() - || catalog.gameTemplateId() != descriptor.gameTemplateId() - || !descriptor.worldSlug().equals(catalog.worldSlug()) - || !descriptor.worldDisplayName().equals(catalog.worldDisplayName()) - || !descriptor.realmSlug().equals(catalog.realmSlug()) - || !descriptor.realmDisplayName().equals(catalog.realmDisplayName()) - || catalog.catalogRevision() <= 0L - || !catalog.visible() - || !catalog.publicProductionRealm() - || catalog.requiresCharacterSelection() != descriptor.requiresCharacterSelection() - || !RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE.equals(catalog.stateScope()) - || !RunOwnedInitialAdmissionFixtureCapability.CHARACTER_CREATION_POLICY.equals( - catalog.characterCreationPolicy())) { - throw unresolved(); - } - } - - private static void requireExactAttempt( - InitialAdmissionBindAttempt attempt, - InitialAdmissionBindRequest request, - InitialAdmissionBindCatalog catalog, - String holdId, - String holdFence) { - if (attempt == null - || attempt.attemptId() == null - || attempt.tenantId() != request.tenantId() - || !request.initialAdmissionRequestId().equals(attempt.initialAdmissionRequestId()) - || !request.requestDigest().equals(attempt.requestDigest()) - || !catalog.realmId().equals(attempt.realmId()) - || !catalog.playableStateNamespaceId().equals(attempt.playableStateNamespaceId()) - || !RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE.equals( - attempt.playableStateScope()) - || !attempt.expectedNoPriorPointer() - || attempt.catalogRevision() != catalog.catalogRevision() - || attempt.gameInstanceId() != request.gameInstanceId() - || attempt.versionId() != request.versionId() - || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() - || (holdId != null && !holdId.equals(asCanonicalUuid(attempt.holdId()))) - || (holdFence != null && !holdFence.equals(asCanonicalUuid(attempt.holdFence())))) { - throw unresolved(); - } - } - - private static InitialAdmissionBindHoldBinding requireExactHold( - InitialAdmissionBindHold hold, - InitialAdmissionBindRequest request, - InitialAdmissionBindCatalog catalog, - long gameInstanceId, - long versionId, - long activeLifecycleEpoch) { - if (hold == null - || !isCanonicalUuid(hold.getHoldId()) - || !isCanonicalUuid(hold.getHoldFence()) - || !Long.toString(request.tenantId()).equals(hold.getTenantId()) - || !catalog.realmId().toString().equals(hold.getRealmUuid()) - || !catalog - .playableStateNamespaceId() - .toString() - .equals(hold.getPlayableStateNamespaceUuid()) - || hold.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED - || !Long.toString(gameInstanceId).equals(hold.getGameInstanceId()) - || !Long.toString(versionId).equals(hold.getVersionId()) - || hold.getActiveLifecycleEpoch() != activeLifecycleEpoch - || !request.initialAdmissionRequestId().equals(hold.getInitialAdmissionRequestId()) - || !request.requestDigest().equals(hold.getRequestDigest()) - || !hold.getExpectedNoPriorPointer() - || hold.getExpectedCatalogRevision() != catalog.catalogRevision() - || hold.getStatus() - == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED) { - throw unresolved(); - } - return new InitialAdmissionBindHoldBinding( - hold.getHoldId(), - hold.getHoldFence(), - request.tenantId(), - hold.getRealmUuid(), - hold.getPlayableStateNamespaceUuid(), - RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE, - gameInstanceId, - versionId, - activeLifecycleEpoch, - request.initialAdmissionRequestId(), - request.requestDigest(), - true, - catalog.catalogRevision()); - } - - private static BootstrapResult resultFromProof( - InitialAdmissionBindOwnerProof proof, - InitialAdmissionBindHoldBinding binding, - InitialAdmissionBindAttempt attempt, - String expectedRequestId) { - if (!matchesExactProof(proof, binding, attempt, expectedRequestId)) { - throw unresolved(); - } - if (proof.outcome() == Outcome.COMMITTED) { - return BootstrapResult.COMMITTED; - } - if (proof.outcome() == Outcome.ABORTED && proof.futureCommitPrevented()) { - return BootstrapResult.ABORTED; - } - throw unresolved(); - } - - private static boolean matchesExactProof( - InitialAdmissionBindOwnerProof proof, - InitialAdmissionBindHoldBinding binding, - InitialAdmissionBindAttempt attempt, - String expectedRequestId) { - if (proof == null - || proof.holdId() == null - || !binding.holdId().equals(proof.holdId()) - || !binding.holdFence().equals(proof.holdFence()) - || proof.tenantId() != binding.tenantId() - || !binding.realmUuid().equals(proof.realmUuid()) - || !binding.playableStateNamespaceUuid().equals(proof.playableStateNamespaceUuid()) - || !binding.playableStateScope().equals(proof.playableStateScope()) - || proof.gameInstanceId() != binding.gameInstanceId() - || proof.versionId() != binding.versionId() - || proof.activeLifecycleEpoch() != binding.activeLifecycleEpoch() - || !expectedRequestId.equals(proof.initialAdmissionRequestId()) - || !binding.requestDigest().equals(proof.requestDigest()) - || proof.expectedNoPriorPointer() != binding.expectedNoPriorPointer() - || proof.expectedCatalogRevision() != binding.expectedCatalogRevision() - || attempt == null - || !attempt.attemptId().toString().equals(proof.ownerProofId())) { - return false; - } - - if (proof.outcome() == Outcome.COMMITTED) { - return proof.pointerAuditId() != null - && isCanonicalPositiveLong(proof.pointerAuditId()) - && proof.pointerVersion() == 1L - && binding.requestDigest().equals(proof.pointerAuditRequestDigest()) - && !proof.futureCommitPrevented(); - } - if (proof.outcome() == Outcome.ABORTED) { - return proof.pointerAuditId() == null - && proof.pointerVersion() == 0L - && proof.pointerAuditRequestDigest() == null - && proof.futureCommitPrevented(); - } - return false; - } - - private static boolean isTerminalHoldStatus(InitialAdmissionBindHoldStatus status) { - return status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED - || status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED; - } - - private static boolean isRetryableHoldStatus(InitialAdmissionBindHoldStatus status) { - return status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING - || status - == InitialAdmissionBindHoldStatus - .INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED; - } - - private static String requestDigest( - RunOwnedInitialAdmissionFixtureCapability capability, - InitialAdmissionBindCatalog catalog, - long gameInstanceId, - long versionId, - long activeLifecycleEpoch) { - StringBuilder canonical = new StringBuilder(); - appendDigestField(canonical, "domain", DIGEST_DOMAIN); - appendDigestField(canonical, "operationId", capability.operationId()); - appendDigestField(canonical, "tenantId", Long.toString(capability.tenantId())); - appendDigestField(canonical, "gameTemplateId", Long.toString(capability.gameTemplateId())); - appendDigestField(canonical, "ownerAccountId", Long.toString(capability.ownerAccountId())); - appendDigestField(canonical, "worldSlug", capability.worldSlug()); - appendDigestField(canonical, "worldDisplayName", capability.worldDisplayName()); - appendDigestField(canonical, "realmSlug", capability.realmSlug()); - appendDigestField(canonical, "realmDisplayName", capability.realmDisplayName()); - appendDigestField( - canonical, - "requiresCharacterSelection", - Boolean.toString(capability.requiresCharacterSelection())); - appendDigestField(canonical, "realmId", catalog.realmId().toString()); - appendDigestField( - canonical, "playableStateNamespaceId", catalog.playableStateNamespaceId().toString()); - appendDigestField( - canonical, "playableStateScope", RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE); - appendDigestField(canonical, "expectedNoPriorPointer", "true"); - appendDigestField(canonical, "gameInstanceId", Long.toString(gameInstanceId)); - appendDigestField(canonical, "versionId", Long.toString(versionId)); - appendDigestField(canonical, "activeLifecycleEpoch", Long.toString(activeLifecycleEpoch)); - appendDigestField(canonical, "catalogRevision", Long.toString(catalog.catalogRevision())); - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(canonical.toString().getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } - - private static void appendDigestField(StringBuilder canonical, String name, String value) { - int nameBytes = name.getBytes(StandardCharsets.UTF_8).length; - int valueBytes = value.getBytes(StandardCharsets.UTF_8).length; - canonical - .append(nameBytes) - .append(':') - .append(name) - .append(valueBytes) - .append(':') - .append(value); - } - - private static String asCanonicalUuid(UUID value) { - return value == null ? null : value.toString(); - } - - private static boolean isCanonicalUuid(String value) { - if (value == null) { - return false; - } - try { - return UUID.fromString(value).toString().equals(value); - } catch (IllegalArgumentException exception) { - return false; - } - } - - private static boolean isCanonicalPositiveLong(String value) { - if (value == null) { - return false; - } - try { - long parsed = Long.parseLong(value); - return parsed > 0L && Long.toString(parsed).equals(value); - } catch (NumberFormatException exception) { - return false; - } - } - private static RuntimeException unresolved() { - return new IllegalStateException("Run-owned initial-admission fixture remains unresolved"); + return new IllegalStateException("Run-owned fixture launch preparation remains unresolved"); } private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { @@ -572,7 +414,7 @@ private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { return new SafeDiagnostic( exception.getClass().getSimpleName(), "FIXTURE_STATE_UNRESOLVED", - "Fixture state remains unresolved."); + "Fixture launch state remains unresolved."); } return new SafeDiagnostic( exception.getClass().getSimpleName(), @@ -582,8 +424,12 @@ private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { private record SafeDiagnostic(String exceptionType, String errorCode, String message) {} - enum BootstrapResult { - COMMITTED, - ABORTED + record CommittedFixtureLaunchOwnerEvidence( + RunOwnedInitialAdmissionLaunchEvidence launchEvidence, + FixtureCanonicalInstanceLaunch launch) { + CommittedFixtureLaunchOwnerEvidence { + Objects.requireNonNull(launchEvidence, "launchEvidence"); + Objects.requireNonNull(launch, "launch"); + } } } 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..cb2bf08918 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) { @@ -49,6 +73,7 @@ static RunOwnedInitialAdmissionLaunchEvidence fromVerifiedSourceReceipt( RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence readEvidence = receipt.launchReadEvidence(); return new RunOwnedInitialAdmissionLaunchEvidence( + new VerifiedFixture(capability, receipt), receipt.sourceEvidence(), readEvidence.schema(), readEvidence.gameTemplateId(), @@ -58,6 +83,89 @@ 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"); + } + RunOwnedInitialAdmissionFixtureCoordinator.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 (!"firemud.run-owned-fixture-policy-seal.v1".equals(seal.schema()) + || !"game-design-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..0786f8447e 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 @@ -65,6 +65,18 @@ public CanonicalGameInstanceLaunchAssociation capture( long gameInstanceId, CompleteLaunchBindingEvidence launchBindingEvidence) { requireWritableReadCommittedOwnerTransaction(); + throw new IllegalStateException( + "Original StartSession tuple is required for canonical launch capture"); + } + + /** Captures the exact Human tuple and actual catalog owner identity with the STARTING row. */ + public CanonicalGameInstanceLaunchAssociation capture( + FreshGameSessionTenantAssociation tenantAssociation, + long gameInstanceId, + CompleteLaunchBindingEvidence launchBindingEvidence, + StartSessionPostAuthorizationExecutionTuple originalTuple) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(originalTuple, "originalTuple"); Objects.requireNonNull(tenantAssociation, "tenantAssociation"); requirePositive(gameInstanceId, "gameInstanceId"); ValidatedBinding binding = validateBinding(launchBindingEvidence); @@ -72,6 +84,20 @@ 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"); + } + requireOriginalPinsBeforeStarting(originalTuple, binding.evidence()); RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); requireFreshSourceIdentity(tenantAssociation, source); if (!binding.descriptor().canonicalTenantId().equals(source.canonicalTenantId())) { @@ -82,12 +108,14 @@ public CanonicalGameInstanceLaunchAssociation capture( 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 +136,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 +166,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 +187,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 +221,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 +313,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 +507,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 +786,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 +930,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 +1333,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 +1359,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 +1493,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 +1814,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 +1842,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..a908c77dd6 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,7 +1,6 @@ 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; @@ -29,7 +28,6 @@ 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; @@ -54,7 +52,6 @@ public class CanonicalInitialAdmissionRepository { 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( @@ -87,7 +84,7 @@ public CanonicalInitialAdmissionRepository( this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); this.launchRepository = Objects.requireNonNull(launchRepository, "launchRepository"); - this.eventRepository = Objects.requireNonNull(eventRepository, "eventRepository"); + Objects.requireNonNull(eventRepository, "eventRepository"); } /** Persists the immutable request identity before remote World verification is attempted. */ @@ -189,8 +186,8 @@ public void reserve(CanonicalInitialAdmissionRequest request) { } /** - * 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( @@ -200,80 +197,10 @@ public void commit( 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. - */ + /** Denies Human abort before owner effects while Account terminal protection is unavailable. */ @Transactional(isolation = Isolation.READ_COMMITTED) public void abort( CanonicalInitialAdmissionRequest request, @@ -281,62 +208,7 @@ public void abort( 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. */ @@ -458,152 +330,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) { @@ -893,23 +638,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( @@ -997,16 +725,6 @@ private void lockAllAdmissionRepresentationsForNoPrior() { + "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, @@ -1237,14 +955,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); } 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..627eccc1e0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java @@ -0,0 +1,544 @@ +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.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..2899a59553 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 @@ -1,6 +1,9 @@ package net.firedevops.firemud.gamesession.repository; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; @@ -9,24 +12,38 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.Connection; +import java.util.Arrays; +import java.util.HashSet; import java.util.HexFormat; 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.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 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 +132,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; } /** @@ -127,6 +147,16 @@ public PreparedInitialPublicProduction prepareInitialPublicProduction( CreateCanonicalRealmCatalogRequest request) { Objects.requireNonNull(request, "request"); requireCommittedRead(); + throw new InvalidCatalogEvidenceException( + "Complete immutable published policy evidence is required"); + } + + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialPublicProduction prepareInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); Record binding = dsl.fetchOne( "SELECT * FROM game_session_authored_world_tenant_source_binding " @@ -152,7 +182,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 +202,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 +214,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 +272,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(); @@ -654,6 +713,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 +1199,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) { + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt committedSource, + RealmPolicyPublishedEvidence.PublishedSet publishedSet, + byte[] policyBytes) { + this(request, committedSource, new HumanPolicy(publishedSet), policyBytes); + } + + private PreparedInitialPublicProduction( + 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 +1245,487 @@ 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) { + 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) { + 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 static final ObjectMapper JSON = new ObjectMapper(); + private static final Set CREATION_EVIDENCE_FIELDS = + Set.of( + "schemaVersion", + "targetNamespace", + "creationRequestId", + "operationId", + "requestDigest", + "canonicalTenantId", + "sourceGameRowId", + "sourceGameTenantKey", + "provenanceKind", + "evidenceDigest"); + + private final String workloadNamespace; + private final TransactionTemplate writeTransaction; + private final TransactionTemplate readTransaction; + + @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.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) { + Record row = + dsl.fetchOne( + "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" + + " WHERE fresh.target_namespace = ? AND fresh.canonical_tenant_id = ?", + source.targetNamespace(), + canonicalTenantId); + if (row == null) { + throw new InvalidCanonicalRealmCatalogException( + "Fresh canonical realm requires an existing complete Game Session tenant association"); + } + try { + String requestIdText = required(row, "association_request_id", UUID.class).toString(); + UUID associationOperationId = required(row, "association_operation_id", UUID.class); + UUID tenantId = required(row, "canonical_tenant_id", UUID.class); + long numericTenantId = required(row, "legacy_game_session_tenant_id", Long.class); + FreshTenantCreationEvidence creation = + parseCreationEvidence(required(row, "complete_source_evidence", String.class)); + if (!source.targetNamespace().equals(required(row, "target_namespace", String.class)) + || !source + .targetNamespace() + .equals(required(row, "source_target_namespace", String.class)) + || !requestIdText.equals(required(row, "source_request_id", UUID.class).toString()) + || !tenantId.equals(required(row, "source_canonical_tenant_id", UUID.class)) + || required(row, "source_schema_version", Integer.class) != creation.schemaVersion() + || required(row, "source_game_row_id", Long.class) != creation.sourceGameRowId() + || !required(row, "source_game_tenant_key", String.class) + .equals(creation.sourceGameTenantKey()) + || !required(row, "provenance_kind", String.class).equals(creation.provenanceKind()) + || !"FRESH_SOURCE_BOUND".equals(required(row, "association_kind", String.class)) + || !creation.targetNamespace().equals(source.targetNamespace()) + || !creation + .creationRequestId() + .equals(required(row, "association_request_id", UUID.class)) + || !creation.canonicalTenantId().equals(tenantId) + || !creation.targetNamespace().equals(source.targetNamespace()) + || !creation.canonicalTenantId().equals(source.canonicalTenantId()) + || creation.sourceGameRowId() != source.sourceGameRowId() + || !creation.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !creation.provenanceKind().equals(source.provenanceKind()) + || !"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)) + || !source.targetNamespace().equals(required(row, "claim_namespace", String.class)) + || !tenantId.equals(required(row, "claim_canonical_tenant_id", UUID.class)) + || numericTenantId != required(row, "claim_tenant_id", Long.class) + || !associationOperationId.equals(required(row, "claim_operation_id", UUID.class)) + || !required(row, "association_request_id", UUID.class) + .equals(required(row, "claim_request_id", UUID.class)) + || associationOperationId.equals(creation.operationId())) { + throw new InvalidCanonicalRealmCatalogException( + "Stored fresh tenant association differs from complete source receipt or canonical claim"); + } + return new FreshTenantAssociation( + source.targetNamespace(), tenantId, numericTenantId, associationOperationId, creation); + } catch (IllegalArgumentException invalid) { + throw new InvalidCanonicalRealmCatalogException( + "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 InvalidCanonicalRealmCatalogException( + "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 InvalidCanonicalRealmCatalogException( + "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 InvalidCanonicalRealmCatalogException( + "Public-production policy must exactly match the authored world"); + } + return new SelectedPolicy(selected.policyId(), selected.policyDigest(), policy); + } + + /** ADR0047 UTF-8 byte-length framing; every input segment has an unambiguous byte boundary. */ + private static FreshTenantCreationEvidence parseCreationEvidence(String serializedEvidence) { + try { + JsonNode json = JSON.readTree(serializedEvidence); + if (json == null || !json.isObject() || json.size() != CREATION_EVIDENCE_FIELDS.size()) { + throw new IllegalArgumentException( + "Complete creation evidence must be one closed JSON object"); + } + HashSet fields = new HashSet<>(); + json.fieldNames().forEachRemaining(fields::add); + if (!fields.equals(CREATION_EVIDENCE_FIELDS)) { + throw new IllegalArgumentException( + "Complete creation evidence has unknown or missing fields"); + } + 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 invalid) { + throw new InvalidCanonicalRealmCatalogException( + "Stored complete Game Design creation evidence is invalid", invalid); + } + } + + private static String requiredText(JsonNode json, String field) { + JsonNode value = json.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Complete creation 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 creation 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 creation 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) || NIL_UUID.equals(parsed)) { + throw new IllegalArgumentException( + "Complete creation evidence UUID must be canonical and nonnil"); + } + return parsed; + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new InvalidCanonicalRealmCatalogException( + "Stored canonical realm catalog is missing required evidence: " + field); + } + return value; + } + + private static void sourceRequireNonNil(UUID id, String label) { + if (id == null || NIL_UUID.equals(id)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + } + + 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) {} + + public static final class InvalidCanonicalRealmCatalogException extends IllegalStateException { + public InvalidCanonicalRealmCatalogException(String message) { + super(message); + } + + public InvalidCanonicalRealmCatalogException(String message, Throwable cause) { + super(message, cause); + } + } } 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..2c0461fb58 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,35 @@ 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.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. @@ -35,6 +50,10 @@ 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; } /** @@ -48,63 +67,48 @@ public GameSessionFreshTenantAssociationRepository(DSLContext dsl) { public FreshGameSessionTenantAssociation associateFresh( UUID associationOperationId, String targetNamespace, IntakeReceipt expectedSourceReceipt) { requireWritableReadCommittedOwnerTransaction(); + throw new InvalidFreshTenantSourceException( + "Complete immutable Game Design fresh-creation evidence is required before association"); + } + + /** 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, + 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"); + "Complete creation and authored-source receipts differ"); } - 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"); - } - 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) { @@ -278,75 +282,6 @@ private Record findClaimByAssociationRequest(String namespace, UUID associationR 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, @@ -434,4 +369,531 @@ 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; + + @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.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(); + 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(); + 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); + 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(); + 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) { + 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() { + Record reservation = + dsl.fetchOne( + "INSERT INTO game_session_tenant_scope_reservation (reservation_kind)" + + " VALUES ('FRESH_SOURCE_BOUND') RETURNING game_session_tenant_id, reservation_kind"); + if (reservation == null + || !"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; + } + + 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..d9a2d29dd6 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,6 +15,7 @@ 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", 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/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index 62844772ac..de1d767ee0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -2,13 +2,8 @@ import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.HashSet; -import java.util.HexFormat; import java.util.Objects; -import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; @@ -59,8 +54,6 @@ public class GameInstanceServiceImpl implements GameInstanceService { private static final String STATUS_RUNNING = "RUNNING"; private static final String STATUS_STOPPING = "STOPPING"; private static final String STATUS_STOPPED = "STOPPED"; - private static final String RUN_OWNED_LAUNCH_DIGEST_SCHEMA = - "firemud.run-owned-initial-launch/v2"; private static final String SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION = "v1"; private static final String WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE = "world activation authority unavailable"; @@ -250,115 +243,12 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { validateRunOwnedLaunchRequest(request); + Objects.requireNonNull(launchEvidence, "launchEvidence").requireVerifiedFixture(); requireRunOwnedSourceMatchesRequest(request, launchEvidence); - ResolvedLaunchDescriptor resolvedLaunchDescriptor = - preflightRunOwnedLaunch(request, launchEvidence); - requireDescriptorMatchesRequest(request, resolvedLaunchDescriptor); - String requestDigest = runOwnedLaunchRequestDigest(request, launchEvidence); - GameInstance reserved = - inTransaction( - () -> reserveRunOwnedInitialLaunch(request, resolvedLaunchDescriptor, requestDigest), - "reserve run-owned initial launch"); - long gameInstanceId = reserved.getId(); - requireRunOwnedTargetCanResume(reserved); - - if (STATUS_RUNNING.equals(reserved.getStatus())) { - long activeEpoch = requireRunOwnedRecordedActiveEpoch(reserved); - WorldInstanceLifecycleSnapshot current = - readRunOwnedWorldLifecycle(reserved, request, resolvedLaunchDescriptor); - if (current.getStatus() - == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World"); - } - if (current.getStatus() - != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { - throw runOwnedWorldStatusFailure(current.getStatus()); - } - requireRunOwnedActiveEpoch(current, activeEpoch); - sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_RUNNING)); - GameInstance completed = - inTransaction( - () -> - completeRunOwnedInitialLaunch( - request, - requestDigest, - resolvedLaunchDescriptor, - gameInstanceId, - activeEpoch), - "complete run-owned initial launch retry"); - return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); - } - - validateStartDependencies(); - - WorldInstanceLifecycleSnapshot prepared = - prepareRunOwnedWorldInstance(reserved, resolvedLaunchDescriptor, request); - if (prepared.getStatus() - == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { - reserved = - inTransaction( - () -> - recordRunOwnedPreparingEpoch( - request, - requestDigest, - resolvedLaunchDescriptor, - gameInstanceId, - prepared.getLifecycleEpoch()), - "record run-owned preparing epoch"); - } else { - reserved = - reloadRunOwnedInitialLaunch( - request, requestDigest, resolvedLaunchDescriptor, gameInstanceId); - } - - WorldInstanceLifecycleSnapshot current = - readRunOwnedWorldLifecycle(reserved, request, resolvedLaunchDescriptor); - long activeEpoch; - if (current.getStatus() - == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { - if (STATUS_RUNNING.equals(reserved.getStatus())) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World"); - } - if (reserved.getRunOwnedStartActiveEpoch() != null) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: starting owner row already has an active epoch"); - } - long preparingEpoch = requireRunOwnedPreparingEpoch(reserved); - activeEpoch = Math.addExact(preparingEpoch, 1L); - if (current.getLifecycleEpoch() != preparingEpoch) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch differs from the durable launch fence"); - } - if (STATUS_STARTING.equals(reserved.getStatus())) { - sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_STARTING)); - } - activateAndReadBackRunOwnedWorld( - reserved, request, resolvedLaunchDescriptor, preparingEpoch, activeEpoch); - } else if (current.getStatus() - == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { - long preparingEpoch = requireRunOwnedPreparingEpoch(reserved); - activeEpoch = Math.addExact(preparingEpoch, 1L); - if (reserved.getRunOwnedStartActiveEpoch() != null - && reserved.getRunOwnedStartActiveEpoch() != activeEpoch) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation result"); - } - requireRunOwnedActiveEpoch(current, activeEpoch); - } else { - throw runOwnedWorldStatusFailure(current.getStatus()); - } - - GameInstanceDto runningState = withStatus(snapshot(reserved), STATUS_RUNNING); - sessionStateService.saveState(runningState); - GameInstance completed = - inTransaction( - () -> - completeRunOwnedInitialLaunch( - request, requestDigest, resolvedLaunchDescriptor, gameInstanceId, activeEpoch), - "complete run-owned initial launch"); - return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); + throw new IllegalStateException( + "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: canonical STARTING launch preparation" + + " is owned by the fixture coordinator; World materialization and first OPEN" + + " admission remain unavailable"); } @Override @@ -738,508 +628,6 @@ private void validateRunOwnedLaunchRequest(StartSessionRequest request) { } } - private static String runOwnedLaunchRequestDigest( - StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { - AuthoredWorldSourceEvidence sourceEvidence = launchEvidence.sourceEvidence(); - StringBuilder preimage = new StringBuilder(); - appendDigestField(preimage, "schema", RUN_OWNED_LAUNCH_DIGEST_SCHEMA); - appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); - appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); - appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); - appendDigestField(preimage, "ownerAccountId", Long.toString(request.ownerAccountId())); - appendDigestField(preimage, "replaceExistingFirst", "false"); - appendDigestField( - preimage, "sourceSchemaVersion", Integer.toString(sourceEvidence.schemaVersion())); - appendDigestField(preimage, "sourceTargetNamespace", sourceEvidence.targetNamespace()); - appendDigestField( - preimage, "sourceRegistrationRequestId", sourceEvidence.registrationRequestId().toString()); - appendDigestField(preimage, "sourceOperationId", sourceEvidence.operationId().toString()); - appendDigestField(preimage, "sourceRequestDigest", sourceEvidence.requestDigest()); - appendDigestField( - preimage, "sourceCanonicalTenantId", sourceEvidence.canonicalTenantId().toString()); - appendDigestField(preimage, "sourceTenantSlug", sourceEvidence.tenantSlug()); - appendDigestField(preimage, "sourceWorldSlug", sourceEvidence.worldSlug()); - appendDigestField(preimage, "sourceWorldDisplayName", sourceEvidence.worldDisplayName()); - appendDigestField(preimage, "sourceGameRowId", Long.toString(sourceEvidence.sourceGameRowId())); - appendDigestField(preimage, "sourceGameTenantKey", sourceEvidence.sourceGameTenantKey()); - appendDigestField(preimage, "sourceProvenanceKind", sourceEvidence.provenanceKind()); - appendDigestField(preimage, "sourceEvidenceDigest", sourceEvidence.evidenceDigest()); - appendDigestField(preimage, "launchReadEvidenceSchema", launchEvidence.schema()); - appendDigestField( - preimage, - "launchReadEvidenceGameTemplateId", - Long.toString(launchEvidence.gameTemplateId())); - appendDigestField( - preimage, - "publishedReleaseBundleSnapshotSha256", - sha256Hex(launchEvidence.publishedReleaseBundle().toByteArray())); - appendDigestField( - preimage, - "versionAssetArtifactStateSnapshotSha256", - sha256Hex(launchEvidence.versionAssetArtifactState().toByteArray())); - appendDigestField( - preimage, - "versionStateSnapshotSha256", - sha256Hex(launchEvidence.versionState().toByteArray())); - return sha256Hex(preimage.toString().getBytes(StandardCharsets.UTF_8)); - } - - private static String sha256Hex(byte[] bytes) { - try { - return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 unavailable", exception); - } - } - - private static void appendDigestField(StringBuilder preimage, String name, String value) { - int nameByteLength = name.getBytes(StandardCharsets.UTF_8).length; - int valueByteLength = value.getBytes(StandardCharsets.UTF_8).length; - preimage - .append(nameByteLength) - .append(':') - .append(name) - .append(valueByteLength) - .append(':') - .append(value); - } - - private void requireDescriptorMatchesRequest( - StartSessionRequest request, ResolvedLaunchDescriptor descriptor) { - if (descriptor.tenantId() != request.tenantId() - || descriptor.gameTemplateId() != request.gameTemplateId() - || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_REQUEST_MISMATCH: resolved descriptor is not bound to this request"); - } - if (descriptor.launchDescriptorId() == null - || descriptor.launchDescriptorId().isBlank() - || descriptor.versionId() <= 0L - || descriptor.releaseBundleId() <= 0L - || descriptor.versionStateEpoch() <= 0L - || descriptor.generationConfigRevision() == null - || descriptor.generationConfigRevision().isBlank() - || descriptor.publishedReleaseBundleRef() == null - || descriptor.publishedReleaseBundleRef().isBlank()) { - throw new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_INCOMPLETE: resolved descriptor is missing exact published inputs"); - } - } - - private GameInstance reserveRunOwnedInitialLaunch( - StartSessionRequest request, ResolvedLaunchDescriptor descriptor, String requestDigest) { - repository.lockRunOwnedStartIdentity(request.tenantId(), request.controlPlaneRequestId()); - Optional existing = - repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( - request.tenantId(), request.controlPlaneRequestId()); - if (existing.isPresent()) { - requireSameRunOwnedInitialLaunch(existing.get(), request, descriptor, requestDigest); - return existing.get(); - } - - GameInstance instance = new GameInstance(); - instance.setTenantId(request.tenantId()); - instance.setRuntimeVersion(Long.toString(descriptor.versionId())); - instance.setGameTemplateId(request.gameTemplateId()); - instance.setLaunchDescriptorId(descriptor.launchDescriptorId()); - instance.setVersionId(descriptor.versionId()); - instance.setReleaseBundleId(descriptor.releaseBundleId()); - instance.setVersionStateEpoch(descriptor.versionStateEpoch()); - instance.setGenerationConfigRevision(descriptor.generationConfigRevision()); - instance.setRemapSetId(descriptor.remapSetId()); - instance.setOwnerAccountId(request.ownerAccountId()); - instance.setStatus(STATUS_STARTING); - instance.setRunOwnedStartRequestId(request.controlPlaneRequestId()); - instance.setRunOwnedStartRequestDigest(requestDigest); - instance.setRunOwnedStartPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()); - return repository.save(instance); - } - - private void requireSameRunOwnedInitialLaunch( - GameInstance instance, - StartSessionRequest request, - ResolvedLaunchDescriptor descriptor, - String requestDigest) { - if (!request.controlPlaneRequestId().equals(instance.getRunOwnedStartRequestId()) - || !requestDigest.equals(instance.getRunOwnedStartRequestDigest()) - || !Objects.equals(instance.getTenantId(), request.tenantId()) - || !Objects.equals(instance.getOwnerAccountId(), request.ownerAccountId()) - || !Objects.equals(instance.getGameTemplateId(), request.gameTemplateId()) - || !Objects.equals(instance.getRuntimeVersion(), Long.toString(descriptor.versionId())) - || !Objects.equals(instance.getLaunchDescriptorId(), descriptor.launchDescriptorId()) - || !Objects.equals(instance.getVersionId(), descriptor.versionId()) - || !Objects.equals(instance.getReleaseBundleId(), descriptor.releaseBundleId()) - || !Objects.equals(instance.getVersionStateEpoch(), descriptor.versionStateEpoch()) - || !Objects.equals( - instance.getGenerationConfigRevision(), descriptor.generationConfigRevision()) - || !Objects.equals(instance.getRemapSetId(), descriptor.remapSetId()) - || !Objects.equals( - instance.getRunOwnedStartPublishedReleaseBundleRef(), - descriptor.publishedReleaseBundleRef())) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_CONFLICT: request or resolved descriptor changed"); - } - } - - private void requireRunOwnedTargetCanResume(GameInstance instance) { - if (instance.getId() == null - || instance.getRunOwnedStartRequestId() == null - || instance.getRunOwnedStartRequestDigest() == null) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: durable request identity is incomplete"); - } - if (!STATUS_STARTING.equals(instance.getStatus()) - && !STATUS_RUNNING.equals(instance.getStatus())) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_TARGET_NOT_RESUMABLE: existing instance is not starting or running"); - } - if (STATUS_RUNNING.equals(instance.getStatus())) { - requireRunOwnedRecordedActiveEpoch(instance); - } - } - - private long requireRunOwnedRecordedActiveEpoch(GameInstance instance) { - long preparingEpoch = requireRunOwnedPreparingEpoch(instance); - Long activeEpoch = instance.getRunOwnedStartActiveEpoch(); - if (activeEpoch == null || activeEpoch <= 0L) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_EPOCH_UNAVAILABLE: running instance has no active epoch proof"); - } - if (activeEpoch != Math.addExact(preparingEpoch, 1L)) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: durable ACTIVE epoch differs from the prepare fence"); - } - return activeEpoch; - } - - private GameInstance recordRunOwnedPreparingEpoch( - StartSessionRequest request, - String requestDigest, - ResolvedLaunchDescriptor descriptor, - long gameInstanceId, - long preparingEpoch) { - if (preparingEpoch <= 0L) { - throw new IllegalStateException( - "WORLD_AUTHORITY_MALFORMED: lifecycle epoch must be positive"); - } - GameInstance instance = - repository - .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) - .orElseThrow( - () -> - new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); - requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); - Long recordedEpoch = instance.getRunOwnedStartPreparingEpoch(); - if (recordedEpoch != null) { - if (recordedEpoch != preparingEpoch) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch changed across retries"); - } - return instance; - } - if (instance.getRunOwnedStartActiveEpoch() != null) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_EPOCH_MISMATCH: active epoch exists without its prepare fence"); - } - instance.setRunOwnedStartPreparingEpoch(preparingEpoch); - return repository.save(instance); - } - - private GameInstance reloadRunOwnedInitialLaunch( - StartSessionRequest request, - String requestDigest, - ResolvedLaunchDescriptor descriptor, - long gameInstanceId) { - return inTransaction( - () -> { - GameInstance instance = - repository - .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) - .orElseThrow( - () -> - new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); - requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); - return instance; - }, - "reload run-owned initial launch"); - } - - private GameInstance completeRunOwnedInitialLaunch( - StartSessionRequest request, - String requestDigest, - ResolvedLaunchDescriptor descriptor, - long gameInstanceId, - long activeEpoch) { - GameInstance instance = - repository - .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) - .orElseThrow( - () -> - new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); - requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); - long expectedActiveEpoch = Math.addExact(requireRunOwnedPreparingEpoch(instance), 1L); - if (activeEpoch != expectedActiveEpoch) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation fence"); - } - if (instance.getRunOwnedStartActiveEpoch() != null - && instance.getRunOwnedStartActiveEpoch() != activeEpoch) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch changed across retries"); - } - if (!STATUS_STARTING.equals(instance.getStatus()) - && !STATUS_RUNNING.equals(instance.getStatus())) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_TARGET_NOT_RESUMABLE: existing instance is not starting or running"); - } - instance.setRunOwnedStartActiveEpoch(activeEpoch); - instance.setStatus(STATUS_RUNNING); - return repository.save(instance); - } - - private long requireRunOwnedPreparingEpoch(GameInstance instance) { - Long epoch = instance.getRunOwnedStartPreparingEpoch(); - if (epoch == null || epoch <= 0L) { - throw new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_EPOCH_UNAVAILABLE: exact PREPARING epoch is not durable"); - } - return epoch; - } - - private WorldInstanceLifecycleSnapshot prepareRunOwnedWorldInstance( - GameInstance instance, ResolvedLaunchDescriptor descriptor, StartSessionRequest request) { - if (worldManagementClient == null) { - throw new IllegalStateException(WORLD_PREPARATION_AUTHORITY_UNAVAILABLE); - } - final PrepareWorldInstanceResponse response; - try { - response = - worldManagementClient.prepareWorldInstance( - request.tenantId(), - instance.getId(), - request.gameTemplateId(), - request.controlPlaneRequestId(), - descriptor.launchDescriptorId(), - descriptor.versionId(), - instance.getScriptPatchVersion(), - descriptor.runtimeFlagsJson(), - descriptor.generationConfigRevision(), - descriptor.releaseBundleId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - descriptor.remapSetId()); - } catch (RuntimeException exception) { - throw new IllegalStateException(WORLD_PREPARATION_AUTHORITY_UNAVAILABLE, exception); - } - if (response == null) { - throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); - } - if (response.hasError()) { - throw new IllegalStateException( - response.getError().getCode() + ": " + response.getError().getMessage()); - } - WorldInstanceLifecycleSnapshot snapshot = - requireWorldSnapshot( - response.hasWorldInstance(), - response.getWorldInstance(), - request.tenantId(), - instance.getId(), - null); - requireRunOwnedWorldDescriptor(snapshot, request, descriptor, instance.getId()); - requireKnownRunOwnedWorldStatus(snapshot.getStatus()); - return snapshot; - } - - private WorldInstanceLifecycleSnapshot readRunOwnedWorldLifecycle( - GameInstance instance, StartSessionRequest request, ResolvedLaunchDescriptor descriptor) { - if (worldManagementClient == null) { - throw new IllegalStateException(WORLD_LIFECYCLE_AUTHORITY_UNAVAILABLE); - } - final GetWorldInstanceLifecycleResponse response; - try { - response = - worldManagementClient.getWorldInstanceLifecycle(request.tenantId(), instance.getId()); - } catch (RuntimeException exception) { - throw new IllegalStateException(WORLD_LIFECYCLE_AUTHORITY_UNAVAILABLE, exception); - } - if (response == null) { - throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); - } - if (response.hasError()) { - throw new IllegalStateException( - response.getError().getCode() + ": " + response.getError().getMessage()); - } - WorldInstanceLifecycleSnapshot snapshot = - requireWorldSnapshot( - response.hasWorldInstance(), - response.getWorldInstance(), - request.tenantId(), - instance.getId(), - null); - requireRunOwnedWorldDescriptor(snapshot, request, descriptor, instance.getId()); - requireKnownRunOwnedWorldStatus(snapshot.getStatus()); - return snapshot; - } - - private WorldInstanceLifecycleSnapshot activateAndReadBackRunOwnedWorld( - GameInstance instance, - StartSessionRequest request, - ResolvedLaunchDescriptor descriptor, - long preparingEpoch, - long activeEpoch) { - if (worldManagementClient == null) { - throw new IllegalStateException(WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE); - } - final ActivatePreparedWorldInstanceResponse response; - try { - response = - worldManagementClient.activatePreparedWorldInstance( - request.tenantId(), instance.getId(), preparingEpoch); - } catch (RuntimeException activationFailure) { - return reconcileRunOwnedActivationFailure( - instance, request, descriptor, preparingEpoch, activeEpoch, activationFailure); - } - if (response == null) { - throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); - } - if (response.hasError()) { - return reconcileRunOwnedActivationFailure( - instance, - request, - descriptor, - preparingEpoch, - activeEpoch, - new IllegalStateException( - response.getError().getCode() + ": " + response.getError().getMessage())); - } - WorldInstanceLifecycleSnapshot activated = - requireWorldSnapshot( - response.hasWorldInstance(), - response.getWorldInstance(), - request.tenantId(), - instance.getId(), - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); - requireRunOwnedWorldDescriptor(activated, request, descriptor, instance.getId()); - requireRunOwnedActiveEpoch(activated, activeEpoch); - - WorldInstanceLifecycleSnapshot readback = - readRunOwnedWorldLifecycle(instance, request, descriptor); - if (readback.getStatus() - != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { - throw runOwnedWorldStatusFailure(readback.getStatus()); - } - requireRunOwnedActiveEpoch(readback, activeEpoch); - return readback; - } - - private WorldInstanceLifecycleSnapshot reconcileRunOwnedActivationFailure( - GameInstance instance, - StartSessionRequest request, - ResolvedLaunchDescriptor descriptor, - long preparingEpoch, - long activeEpoch, - RuntimeException activationFailure) { - WorldInstanceLifecycleSnapshot current = - readRunOwnedWorldLifecycle(instance, request, descriptor); - if (current.getStatus() - == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { - requireRunOwnedActiveEpoch(current, activeEpoch); - return current; - } - if (current.getStatus() - == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { - if (current.getLifecycleEpoch() != preparingEpoch) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch differs from the durable launch fence", - activationFailure); - } - throw new IllegalStateException(WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE, activationFailure); - } - throw runOwnedWorldStatusFailure(current.getStatus()); - } - - private void requireRunOwnedWorldDescriptor( - WorldInstanceLifecycleSnapshot snapshot, - StartSessionRequest request, - ResolvedLaunchDescriptor descriptor, - long gameInstanceId) { - final long tenantId; - final long instanceId; - final long templateId; - final long versionId; - final long releaseBundleId; - try { - tenantId = RequestIdValidation.requirePositiveLong(snapshot.getTenantId(), "tenantId"); - instanceId = - RequestIdValidation.requirePositiveLong(snapshot.getGameInstanceId(), "gameInstanceId"); - templateId = - RequestIdValidation.requirePositiveLong(snapshot.getGameTemplateId(), "gameTemplateId"); - versionId = RequestIdValidation.requirePositiveLong(snapshot.getVersionId(), "versionId"); - releaseBundleId = - RequestIdValidation.requirePositiveLong(snapshot.getReleaseBundleId(), "releaseBundleId"); - } catch (IllegalArgumentException exception) { - throw new IllegalStateException( - "WORLD_AUTHORITY_MALFORMED: " + exception.getMessage(), exception); - } - if (tenantId != request.tenantId() - || instanceId != gameInstanceId - || templateId != request.gameTemplateId() - || !request.controlPlaneRequestId().equals(snapshot.getControlPlaneRequestId()) - || !descriptor.launchDescriptorId().equals(snapshot.getLaunchDescriptorId()) - || versionId != descriptor.versionId() - || releaseBundleId != descriptor.releaseBundleId() - || !descriptor.generationConfigRevision().equals(snapshot.getGenerationConfigRevision()) - || !descriptor.publishedReleaseBundleRef().equals(snapshot.getPublishedReleaseBundleRef()) - || snapshot.getVersionStateEpoch() != descriptor.versionStateEpoch() - || !Objects.equals( - normalizeBlank(descriptor.remapSetId()), normalizeBlank(snapshot.getRemapSetId()))) { - throw new IllegalStateException( - "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor"); - } - } - - private void requireKnownRunOwnedWorldStatus(WorldInstanceLifecycleStatus status) { - if (status == null - || status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED - || status == WorldInstanceLifecycleStatus.UNRECOGNIZED) { - throw new IllegalStateException("WORLD_AUTHORITY_MALFORMED: lifecycle status is unavailable"); - } - } - - private void requireRunOwnedActiveEpoch( - WorldInstanceLifecycleSnapshot snapshot, long expectedActiveEpoch) { - if (snapshot.getLifecycleEpoch() != expectedActiveEpoch) { - throw new IllegalStateException( - "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation result"); - } - } - - private RuntimeException runOwnedWorldStatusFailure(WorldInstanceLifecycleStatus status) { - if (status - == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) { - return new LifecycleOutcomeException( - "WORLD_INSTANCE_LIFECYCLE_FAILED_PRE_ACTIVATION", - "run-owned instance failed before activation and remains terminal for this request"); - } - if (status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATING) { - return new LifecycleOutcomeException( - "WORLD_TERMINATION_IN_PROGRESS", "run-owned instance termination is in progress"); - } - if (status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) { - return new LifecycleOutcomeException( - "WORLD_INSTANCE_TERMINATED", "run-owned instance is already terminated"); - } - return new IllegalStateException( - "WORLD_AUTHORITY_MALFORMED: lifecycle status cannot resume initial launch"); - } - - private String normalizeBlank(String value) { - return value == null || value.isBlank() ? null : value; - } - private GameInstanceDto withStatus(GameInstanceDto snapshot, String status) { return new GameInstanceDto( snapshot.id(), @@ -1286,83 +674,6 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { return preflightLaunchResponse(request, descriptorResponse, descriptorTenantId); } - private ResolvedLaunchDescriptor preflightRunOwnedLaunch( - StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { - if (gameDesignClient == null) { - throw new IllegalStateException("launch descriptor authority unavailable"); - } - AuthoredWorldSourceEvidence sourceEvidence = launchEvidence.sourceEvidence(); - ResolveLaunchDescriptorResponse descriptorResponse = - gameDesignClient.resolveLaunchDescriptor( - request.tenantId(), - request.gameTemplateId(), - request.controlPlaneRequestId(), - sourceEvidence); - AuthoredWorldLaunchDescriptorEvidence actualDescriptorEvidence = - requireExactAuthoredWorldDescriptorRequest(request, sourceEvidence, descriptorResponse); - if (descriptorResponse.hasError()) { - throw new IllegalArgumentException( - descriptorResponse.getError().getCode() - + ": " - + descriptorResponse.getError().getMessage()); - } - requireRunOwnedLaunchDescriptorMatchesReceipt( - actualDescriptorEvidence, launchEvidence.launchDescriptor()); - if (!descriptorResponse.hasLaunchDescriptor()) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); - } - var descriptor = descriptorResponse.getLaunchDescriptor(); - var bundle = launchEvidence.publishedReleaseBundle(); - var artifactState = launchEvidence.versionAssetArtifactState(); - var versionState = launchEvidence.versionState(); - String tenantId = Long.toString(request.tenantId()); - if (!RunOwnedInitialAdmissionLaunchEvidence.SCHEMA.equals(launchEvidence.schema()) - || launchEvidence.gameTemplateId() != request.gameTemplateId() - || descriptor.getGameTemplateId() != request.gameTemplateId() - || descriptor.getVersionId() != bundle.getVersionId() - || descriptor.getReleaseBundleId() != bundle.getId() - || descriptor.getVersionStateEpoch() != versionState.getVersionStateEpoch() - || !descriptor.getPublishedReleaseBundleRef().equals(bundle.getPublishedReleaseBundleRef()) - || !descriptor.getGenerationConfigRevision().equals(bundle.getGenerationConfigRevision()) - || !sourceEvidence.canonicalTenantId().toString().equals(bundle.getCanonicalTenantId()) - || !tenantId.equals(artifactState.getTenantId()) - || artifactState.getVersionId() != descriptor.getVersionId() - || artifactState.getStateEpoch() <= 0L - || artifactState.getArtifactState() - != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED - || !artifactState.getManifestHash().equals(bundle.getManifestHash()) - || artifactState.getExportedVersionNumber() != bundle.getVersionNumber() - || !artifactState - .getExportedManifestAssetKeysList() - .containsAll(bundle.getRequiredManifestAssetKeysList()) - || !tenantId.equals(versionState.getTenantId()) - || versionState.getVersionId() != descriptor.getVersionId() - || versionState.getVersionStateEpoch() != descriptor.getVersionStateEpoch() - || (versionState.getVersionState() - != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED - && versionState.getVersionState() - != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE)) { - throw new IllegalArgumentException( - "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch" - + " descriptor"); - } - requireSupportedReleaseAttestationSchema(bundle.getAttestationSchemaVersion()); - return new ResolvedLaunchDescriptor( - descriptor.getLaunchDescriptorId(), - request.tenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion().isBlank() ? null : descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); - } - private ResolvedLaunchDescriptor preflightLaunchResponse( StartSessionRequest request, ResolveLaunchDescriptorResponse descriptorResponse, @@ -1497,28 +808,6 @@ private AuthoredWorldLaunchDescriptorEvidence requireExactAuthoredWorldDescripto } } - private void requireRunOwnedLaunchDescriptorMatchesReceipt( - AuthoredWorldLaunchDescriptorEvidence actualDescriptorEvidence, - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor receiptDescriptor) { - AuthoredWorldLaunchDescriptorEvidence receiptDescriptorEvidence; - try { - receiptDescriptorEvidence = - AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( - actualDescriptorEvidence.request(), receiptDescriptor); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException( - "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: owner receipt descriptor is invalid", exception); - } - if (!AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(actualDescriptorEvidence) - .equals( - AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( - receiptDescriptorEvidence))) { - throw new IllegalArgumentException( - "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" - + " owner receipt descriptor"); - } - } - private void validatePublishedAssetProof( long tenantId, long versionId, 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..0e59e58c80 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.RunOwnedInitialAdmissionFixtureCoordinator; +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 RunOwnedInitialAdmissionFixtureCoordinator runOwnedFixtureCoordinator; + 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( + RunOwnedInitialAdmissionFixtureCoordinator fixtureCoordinator, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean fixtureEnabled, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.runOwnedFixtureCoordinator = fixtureCoordinator; + this.fixtureLaunchReadEnabled = fixtureEnabled; + this.fixtureReadWorkloadNamespace = workloadNamespace; + } + private long parseTenantId(String tenantId) { return ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_id"); } @@ -285,6 +307,109 @@ 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 || runOwnedFixtureCoordinator == 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) { + throw new IllegalArgumentException("Fixture launch owner request is required"); + } + + // Authentication and the fixed default-off boundary precede strict wire decoding. + RunOwnedInitialAdmissionLaunchEvidence evidence = + runOwnedFixtureCoordinator.loadFixedVerifiedEvidenceForWorldPeer(); + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest selector = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request); + if (!fixtureReadWorkloadNamespace.equals(selector.targetNamespace()) + || !evidence.sourceEvidence().targetNamespace().equals(selector.targetNamespace()) + || !evidence + .fixtureCapability() + .operationId() + .equals(selector.fixtureOperationId().toString()) + || !evidence + .fixturePolicySeal() + .evidenceDigest() + .equals(selector.expectedFixturePolicyEvidenceDigest())) { + throw new IllegalArgumentException( + "Fixture launch owner selector differs from the fixed verified source"); + } + + var launch = runOwnedFixtureCoordinator.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 malformed) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture launch owner selector is invalid") + .asRuntimeException()); + } catch (IllegalStateException unavailable) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact fixed fixture launch owner read is unavailable") + .asRuntimeException()); + } catch (RuntimeException failure) { + logger.error("GetRunOwnedFixtureLaunchAssociation failed"); + 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/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..91d483fa71 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java @@ -0,0 +1,1049 @@ +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() {} + + 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..1976055064 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,28 @@ 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.time.Instant; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +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 +41,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,8 +50,8 @@ 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.impl.DSL; import org.junit.jupiter.api.Test; @@ -58,10 +67,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 +82,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,7 +93,7 @@ class CanonicalInitialAdmissionRepositoryIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { + void reservesExactHumanIntentButDeniesCommitAndAbortBeforePointerOrAuditEffects() { Fixture fixture = fixture(); IntakeReceipt source = fixture.registerSource(); CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); @@ -106,7 +115,15 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { FreshGameSessionTenantAssociation tenantAssociation = fixture.createTestOnlyFreshMappingAndRunningLaunch(source, completeBinding); - CanonicalInitialAdmissionRequest request = initialAdmissionRequest(catalog, completeBinding); + CanonicalInitialAdmissionRequest request = + initialAdmissionRequest( + catalog, + completeBinding, + fixture + .launchRepository + .read(CONTROL_PLANE_REQUEST_ID) + .orElseThrow() + .gameInstanceUuid()); assertThat(tenantAssociation.legacyGameSessionTenantId()) .isNotEqualTo(source.source().sourceGameRowId()); assertThat(request.playableStateNamespaceId()).isEqualTo(catalog.playableStateNamespaceId()); @@ -235,218 +252,33 @@ 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 = + CanonicalInitialAdmissionOwnerProof pending = 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(); + String before = attemptProjection(fixture, request); + for (int retry = 0; retry < 2; retry++) { + assertHumanProtectionUnavailable( + () -> + fixture.transactions.executeWithoutResult( + status -> fixture.initialAdmissionRepository.commit(request, worldProof, null))); + assertHumanProtectionUnavailable( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture.initialAdmissionRepository.abort( + request, null, "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 @@ -458,6 +290,7 @@ void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { initialAdmissionRequest( prepared.catalog(), prepared.binding(), + prepared.gameInstanceUuid(), requestId, CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, null, @@ -479,52 +312,49 @@ void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { } @Test - void newNoPriorPointerReservationRejectsAnAlreadyOpenRealmWithoutLeavingPendingAttempt() { + void competingNoPriorPointerReservationCannotReplacePendingUnprotectedHumanIntent() { 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()); + fixture.transactions.executeWithoutResult( + status -> fixture.initialAdmissionRepository.reserve(first)); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.commit(first, testWorldProof(first), null)); + 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; - })) + fixture.transactions.executeWithoutResult( + status -> fixture.initialAdmissionRepository.reserve(competing))) .isInstanceOf( - GameSessionCanonicalAdmissionPointerRepository.CanonicalClosedPointerConflictException - .class) - .hasMessageContaining("already names this target"); - - assertNoAttemptAndNoPending(fixture, staleRequest); + CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException.class) + .hasMessageContaining("pending realm attempt"); + assertThat( + fixture.initialAdmissionRepository.read( + NAMESPACE, competing.initialAdmissionRequestId())) + .isEmpty(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt")), + DSL.field(DSL.name("status"), String.class).eq("PENDING"))) + .isEqualTo(1); + assertThat( + fixture.initialAdmissionRepository.read(NAMESPACE, first.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.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 @@ -554,6 +384,7 @@ void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { initialAdmissionRequest( catalog, binding, + preparedAdmission.gameInstanceUuid(), "canonical-expected-closed-v129-" + catalog.realmId(), CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, 129L, @@ -576,6 +407,7 @@ void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { initialAdmissionRequest( catalog, binding, + preparedAdmission.gameInstanceUuid(), "canonical-expected-closed-v1-" + catalog.realmId(), CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED, 1L, @@ -594,190 +426,723 @@ void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { 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); + String closedBefore = pointerAndAuditProjection(fixture); + String pendingBefore = attemptProjection(fixture, firstOpenRequest); + assertHumanProtectionUnavailable( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture.initialAdmissionRepository.commit( + firstOpenRequest, + testWorldProof(firstOpenRequest), + preparedExpectedClosed))); + assertHumanProtectionUnavailable( + () -> + fixture.transactions.executeWithoutResult( + status -> + fixture.initialAdmissionRepository.abort( + firstOpenRequest, preparedExpectedClosed, "Missing protection"))); + assertThat(pointerAndAuditProjection(fixture)).isEqualTo(closedBefore); + assertThat(attemptProjection(fixture, firstOpenRequest)).isEqualTo(pendingBefore); + assertThat( + fixture.initialAdmissionRepository.read( + NAMESPACE, firstOpenRequest.initialAdmissionRequestId())) + .map(CanonicalInitialAdmissionOwnerProof::outcome) + .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); } @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); - - CanonicalInitialAdmissionOwnerProof committed = service.bind(request); - - assertThat(committed.outcome()) - .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); - assertThat(committed.committedPointerVersion()).isEqualTo(1L); - assertThat(committed.auditEventId()).isPositive(); + 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(); - 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_event")), - DSL.field(DSL.name("initial_admission_request_id"), String.class) - .eq(request.initialAdmissionRequestId()))) - .isEqualTo(1); } @Test - void exactDefinitivelyAbortedAttemptCannotBeReopenedByRetry() { + void unprotectedHumanAbortAndCommitRetryLeaveTheExactPendingOwnerUnchanged() { 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); - - 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(); - - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.abort(request, null, "World hold expired"); - return null; - }); - - CanonicalInitialAdmissionOwnerProof aborted = + PreparedAdmission prepared = prepareAdmission(fixture); + var request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + fixture.transactions.executeWithoutResult( + status -> fixture.initialAdmissionRepository.reserve(request)); + var pending = 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); + String before = attemptProjection(fixture, request); + for (int retry = 0; retry < 2; retry++) { + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.abort(request, null, "World hold expired")); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.commit(request, testWorldProof(request), null)); + fixture.transactions.executeWithoutResult( + status -> fixture.initialAdmissionRepository.reserve(request)); + 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")))) - .isEqualTo(auditRowsBeforeAbort); + .isZero(); + } - fixture.transactions.execute( + @Test + void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Exception { + 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 schema = predecessor.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + var migration = + Flyway.configure() + .dataSource(Objects.requireNonNull(predecessor.transactionManager.getDataSource())) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load(); + migration.migrate(); + 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(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), null)); + assertHumanProtectionUnavailable( + () -> + predecessor.initialAdmissionRepository.abort( + request, null, "Current Human retry remains unprotected")); + assertThat(predecessorAttemptProjection(predecessor, request)).isEqualTo(originalAttempt); + assertThat(pointerAndAuditProjection(predecessor)).isEqualTo(originalPointerAndAudit); + assertThat(predecessorSourceProjection(predecessor)).isEqualTo(originalSources); + } + } + + /** 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); - 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); + /** 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 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 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 +1150,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); @@ -882,8 +1250,8 @@ private static CreateCanonicalLaunchPreparationRequest preparationRequest( null, false, null, - false, - null); + true, + "{}"); } private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient( @@ -905,7 +1273,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 +1283,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 +1314,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( private static CanonicalInitialAdmissionRequest initialAdmissionRequest( CanonicalRealmCatalogSnapshot catalog, CompleteLaunchBindingEvidence binding, + UUID gameInstanceUuid, String requestId, CanonicalInitialAdmissionRequest.OriginKind origin, Long expectedPriorPointerVersion, @@ -986,7 +1330,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( catalog.realmId(), catalog.playableStateNamespaceId(), "SHARED", - GAME_INSTANCE_UUID, + gameInstanceUuid, canonicalVersionId, activeEpoch, catalog.catalogRevision(), @@ -1000,7 +1344,7 @@ private static CanonicalInitialAdmissionRequest initialAdmissionRequest( catalog.realmId(), catalog.playableStateNamespaceId(), "SHARED", - GAME_INSTANCE_UUID, + gameInstanceUuid, canonicalVersionId, activeEpoch, catalog.catalogRevision(), @@ -1046,7 +1390,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 +1429,7 @@ private static CreateCanonicalRealmCatalogRequest catalogRequest(IntakeReceipt s true, true, "SHARED", - "explicit-policy-v1", + "PRESEEDED_ONLY", null, null); } @@ -1097,7 +1443,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 +1463,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 +1482,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); - 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); + 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 = ?", - 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..33b3615bca 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"); @@ -259,10 +260,9 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan 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 +284,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 +308,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 +330,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 +358,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 +584,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 +627,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 +671,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 +695,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 +870,8 @@ private Fixture fixture(boolean seedRetainedNumericRows, MigrationVersion target transactionManager, transactions, dataSource, - schema); + schema, + new java.util.concurrent.ConcurrentHashMap<>()); } private static UUID tenant(int value) { @@ -891,7 +894,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 +922,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..6b89f1f367 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,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; -import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -13,17 +12,16 @@ 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.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 +59,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 +82,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 +92,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 +136,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 +169,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 +200,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 +249,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 +264,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( @@ -274,14 +296,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 +318,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() { @@ -407,7 +396,9 @@ private record Fixture( GameSessionCanonicalRealmCatalogRepository catalogRepository, GameSessionCanonicalStartingInstanceRepository startingRepository, IntakeReceipt source, - FreshGameSessionTenantAssociation tenantAssociation) { + FreshGameSessionTenantAssociation tenantAssociation, + StartSessionPostAuthorizationExecutionTuple originalTuple, + RealmPolicyPublishedEvidence.PublishedSet publishedSet) { StartingInstance start( UUID ownerAccountUuid, String controlPlaneRequestId, @@ -421,7 +412,8 @@ StartingInstance start( binding, ownerAccountUuid, controlPlaneRequestId, - requestDigest)), + requestDigest, + originalTuple)), "canonical STARTING owner result"); } } @@ -461,31 +453,48 @@ 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, transactions, @@ -494,6 +503,8 @@ private static Fixture fixture(boolean createRealm) { 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..d044ab765e 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 @@ -13,11 +13,13 @@ import java.util.concurrent.TimeUnit; 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.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.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; @@ -64,10 +66,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); @@ -97,10 +102,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 +127,10 @@ void rejectsSameOperationWithDifferentSourceOrNamespaceAsAnIdempotencyConflict() FreshGameSessionTenantAssociation committed = fixture.associate(associationOperationId, NAMESPACE, firstSource); assertThatThrownBy(() -> fixture.associate(associationOperationId, NAMESPACE, secondSource)) - .isInstanceOf(FreshTenantAssociationConflictException.class) - .hasMessageContaining("different source or namespace"); + .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThatThrownBy( () -> fixture.associate(associationOperationId, NAMESPACE + "-other", firstSource)) - .isInstanceOf(FreshTenantAssociationConflictException.class); + .isInstanceOf(InvalidFreshTenantSourceException.class); assertThat( Objects.requireNonNull( @@ -200,7 +204,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 +258,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 +276,49 @@ 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)); + 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 +516,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"); } } 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..7e0a6d6d31 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java @@ -0,0 +1,507 @@ +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.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); + } + + 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); + } + + 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() { + String schema = "gs_run_owned_launch_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + 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); + 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); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionFreshTenantAssociationRepository tenantAssociationRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalInstanceLaunchRepository launchRepository) {} + + 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..b592839853 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 @@ -4,10 +4,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; @@ -28,7 +32,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 +79,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 +105,63 @@ 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. + var catalogEvidenceBefore = + 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()); + var launchEvidenceBefore = + 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()); + assertThat(launchEvidenceBefore).isNotNull(); + String originalLaunchColumnsBefore = + launchEvidenceBefore.get("original_columns", String.class); + String launchXminBefore = launchEvidenceBefore.get("xmin", String.class); + assertThat(catalogEvidenceBefore).isNotNull(); + String originalCatalogColumnsBefore = + catalogEvidenceBefore.get("original_columns", String.class); + String catalogXminBefore = catalogEvidenceBefore.get("xmin", String.class); + 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 +187,56 @@ 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); + var catalogEvidenceAfter = + 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()); + assertThat(catalogEvidenceAfter).isNotNull(); + assertThat(catalogEvidenceAfter.get("original_columns", String.class)) + .isEqualTo(originalCatalogColumnsBefore); + assertThat(catalogEvidenceAfter.get("xmin", String.class)).isEqualTo(catalogXminBefore); + var launchEvidenceAfter = + 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()); + assertThat(launchEvidenceAfter).isNotNull(); + assertThat(launchEvidenceAfter.get("original_columns", String.class)) + .isEqualTo(originalLaunchColumnsBefore); + assertThat(launchEvidenceAfter.get("xmin", String.class)).isEqualTo(launchXminBefore); assertConstraintsReady( dsl, @@ -168,7 +247,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 +294,395 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr } } + 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 v34_3Digest( + "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 v34_3Digest( + "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 String v34_3Digest(String... values) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + 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:" + HexFormat.of().formatHex(hash.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + 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 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..a52551f44c 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,206 @@ 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 = + 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 = + 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 String historicalDigest(String... fields) { + try { + var 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 unavailable) { + throw new IllegalStateException(unavailable); + } + } + 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 +964,54 @@ private record Fixture( DataSourceTransactionManager transactionManager, TransactionTemplate transactions, IntakeReceipt preV24Source, - CanonicalRealmCatalogSnapshot preV24Catalog) { + CanonicalRealmCatalogSnapshot preV24Catalog, + String historicalCatalogBefore, + String historicalSourceBefore, + String historicalNamespaceBefore, + String historicalBindingBefore) { + void requireHistoricalRowsRetained() { + 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); + } + IntakeReceipt registerFreshSource() { IntakeReceipt receipt = transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); @@ -761,10 +1030,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/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index b830e55c74..1771c71fd9 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 @@ -23,6 +23,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.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapability.CertificatePins; import org.junit.jupiter.api.Test; @@ -34,7 +36,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 +58,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 +143,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); @@ -526,6 +545,8 @@ private static String validSourceReceiptJson( net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState artifactState, net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, LaunchDescriptor descriptor) { + FreshTenantCreationEvidence creation = creationEvidence(source); + var seal = fixturePolicySeal(source, bundle, artifactState, versionState, descriptor, creation); String sourceJson = """ {%n\ @@ -558,6 +579,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 +617,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 +634,92 @@ 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; + try { + requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launchReadEvidence); + } catch (IllegalArgumentException invalidNegativeTestEvidence) { + AuthoredWorldSourceEvidence validSource = sourceEvidence(); + var validBundle = launchBundle(); + var validArtifactState = launchArtifactState(); + var validVersionState = launchVersionState(); + var validCreation = creationEvidence(validSource); + var validLaunchReadEvidence = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + capability.gameTemplateId(), + validBundle, + validArtifactState, + validVersionState, + launchDescriptor(validSource, validBundle, validVersionState)); + requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, validCreation, validSource, validLaunchReadEvidence); + } + 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() { @@ -759,7 +892,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 +905,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) 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..f1fca96135 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 @@ -3,871 +3,513 @@ 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.anyLong; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; 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.same; 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.time.Instant; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; 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.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamesession.client.WorldManagementClient; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; -import net.firedevops.firemud.gamesession.dto.StartSessionRequest; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; -import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; -import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; +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.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.MockedStatic; -import org.springframework.boot.test.system.CapturedOutput; -import org.springframework.boot.test.system.OutputCaptureExtension; -@ExtendWith(OutputCaptureExtension.class) class RunOwnedInitialAdmissionFixtureCoordinatorTest { - private static final String RUN_ID = "compose-smoke-2939"; - private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; + 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 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 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 HOLD_ID = UUID.fromString("5fdd38a3-09e3-46bb-b11a-e2ff2a096211"); - private static final UUID HOLD_FENCE = UUID.fromString("e385de73-4324-44a8-a815-d0c806b9a0f7"); - private static final UUID ATTEMPT_ID = UUID.fromString("6f39929c-44ee-45c7-9e96-8c6548b84e65"); + private static final UUID GAME_INSTANCE_UUID = + UUID.fromString("7556e829-d531-4c61-b8d4-350c8514c4f1"); @Test - void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsync() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + void commitsExactStartingOwnerAllocationThenPerformsSeparateIndependentReadback() { + Fixture fixture = fixture(true); - RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult result = - fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); + var result = fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); - assertThat(fixture.sourceReceipt.sourceEvidence().registrationRequestId()) - .isEqualTo(UUID.fromString(OPERATION_ID)); - assertThat(fixture.sourceReceipt.sourceEvidence().operationId()) - .isNotEqualTo(fixture.sourceReceipt.sourceEvidence().registrationRequestId()); - assertThat(result) - .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.COMMITTED); - InOrder order = inOrder(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); - ArgumentCaptor launchEvidence = - ArgumentCaptor.forClass(RunOwnedInitialAdmissionLaunchEvidence.class); - order - .verify(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any(), launchEvidence.capture()); - assertThat(launchEvidence.getValue().sourceEvidence()) + assertThat(result.launchEvidence().sourceEvidence()) .isEqualTo(fixture.sourceReceipt.sourceEvidence()); - assertThat(launchEvidence.getValue().publishedReleaseBundle()) - .isEqualTo(fixture.sourceReceipt.launchReadEvidence().publishedReleaseBundle()); - assertThat(launchEvidence.getValue().launchDescriptor()) - .isEqualTo(fixture.sourceReceipt.launchReadEvidence().launchDescriptor()); - order.verify(fixture.ownerService).registerPublicSharedFixtureCatalog(any()); - order.verify(fixture.ownerService).beginIntent(any()); - order - .verify(fixture.worldClient) - .acquireInitialAdmissionBindHold( - eq(7L), - eq(42L), - eq(11L), - eq(4L), - eq(OPERATION_ID), - anyString(), - eq(REALM_ID), - eq(NAMESPACE_ID), - eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), - eq(3L)); - order.verify(fixture.ownerService).attachHold(any()); - order.verify(fixture.ownerService).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - verify(fixture.ownerService, never()).read(any()); + 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 unresolvedOwnerProofDoesNotReleaseHoldOrCompensate() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof(binding, Outcome.PENDING, ATTEMPT_ID, null, 0L, null, false); - }) - .when(fixture.ownerService) - .commit(any()); - - assertThatThrownBy( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isInstanceOf(IllegalStateException.class); - - verify(fixture.ownerService, never()).abort(any()); - verify(fixture.ownerService).attachHold(any()); - verify(fixture.ownerService).commit(any()); + void exactReplayUsesTheSameOperationAndReturnsTheSameStartingAllocation() { + Fixture fixture = fixture(true); + + var first = fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); + var replay = fixture.coordinator.coordinate(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 rejectsMismatchedWorldHoldBeforeAttachingOrCommitting() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> - AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold( - hold( - InitialAdmissionBindHoldStatus - .INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, - UUID.fromString("49de9f26-f314-40e1-96a7-5655c5e5b16e"), - fixture.request.get().requestDigest())) - .build()) - .when(fixture.worldClient) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); + 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( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) + () -> + changedIdentity.coordinator.coordinate( + changedIdentity.capability, changedIdentity.sourceReceipt)) .isInstanceOf(IllegalStateException.class); - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - } - - @Test - void rejectsMalformedWorldHoldIdentityBeforeAttachingOrCommitting() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> { - UUID namespaceId = invocation.getArgument(7); - String requestDigest = invocation.getArgument(5); - return AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold( - hold( - InitialAdmissionBindHoldStatus - .INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, - namespaceId, - requestDigest) - .toBuilder() - .setHoldFence("not-a-uuid") - .build()) - .build(); - }) - .when(fixture.worldClient) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); + 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( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) + () -> + changedStatus.coordinator.coordinate( + changedStatus.capability, changedStatus.sourceReceipt)) .isInstanceOf(IllegalStateException.class); - - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - } - - @Test - void rejectsMissingOrNoncanonicalCommittedAuditId() { - for (String auditId : new String[] {null, "031"}) { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof( - binding, - Outcome.COMMITTED, - ATTEMPT_ID, - auditId, - 1L, - binding.requestDigest(), - false); - }) - .when(fixture.ownerService) - .commit(any()); - - assertThatThrownBy( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isInstanceOf(IllegalStateException.class); - } - } - - @Test - void terminalWorldAbortUsesExactReadbackWithoutTryingToCommit() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED); - when(fixture.ownerService.read(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof(binding, Outcome.ABORTED, ATTEMPT_ID, null, 0L, null, true); - }); - - assertThat(fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.ABORTED); - - verify(fixture.ownerService).read(any()); - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - } - - @Test - void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { - GameInstanceService gameInstanceService = org.mockito.Mockito.mock(GameInstanceService.class); - InitialAdmissionBindOwnerService ownerService = - org.mockito.Mockito.mock(InitialAdmissionBindOwnerService.class); - WorldManagementClient worldClient = org.mockito.Mockito.mock(WorldManagementClient.class); - RunOwnedInitialAdmissionFixtureCoordinator coordinator = - new RunOwnedInitialAdmissionFixtureCoordinator( - false, - "", - "", - "", - "", - new CommonGrpcClientProperties(), - gameInstanceService, - ownerService, - worldClient); - - coordinator.retryRunOwnedFixtureBootstrap(); - - verifyNoInteractions(gameInstanceService, ownerService, worldClient); } @Test - void missingSourceReceiptRejectsBeforeLaunchOrOwnerMutation() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenThrow(RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - - verifyNoInteractions(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); + 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.coordinate(fixture.capability, changedReceipt)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(fixture.launchOwner); } @Test - void changedSourceReceiptAcrossRetriesIsRejectedBeforeSecondLaunch() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doThrow(new IllegalStateException("stop after initial launch")) - .when(fixture.ownerService) - .registerPublicSharedFixtureCatalog(any()); - var changedReceipt = - sourceReceipt( - fixture.capability, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")); - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt, changedReceipt); + void disabledCoordinatorDoesNotReadFixturePathsOrWriteLaunchOwner() { + Fixture fixture = fixture(false); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } + fixture.coordinator.retryRunOwnedFixtureBootstrap(); - verify(fixture.gameInstanceService, times(1)) - .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); - verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); - verify(fixture.ownerService, never()).beginIntent(any()); - verifyNoInteractions(fixture.worldClient); + verifyNoInteractions(fixture.launchOwner); } @Test - void changedOwnerReadEvidenceAcrossRetriesIsRejectedBeforeSecondLaunch() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doThrow(new IllegalStateException("stop after initial launch")) - .when(fixture.ownerService) - .registerPublicSharedFixtureCatalog(any()); - var changedReceipt = - withPublishedReleaseBundleRef(fixture.sourceReceipt, "owner-release-ref-changed"); - try (MockedStatic capabilityLoader = + 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)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt, changedReceipt); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); + 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); + + 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(); + } } - - verify(fixture.gameInstanceService, times(1)) - .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); - verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); - verify(fixture.ownerService, never()).beginIntent(any()); - verifyNoInteractions(fixture.worldClient); } @Test - void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( - CapturedOutput output) { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - String hostileMessage = - "capability-bytes=secret grpc-status-detail=tenant-token raw-pointer=private"; - doThrow(new IllegalStateException(hostileMessage)) - .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any(), any()); - - try (MockedStatic capabilityLoader = + void retryPinsReceiptRejectsChangedSourceAndExhaustsAtTheBoundedBudget() { + Fixture conflict = fixture(true); + var changedReceipt = sourceReceipt(conflict.capability, 30L); + doAnswer( + invocation -> { + throw new IllegalStateException("owner unavailable"); + }) + .when(conflict.launchOwner) + .createVerifiedFixtureStartingLaunch(any()); + try (MockedStatic loader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); + stubFixtureLoaders(loader, conflict, conflict.sourceReceipt, changedReceipt); + conflict.coordinator.retryRunOwnedFixtureBootstrap(); + conflict.coordinator.retryRunOwnedFixtureBootstrap(); } + verify(conflict.launchOwner, times(1)).createVerifiedFixtureStartingLaunch(any()); + verify(conflict.launchOwner, never()).readVerifiedFixtureLaunch(any()); - assertThat(output) - .contains("exceptionType=IllegalStateException") - .contains("errorCode=FIXTURE_STATE_UNRESOLVED") - .contains("message=Fixture state remains unresolved.") - .doesNotContain(hostileMessage, "capability-bytes=secret", "tenant-token", "raw-pointer"); - } - - @Test - void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( - CapturedOutput output) { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - String hostileMessage = "grpc sensitive details capability bytes that must not appear"; - doThrow(new IllegalStateException(hostileMessage)) - .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any(), any()); - - try (MockedStatic capabilityLoader = + Fixture exhausted = fixture(true); + doAnswer( + invocation -> { + throw new IllegalStateException("owner unavailable"); + }) + .when(exhausted.launchOwner) + .createVerifiedFixtureStartingLaunch(any()); + try (MockedStatic loader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt); - - for (int attempt = 0; attempt < 12; attempt++) { - fixture.coordinator.retryRunOwnedFixtureBootstrap(); + stubFixtureLoaders(loader, exhausted, exhausted.sourceReceipt); + for (int attempt = 0; attempt < 13; attempt++) { + exhausted.coordinator.retryRunOwnedFixtureBootstrap(); } } - - assertThat(output) - .contains("did not reach a verified terminal result after the bounded retry budget") - .contains("exceptionType=IllegalStateException") - .contains("errorCode=FIXTURE_STATE_UNRESOLVED") - .contains("message=Fixture state remains unresolved.") - .doesNotContain(hostileMessage, "grpc sensitive details", "capability bytes"); + verify(exhausted.launchOwner, times(12)).createVerifiedFixtureStartingLaunch(any()); + verify(exhausted.launchOwner, never()).readVerifiedFixtureLaunch(any()); } @Test - void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - AtomicInteger worldAcquisitions = new AtomicInteger(); + void scheduledRetryDoesNotOverlapAnInProgressLaunchOwnerAttempt() throws Exception { + Fixture fixture = fixture(true); + CountDownLatch enteredOwner = new CountDownLatch(1); + CountDownLatch releaseOwner = new CountDownLatch(1); doAnswer( invocation -> { - int acquisition = worldAcquisitions.incrementAndGet(); - if (acquisition <= 12) { - throw new IllegalStateException("Simulated unresolved World response"); + enteredOwner.countDown(); + if (!releaseOwner.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for owner release"); } - String requestDigest = invocation.getArgument(5); - return AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold( - hold( - InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, - NAMESPACE_ID, - requestDigest)) - .build(); + throw new IllegalStateException("Controlled unresolved owner result"); }) - .when(fixture.worldClient) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); - - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt); - - // Orchestration unit proof only; capability TLS and durable cross-service behavior have - // separate proof boundaries. - for (int attempt = 0; attempt < 12; attempt++) { - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - - verify(fixture.ownerService, times(12)).beginIntent(any()); - verify(fixture.worldClient, times(12)) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - eq(OPERATION_ID), - anyString(), - eq(REALM_ID), - eq(NAMESPACE_ID), - eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), - eq(3L)); - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - capabilityLoader.verify( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - eq(Path.of(CAPABILITY_PATH)), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.grpcProperties)), - times(12)); + .when(fixture.launchOwner) + .createVerifiedFixtureStartingLaunch(any()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var first = + executor.submit( + () -> { + try (MockedStatic loader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + stubFixtureLoaders(loader, fixture, fixture.sourceReceipt); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } + }); + assertThat(enteredOwner.await(5, TimeUnit.SECONDS)).isTrue(); fixture.coordinator.retryRunOwnedFixtureBootstrap(); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - verify(fixture.ownerService, times(12)).beginIntent(any()); - verify(fixture.worldClient, times(12)) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); - capabilityLoader.verify( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), anyString(), anyString(), any(CommonGrpcClientProperties.class)), - times(12)); - - RunOwnedInitialAdmissionFixtureCoordinator restarted = newCoordinator(fixture); - restarted.retryRunOwnedFixtureBootstrap(); - - ArgumentCaptor launchRequests = - ArgumentCaptor.forClass(StartSessionRequest.class); - verify(fixture.gameInstanceService, times(13)) - .startRunOwnedInitialLaunch( - launchRequests.capture(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); - assertThat(launchRequests.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.tenantId()).isEqualTo(fixture.capability.tenantId()); - assertThat(request.gameTemplateId()).isEqualTo(fixture.capability.gameTemplateId()); - assertThat(request.ownerAccountId()).isEqualTo(fixture.capability.ownerAccountId()); - assertThat(request.controlPlaneRequestId()).isEqualTo(OPERATION_ID); - }); - ArgumentCaptor ownerRequests = - ArgumentCaptor.forClass(InitialAdmissionBindRequest.class); - verify(fixture.worldClient, times(13)) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - eq(OPERATION_ID), - anyString(), - eq(REALM_ID), - eq(NAMESPACE_ID), - eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), - eq(3L)); - verify(fixture.ownerService, times(13)).beginIntent(ownerRequests.capture()); - assertThat(ownerRequests.getAllValues()) - .extracting(InitialAdmissionBindRequest::initialAdmissionRequestId) - .containsOnly(OPERATION_ID); - assertThat(ownerRequests.getAllValues()) - .extracting(InitialAdmissionBindRequest::requestDigest) - .doesNotContainNull() - .containsOnly(ownerRequests.getValue().requestDigest()); - verify(fixture.ownerService).attachHold(any()); - verify(fixture.ownerService).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - capabilityLoader.verify( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - eq(Path.of(CAPABILITY_PATH)), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.grpcProperties)), - times(13)); - restarted.retryRunOwnedFixtureBootstrap(); - verify(fixture.ownerService, times(13)).beginIntent(any()); - verify(fixture.ownerService).commit(any()); + verify(fixture.launchOwner, times(1)).createVerifiedFixtureStartingLaunch(any()); + releaseOwner.countDown(); + first.get(5, TimeUnit.SECONDS); + verify(fixture.launchOwner, times(1)).createVerifiedFixtureStartingLaunch(any()); + } finally { + releaseOwner.countDown(); + executor.shutdownNow(); } } - private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { - GameInstanceService gameInstanceService = org.mockito.Mockito.mock(GameInstanceService.class); - InitialAdmissionBindOwnerService ownerService = - org.mockito.Mockito.mock(InitialAdmissionBindOwnerService.class); - WorldManagementClient worldClient = org.mockito.Mockito.mock(WorldManagementClient.class); + private static Fixture fixture(boolean enabled) { CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); grpc.setPlaintext(true); - RunOwnedInitialAdmissionFixtureCapability capability = - new RunOwnedInitialAdmissionFixtureCapability( - RUN_ID, - PROJECT_NAME, - OPERATION_ID, - 7L, - 17L, - 27L, - "demo", - "Demo World", - "production", - "Live Realm", - 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)); - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = + RunOwnedInitialAdmissionFixtureCapability capability = capability(); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt = sourceReceipt(capability, 29L); - GameInstanceDto target = - new GameInstanceDto( - 42L, - 7L, - "v1", - null, - null, - null, - null, - 17L, - "launch-descriptor-1", - 11L, - 13L, - 3L, - "config-1", - null, - 27L, - "RUNNING"); - when(gameInstanceService.startRunOwnedInitialLaunch(any(), any())) - .thenReturn(new RunOwnedInitialLaunchResult(target, 4L)); - - InitialAdmissionBindCatalog catalog = - new InitialAdmissionBindCatalog( - REALM_ID, - 7L, - 17L, - "demo", - "Demo World", - "production", - "Live Realm", - 3L, - NAMESPACE_ID, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - Instant.now()); - when(ownerService.registerPublicSharedFixtureCatalog( - any(InitialAdmissionBindCatalogDescriptor.class))) - .thenReturn(catalog); - - AtomicReference request = new AtomicReference<>(); - when(ownerService.beginIntent(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindRequest received = invocation.getArgument(0); - request.set(received); - return attempt(received, catalog, null, null, Status.PENDING); - }); - when(worldClient.acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldStatus selectedStatus = holdStatus; - UUID namespaceId = invocation.getArgument(7); - String requestDigest = invocation.getArgument(5); - return AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold(hold(selectedStatus, namespaceId, requestDigest)) - .build(); - }); - when(ownerService.attachHold(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return attempt( - request.get(), - catalog, - UUID.fromString(binding.holdId()), - UUID.fromString(binding.holdFence()), - Status.PENDING); - }); - when(ownerService.commit(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof( - binding, Outcome.COMMITTED, ATTEMPT_ID, "31", 1L, binding.requestDigest(), false); - }); + FixtureCanonicalInstanceLaunch allocation = allocation(capability, receipt); + GameSessionCanonicalInstanceLaunchRepository launchOwner = + mock(GameSessionCanonicalInstanceLaunchRepository.class); + when(launchOwner.createVerifiedFixtureStartingLaunch(any())).thenReturn(allocation); + when(launchOwner.readVerifiedFixtureLaunch(any())).thenReturn(allocation); RunOwnedInitialAdmissionFixtureCoordinator coordinator = new RunOwnedInitialAdmissionFixtureCoordinator( - true, + enabled, CAPABILITY_PATH, SOURCE_RECEIPT_PATH, RUN_ID, PROJECT_NAME, grpc, - gameInstanceService, - ownerService, - worldClient); - return new Fixture( - coordinator, - capability, - sourceReceipt, - grpc, - gameInstanceService, - ownerService, - worldClient, - request); + launchOwner, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE); + return new Fixture(coordinator, capability, receipt, grpc, launchOwner, allocation); } - private static RunOwnedInitialAdmissionFixtureCoordinator newCoordinator(Fixture fixture) { - return new RunOwnedInitialAdmissionFixtureCoordinator( - true, - CAPABILITY_PATH, - SOURCE_RECEIPT_PATH, - RUN_ID, - PROJECT_NAME, - fixture.grpcProperties, - fixture.gameInstanceService, - fixture.ownerService, - fixture.worldClient); + 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 InitialAdmissionBindAttempt attempt( - InitialAdmissionBindRequest request, - InitialAdmissionBindCatalog catalog, - UUID holdId, - UUID holdFence, - Status status) { - Instant now = Instant.now(); - return new InitialAdmissionBindAttempt( - ATTEMPT_ID, - request.tenantId(), - request.initialAdmissionRequestId(), - request.requestDigest(), - catalog.realmId(), - catalog.playableStateNamespaceId(), - "SHARED", + 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, - catalog.catalogRevision(), - request.gameInstanceId(), - request.versionId(), - request.activeLifecycleEpoch(), - holdId, - holdFence, - status, - status == Status.COMMITTED ? 1L : null, - status == Status.COMMITTED ? 31L : null, - now, - now, - status == Status.PENDING ? null : now); + 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) { - return sourceReceipt(capability, sourceGameRowId, SOURCE_OPERATION_ID); - } - - private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( - RunOwnedInitialAdmissionFixtureCapability capability, - long sourceGameRowId, - UUID operationId) { - UUID registrationRequestId = UUID.fromString(capability.operationId()); - UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); String targetNamespace = RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE; String tenantSlug = "fixture-tenant"; - String worldSlug = capability.worldSlug(); - String worldDisplayName = capability.worldDisplayName(); - String sourceGameTenantKey = Long.toString(capability.tenantId()); + String sourceGameTenantKey = "1"; String provenanceKind = "NEW_GAME_ROW"; - String requestDigest = + UUID registrationRequestId = UUID.fromString(capability.operationId()); + String sourceRequestDigest = AuthoredWorldSourceDigest.requestDigest( targetNamespace, registrationRequestId, - canonicalTenantId, + CANONICAL_TENANT_ID, tenantSlug, - worldSlug, - worldDisplayName); - AuthoredWorldSourceEvidence evidence = + capability.worldSlug(), + capability.worldDisplayName()); + AuthoredWorldSourceEvidence sourceEvidence = new AuthoredWorldSourceEvidence( 1, targetNamespace, registrationRequestId, - operationId, - requestDigest, - canonicalTenantId, + SOURCE_OPERATION_ID, + sourceRequestDigest, + CANONICAL_TENANT_ID, tenantSlug, - worldSlug, - worldDisplayName, + capability.worldSlug(), + capability.worldDisplayName(), sourceGameRowId, sourceGameTenantKey, provenanceKind, AuthoredWorldSourceDigest.evidenceDigest( targetNamespace, registrationRequestId, - operationId, - requestDigest, - canonicalTenantId, + SOURCE_OPERATION_ID, + sourceRequestDigest, + CANONICAL_TENANT_ID, tenantSlug, - worldSlug, - worldDisplayName, + 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(), @@ -879,44 +521,10 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec capability.caCertificateSha256(), capability.worldManagementUriSan(), capability.worldManagementLeafSha256(), - evidence, - launchReadEvidence(capability, evidence)); - } - - private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt - withPublishedReleaseBundleRef( - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt, String bundleRef) { - var original = receipt.launchReadEvidence(); - var changedBundle = - original.publishedReleaseBundle().toBuilder() - .setPublishedReleaseBundleRef(bundleRef) - .build(); - var changedReadEvidence = - new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( - original.schema(), - original.gameTemplateId(), - changedBundle, - original.versionAssetArtifactState(), - original.versionState(), - launchDescriptor( - receipt.sourceEvidence(), - changedBundle, - original.versionState(), - original.gameTemplateId(), - receipt.fixtureOperationId())); - return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( - receipt.schema(), - receipt.runId(), - receipt.composeProjectName(), - receipt.fixtureOperationId(), - receipt.ownerService(), - receipt.gameSessionUriSan(), - receipt.gameSessionLeafSha256(), - receipt.caCertificateSha256(), - receipt.worldManagementUriSan(), - receipt.worldManagementLeafSha256(), - receipt.sourceEvidence(), - changedReadEvidence); + sourceEvidence, + launchRead, + creationEvidence, + seal); } private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence launchReadEvidence( @@ -924,8 +532,8 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun AuthoredWorldSourceEvidence sourceEvidence) { String manifestHash = "sha256:" + "a".repeat(64); String artifactDigest = "sha256:" + "b".repeat(64); - var bundle = - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() + PublishedReleaseBundle bundle = + PublishedReleaseBundle.newBuilder() .setId(77L) .setVersionId(11L) .setVersionNumber(1) @@ -935,7 +543,7 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun .addRequiredManifestAssetKeys("manifest.json") .setGenerationConfigRevision("genrev-11") .setPublishedAt("2026-04-15T10:00:00") - .setPublishedReleaseBundleRef("owner-release-ref-11") + .setPublishedReleaseBundleRef("prb:7:11:77") .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") .setManifestSchemaVersion(1) @@ -943,64 +551,40 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() .setUsageKey("manifest.json") .setArtifactKind("manifest") - .setImmutableObjectKey( - "artifacts/sha256/" + artifactDigest.substring("sha256:".length())) + .setImmutableObjectKey("artifacts/sha256/" + artifactDigest.substring(7)) .setContentDigest(artifactDigest) .setContentType("application/json") .setArtifactSchemaVersion(1) .build()) .build(); - var artifactState = - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() + VersionAssetArtifactState artifactState = + VersionAssetArtifactState.newBuilder() .setTenantId(Long.toString(capability.tenantId())) .setVersionId(11L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) .setStateEpoch(2L) .setManifestHash(manifestHash) .setUpdatedAt("2026-04-15T10:00:00") .addExportedManifestAssetKeys("manifest.json") .setExportedVersionNumber(1) .build(); - var versionState = - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() + VersionStateSnapshot versionState = + VersionStateSnapshot.newBuilder() .setTenantId(Long.toString(capability.tenantId())) .setVersionId(11L) - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) .setVersionStateEpoch(77L) .setUpdatedAt("2026-04-15T10:00:00") .build(); - return new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( - RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, - capability.gameTemplateId(), - bundle, - artifactState, - versionState, - launchDescriptor( - sourceEvidence, - bundle, - versionState, - capability.gameTemplateId(), - capability.operationId())); - } - - private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor launchDescriptor( - AuthoredWorldSourceEvidence sourceEvidence, - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, - long gameTemplateId, - String controlPlaneRequestId) { - var request = + AuthoredWorldLaunchDescriptorEvidence.Request request = new AuthoredWorldLaunchDescriptorEvidence.Request( - RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, - controlPlaneRequestId, + RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, + capability.operationId(), sourceEvidence.canonicalTenantId(), sourceEvidence.worldSlug(), sourceEvidence.operationId(), sourceEvidence.evidenceDigest(), - gameTemplateId, + capability.gameTemplateId(), false, null, false, @@ -1009,7 +593,7 @@ private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor launchDescr null, false, null); - var evidence = + var descriptorEvidence = AuthoredWorldLaunchDescriptorEvidence.create( request, "launch-descriptor-fixture-11", @@ -1023,57 +607,65 @@ private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor launchDescr bundle.getPublishedReleaseBundleRef(), false, null); - return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence); - } - - private static InitialAdmissionBindHold hold( - InitialAdmissionBindHoldStatus status, UUID namespaceId, String requestDigest) { - return InitialAdmissionBindHold.newBuilder() - .setHoldId(HOLD_ID.toString()) - .setHoldFence(HOLD_FENCE.toString()) - .setTenantId("7") - .setRealmUuid(REALM_ID.toString()) - .setPlayableStateNamespaceUuid(namespaceId.toString()) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setGameInstanceId("42") - .setVersionId("11") - .setActiveLifecycleEpoch(4L) - .setInitialAdmissionRequestId(OPERATION_ID) - .setRequestDigest(requestDigest) - .setExpectedNoPriorPointer(true) - .setExpectedCatalogRevision(3L) - .setStatus(status) - .build(); + LaunchDescriptor descriptor = + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); + return new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureCapability.LAUNCH_READ_EVIDENCE_SCHEMA, + capability.gameTemplateId(), + bundle, + artifactState, + versionState, + descriptor); } - private static InitialAdmissionBindOwnerProof proof( - InitialAdmissionBindHoldBinding binding, - Outcome outcome, - UUID attemptId, - String auditId, - long pointerVersion, - String auditDigest, - boolean futureCommitPrevented) { - return new InitialAdmissionBindOwnerProof( - outcome, - binding.holdId(), - binding.holdFence(), - binding.tenantId(), - binding.realmUuid(), - binding.playableStateNamespaceUuid(), - binding.playableStateScope(), - binding.gameInstanceId(), - binding.versionId(), - binding.activeLifecycleEpoch(), - binding.initialAdmissionRequestId(), - binding.requestDigest(), - binding.expectedNoPriorPointer(), - binding.expectedCatalogRevision(), - attemptId.toString(), - auditId, - pointerVersion, - auditDigest, - futureCommitPrevented); + 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( @@ -1081,8 +673,6 @@ private record Fixture( RunOwnedInitialAdmissionFixtureCapability capability, RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt, CommonGrpcClientProperties grpcProperties, - GameInstanceService gameInstanceService, - InitialAdmissionBindOwnerService ownerService, - WorldManagementClient worldClient, - AtomicReference request) {} + GameSessionCanonicalInstanceLaunchRepository launchOwner, + FixtureCanonicalInstanceLaunch allocation) {} } 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..b14b790ff5 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,97 @@ 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.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.UUID; 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; class CanonicalInitialAdmissionRepositoryTest { + @Test + void incompleteHumanCommitAndAbortDenyBeforeAnyOwnerStorageInteraction() { + var dsl = mock(DSLContext.class); + var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); + var pointers = mock(GameSessionCanonicalAdmissionPointerRepository.class); + var launches = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var events = mock(GameplayAdmissionPointerEventRepository.class); + var repository = + new CanonicalInitialAdmissionRepository(dsl, catalog, pointers, launches, events); + var prior = committedProof(); + String digest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + prior.targetNamespace(), + prior.canonicalTenantId(), + prior.worldSlug(), + prior.realmId(), + prior.playableStateNamespaceId(), + prior.playableStateScope(), + prior.canonicalGameInstanceId(), + prior.canonicalVersionId(), + prior.activeLifecycleEpoch(), + prior.expectedCatalogRevision(), + prior.originKind(), + prior.expectedPriorPointerVersion(), + prior.initialAdmissionRequestId()); + var request = + new CanonicalInitialAdmissionRequest( + prior.targetNamespace(), + prior.canonicalTenantId(), + prior.worldSlug(), + prior.realmId(), + prior.playableStateNamespaceId(), + prior.playableStateScope(), + prior.canonicalGameInstanceId(), + prior.canonicalVersionId(), + prior.activeLifecycleEpoch(), + prior.expectedCatalogRevision(), + prior.originKind(), + prior.expectedPriorPointerVersion(), + prior.initialAdmissionRequestId(), + digest, + prior.holdId(), + prior.holdFence(), + prior.holdBindingDigest()); + var world = + new CanonicalInitialAdmissionWorldProof( + request.initialAdmissionRequestId(), + digest, + 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()); + assertThatThrownBy(() -> repository.commit(request, world, null)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); + assertThatThrownBy(() -> repository.abort(request, null, "Missing protection")) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class); + verifyNoInteractions(dsl, catalog, pointers, launches, events); + } + @Test void pointerAndAuditVersionsUseValueEqualityBeyondLongCache() { Long attemptVersion = Long.valueOf(129L); @@ -102,7 +183,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 +196,28 @@ private static Map validOpenFields() { return fields; } + 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/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/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/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionHoldPreparationTest.java index dce51a8bcd..215e740db5 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,8 +3,6 @@ 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; @@ -48,157 +46,62 @@ void clearTransactionContext() { } @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(); - }); + void freshHumanRequestDeniesBeforeIntentTransactionOrWorldAccess() { + Fixtures fixtures = new Fixtures(new ArrayList<>()); + assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); } @Test - void reserveFailurePreventsWorldAcquisition() throws Exception { + void unavailableIntentOwnerCannotMoveDenialAfterReservation() { 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()); + assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); } @Test - void reserveCommitFailurePreventsWorldAcquisitionAndAttachment() throws Exception { + void failingTransactionManagerCannotBeginUnprotectedHumanReservation() { 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); + assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); } @Test - void remoteFailureLeavesPendingIntentAndRetryUsesTheSameExactRequest() throws Exception { + void repeatedHumanRequestDoesNotReserveOrAcquireAfterRemoteFailure() { 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); + .thenThrow(new IllegalStateException("World unavailable")); + for (int retry = 0; retry < 2; retry++) { + assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); + } } @Test - void attachFailurePropagatesWithoutReplacingRequestOrCallingAnyCompensation() throws Exception { + void configuredWorldIdentityAndAttachFailureCannotBypassHumanProtection() { 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)) + HoldIdentity acquired = identity(HOLD_REQUEST, 9); + when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(acquired); + when(fixtures.repository.attach(HOLD_REQUEST, acquired)) .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()); + assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); } @Test - void exactAttachedOrTerminalReplayReturnsHistoricalSnapshotWithoutWorldCall() throws Exception { + void attachedOrTerminalReadbackCannotAuthorizeNewHumanPreparation() { 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()); + // Controlled readback input is never queried and establishes no live admission authority. + var retained = snapshot(state, identity(HOLD_REQUEST, 10), HOLD_REQUEST, LIFECYCLE_REQUEST); + when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(retained); + assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); } } @Test - void wrongWorldIdentityAndChangedSnapshotTupleAreDenied() throws Exception { + void changedRequestLifecycleSnapshotAndWorldIdentityCannotBypassEarlyHumanDenial() { 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()); + assertHumanUnavailable(wrongIdentity, HOLD_REQUEST, LIFECYCLE_REQUEST); Fixtures changedSnapshot = new Fixtures(new ArrayList<>()); when(changedSnapshot.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) @@ -208,16 +111,10 @@ void wrongWorldIdentityAndChangedSnapshotTupleAreDenied() throws Exception { null, HOLD_REQUEST, lifecycleRequestWithChangedIdentity())); - assertThatThrownBy(() -> changedSnapshot.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("changed the exact request tuple"); - verifyNoInteractions(changedSnapshot.worldClient); + assertHumanUnavailable(changedSnapshot, HOLD_REQUEST, LIFECYCLE_REQUEST); 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( @@ -225,9 +122,15 @@ void wrongWorldIdentityAndChangedSnapshotTupleAreDenied() throws Exception { identity(HOLD_REQUEST, 14), HOLD_REQUEST, LIFECYCLE_REQUEST)); - assertThatThrownBy(() -> changedAttach.preparation.prepare(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("exact World hold identity"); + assertHumanUnavailable(changedAttach, HOLD_REQUEST, LIFECYCLE_REQUEST); + assertHumanUnavailable( + new Fixtures(new ArrayList<>()), + holdRequest("different-request"), + lifecycleRequestWithChangedIdentity()); + assertHumanUnavailable( + new Fixtures(new ArrayList<>()), + holdRequest("closed-origin-request", InitialAdmissionOrigin.EXPECT_CLOSED, 1L), + LIFECYCLE_REQUEST); } @Test @@ -248,12 +151,18 @@ 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(); + assertThat(fixtures.transactionManager.events).isEmpty(); } private static CanonicalInitialAdmissionIntentSnapshot snapshot( @@ -298,6 +207,11 @@ private static CanonicalInitialAdmissionIntentSnapshot snapshot( } private static Request holdRequest(String requestId) { + return holdRequest(requestId, InitialAdmissionOrigin.NO_PRIOR_POINTER, null); + } + + private static Request holdRequest( + String requestId, InitialAdmissionOrigin origin, Long priorPointerVersion) { String requestDigest = CanonicalInitialAdmissionRequest.computeRequestDigest( NAMESPACE, @@ -310,8 +224,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 +239,9 @@ private static Request holdRequest(String requestId) { 2L, requestId, requestDigest, - InitialAdmissionOrigin.NO_PRIOR_POINTER, + origin, 1L, - null); + priorPointerVersion); } private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest() { 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..a071e9dd26 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; @@ -39,7 +37,6 @@ class DatabaseCanonicalInitialAdmissionServiceTest { private final CanonicalInitialAdmissionWorldVerifier worldVerifier = mock(CanonicalInitialAdmissionWorldVerifier.class); private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(0); - private int readbackCount; private final DatabaseCanonicalInitialAdmissionService service = new DatabaseCanonicalInitialAdmissionService( repository, pointerRepository, worldVerifier, transactionManager); @@ -49,140 +46,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 +67,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) { 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..71e9694b54 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 @@ -1,7 +1,6 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -10,7 +9,6 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @@ -73,8 +71,6 @@ class GameInstanceServiceImplTest { private GameInstanceServiceImpl service; private Map store; private AtomicLong nextId; - private String runOwnedBundleRefOverride; - private LaunchDescriptor runOwnedDescriptorOverride; @Test void legacyDtoConstructorRejectsNonblankPatchWithoutCompleteTuple() { @@ -112,8 +108,6 @@ void setup() { meterRegistry = new SimpleMeterRegistry(); store = new HashMap<>(); nextId = new AtomicLong(10L); - runOwnedBundleRefOverride = null; - runOwnedDescriptorOverride = null; service = new GameInstanceServiceImpl( repository, @@ -223,484 +217,18 @@ void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority(String l } @Test - void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { + void verifiedRunOwnedLaunchCannotEnterUnavailableWorldPhaseOrNumericAllocation() { StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000001", 42L); - configureRunOwnedWorld(request); - - var first = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); - clearInvocations(stateService, worldManagementClient); - var retry = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); - - assertEquals(first.gameInstance().id(), retry.gameInstance().id()); - assertEquals(10L, retry.gameInstance().id()); - assertEquals(11L, retry.gameInstance().versionId()); - assertEquals(2L, retry.activeLifecycleEpoch()); - assertEquals("RUNNING", store.get(10L).getStatus()); - assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); - assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); - assertEquals(64, store.get(10L).getRunOwnedStartRequestDigest().length()); - ArgumentCaptor repairedState = ArgumentCaptor.forClass(GameInstanceDto.class); - verify(stateService).saveState(repairedState.capture()); - assertEquals("RUNNING", repairedState.getValue().status()); - verify(worldManagementClient).getWorldInstanceLifecycle(1L, 10L); - verifyNoMoreInteractions(worldManagementClient); - } - - @Test - void runOwnedLaunchUsesOpaqueOwnerReferenceWithoutCallingDeniedReadRpcs() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000010", 42L); - String opaqueBundleRef = "gds:owner-ref:immutable-release-77"; - runOwnedBundleRefOverride = opaqueBundleRef; - configureRunOwnedWorld(request); - - service.startRunOwnedInitialLaunch( - request, - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - request, sourceEvidence(request), opaqueBundleRef)); - - ArgumentCaptor preparedBundleRef = ArgumentCaptor.forClass(String.class); - verify(worldManagementClient) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - preparedBundleRef.capture(), - anyLong(), - any()); - assertEquals(opaqueBundleRef, preparedBundleRef.getValue()); - assertEquals(opaqueBundleRef, store.get(10L).getRunOwnedStartPublishedReleaseBundleRef()); - verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); - } - - @Test - void runOwnedLaunchRejectsDifferentValidResolveDescriptorBeforeMutation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000012", 42L); - var ownerEvidence = launchEvidence(request); - runOwnedDescriptorOverride = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - request, sourceEvidence(request), "gds:owner-ref:different-release") - .launchDescriptor(); - assertFalse( - ownerEvidence - .launchDescriptor() - .getAuthoredWorldBinding() - .getResultDigest() - .equals(runOwnedDescriptorOverride.getAuthoredWorldBinding().getResultDigest())); - - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> service.startRunOwnedInitialLaunch(request, ownerEvidence)); - - assertEquals( - "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" - + " owner receipt descriptor", - error.getMessage()); - verifyNoInteractions(stateService, worldManagementClient); - verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); - } - - @Test - void runOwnedLaunchRejectsOwnerVersionEpochMismatchBeforeWorldPreparation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000013", 42L); - var original = launchEvidence(request); - var changed = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - request, - sourceEvidence(request), - original.publishedReleaseBundle(), - original.versionAssetArtifactState(), - original.versionState().toBuilder().setVersionStateEpoch(78L).build()); - - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> service.startRunOwnedInitialLaunch(request, changed)); - - assertEquals( - "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" - + " owner receipt descriptor", - error.getMessage()); - assertTrue(store.isEmpty()); - verifyNoInteractions(stateService, worldManagementClient); - } - - @Test - void runOwnedLaunchRejectsUnrecognizedOwnerVersionStateBeforeWorldPreparation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000015", 42L); - var original = launchEvidence(request); - var unchecked = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.createUncheckedForServicePreflightTests( - request, - sourceEvidence(request), - original.publishedReleaseBundle(), - original.versionAssetArtifactState(), - original.versionState().toBuilder().setVersionStateValue(999).build()); - - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> service.startRunOwnedInitialLaunch(request, unchecked)); - - assertEquals( - "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", - error.getMessage()); - verifyNoInteractions(worldManagementClient); - verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); - } - - @Test - void runOwnedLaunchRejectsOwnerVersionIdentityMismatchBeforeWorldPreparation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000014", 42L); - var original = launchEvidence(request); - var changed = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - request, - sourceEvidence(request), - original.publishedReleaseBundle().toBuilder() - .setVersionId(12L) - .setCanonicalVersionId("10000000-0000-4000-8000-000000000012") - .build(), - original.versionAssetArtifactState().toBuilder().setVersionId(12L).build(), - original.versionState().toBuilder().setVersionId(12L).build()); - - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> service.startRunOwnedInitialLaunch(request, changed)); - - assertEquals( - "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" - + " owner receipt descriptor", - error.getMessage()); - assertTrue(store.isEmpty()); - verifyNoInteractions(stateService, worldManagementClient); - } - - @Test - void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000002", 42L); - AtomicReference worldState = configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request, launchEvidence(request)); - clearInvocations(stateService, worldManagementClient); - worldState.set( - runOwnedWorldSnapshot( - request, - 10L, - 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); - - IllegalStateException error = - assertThrows( - IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); - - assertEquals( - "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World", - error.getMessage()); - assertEquals("RUNNING", store.get(10L).getStatus()); - assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); - verifyNoInteractions(stateService); - verify(worldManagementClient).getWorldInstanceLifecycle(1L, 10L); - verifyNoMoreInteractions(worldManagementClient); - } - - @Test - void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000003", 42L); - AtomicReference worldState = configureRunOwnedWorld(request); - AtomicInteger prepareCalls = new AtomicInteger(); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenAnswer( - invocation -> { - if (prepareCalls.getAndIncrement() == 0) { - worldState.set( - runOwnedWorldSnapshot( - request, - invocation.getArgument(1, Long.class), - 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); - throw new IllegalStateException("prepare response timed out"); - } - return net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse - .newBuilder() - .setWorldInstance(worldState.get()) - .build(); - }); - - IllegalStateException pending = - assertThrows( - IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); - - assertEquals("world preparation authority unavailable", pending.getMessage()); - assertEquals(1, store.size()); - assertEquals(10L, store.get(10L).getId()); - assertNull(store.get(10L).getRunOwnedStartPreparingEpoch()); - - var resumed = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); - - assertEquals(10L, resumed.gameInstance().id()); - assertEquals(2L, resumed.activeLifecycleEpoch()); - assertEquals(1, store.size()); - assertEquals("RUNNING", store.get(10L).getStatus()); - verify(worldManagementClient, times(2)) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any()); - } - - @Test - void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000004", 42L); - AtomicReference worldState = configureRunOwnedWorld(request); - doThrow(new IllegalStateException("activation response timed out")) - .when(worldManagementClient) - .activatePreparedWorldInstance(1L, 10L, 1L); - - IllegalStateException pending = - assertThrows( - IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); - - assertEquals("world activation authority unavailable", pending.getMessage()); - assertEquals("STARTING", store.get(10L).getStatus()); - assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); - assertNull(store.get(10L).getRunOwnedStartActiveEpoch()); - worldState.set( - runOwnedWorldSnapshot( - request, 10L, 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); - - var resumed = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); - - assertEquals(10L, resumed.gameInstance().id()); - assertEquals(2L, resumed.activeLifecycleEpoch()); - assertEquals(1, store.size()); - assertEquals("RUNNING", store.get(10L).getStatus()); - verify(worldManagementClient, times(1)).activatePreparedWorldInstance(1L, 10L, 1L); - verify(repository, never()).deleteById(10L); - } - - @Test - void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 42L); - configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request, launchEvidence(request)); - - assertThrows( - IllegalStateException.class, - () -> - service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000005", 43L), - launchEvidence(request))); - assertThrows( - IllegalStateException.class, - () -> - service.startRunOwnedInitialLaunch( - new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L), - launchEvidence( - new StartSessionRequest(1L, 4L, "10000000-0000-4000-8000-000000000005", 42L)))); - - assertEquals(1, store.size()); - assertEquals(10L, store.get(10L).getId()); - verify(worldManagementClient, times(1)) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any()); - } - - @Test - void runOwnedInitialLaunchRequestIdConflictsOnChangedAuthoredWorldSource() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000008", 42L); - configureRunOwnedWorld(request); - service.startRunOwnedInitialLaunch(request, launchEvidence(request)); - - assertThrows( - IllegalStateException.class, - () -> - service.startRunOwnedInitialLaunch( - request, launchEvidence(request, sourceEvidence(request, 30L)))); - assertThrows( - IllegalStateException.class, - () -> - service.startRunOwnedInitialLaunch( - request, - launchEvidence( - request, - sourceEvidence( - request, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c"))))); - - assertEquals(1, store.size()); - verify(worldManagementClient, times(1)) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any()); - } - - @Test - void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerReadSnapshot() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000009", 42L); - configureRunOwnedWorld(request); - var original = launchEvidence(request); - service.startRunOwnedInitialLaunch(request, original); - var changed = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - request, - sourceEvidence(request), - original.publishedReleaseBundle().toBuilder() - .setPublishWorkflowId("publish-11-replayed-with-changed-input") - .build(), - original.versionAssetArtifactState(), - original.versionState()); - - assertThrows( - IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request, changed)); - - assertEquals(1, store.size()); - verify(worldManagementClient, times(1)) - .prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any()); - } - - @Test - void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000006", 42L); - AtomicReference worldState = configureRunOwnedWorld(request); - doAnswer( - invocation -> - GetWorldInstanceLifecycleResponse.newBuilder() - .setWorldInstance( - worldState.get().toBuilder() - .setPublishedReleaseBundleRef("prb:1:11:78") - .build()) - .build()) - .when(worldManagementClient) - .getWorldInstanceLifecycle(anyLong(), anyLong()); - - IllegalStateException error = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + IllegalStateException denied = assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); - - assertEquals( - "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor", - error.getMessage()); - assertEquals(1, store.size()); - assertEquals("STARTING", store.get(10L).getStatus()); - assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); - verify(worldManagementClient, never()) - .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); - } - - @Test - void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { - StartSessionRequest request = - new StartSessionRequest(1L, 3L, "10000000-0000-4000-8000-000000000007", 42L); - AtomicReference worldState = configureRunOwnedWorld(request); - worldState.set( - runOwnedWorldSnapshot( - request, - 10L, - 2L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION)); - - assertThrows( - IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); - assertThrows( - IllegalStateException.class, - () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); - - assertEquals(1, store.size()); - assertEquals( - "10000000-0000-4000-8000-000000000007", store.get(10L).getRunOwnedStartRequestId()); - assertEquals("STARTING", store.get(10L).getStatus()); - verify(worldManagementClient, never()) - .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); + assertTrue(denied.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + assertTrue(store.isEmpty()); + verify(repository, never()).save(any()); + verifyNoInteractions(gameDesignClient, worldManagementClient, stateService); } @Test @@ -1767,16 +1295,13 @@ private void configureLaunchPreflight() { long gameTemplateId = invocation.getArgument(1, Long.class); String controlPlaneRequestId = invocation.getArgument(2, String.class); AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); - LaunchDescriptor descriptor = runOwnedDescriptorOverride; - if (descriptor == null) { - descriptor = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - new StartSessionRequest( - tenantId, gameTemplateId, controlPlaneRequestId, 42L), - sourceEvidence, - runOwnedBundleRef(tenantId)) - .launchDescriptor(); - } + LaunchDescriptor descriptor = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + new StartSessionRequest( + tenantId, gameTemplateId, controlPlaneRequestId, 42L), + sourceEvidence, + runOwnedBundleRef(tenantId)) + .launchDescriptor(); return ResolveLaunchDescriptorResponse.newBuilder() .setLaunchDescriptor(descriptor) .build(); @@ -1913,9 +1438,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence( } private String runOwnedBundleRef(long tenantId) { - return runOwnedBundleRefOverride == null - ? "prb:" + tenantId + ":11:77" - : runOwnedBundleRefOverride; + return "prb:" + tenantId + ":11:77"; } private static UUID sourceOperationId(StartSessionRequest request) { @@ -2314,15 +1837,6 @@ private AtomicReference configureRunOwnedWorld( return worldState; } - private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( - StartSessionRequest request, - long gameInstanceId, - long lifecycleEpoch, - WorldInstanceLifecycleStatus status) { - return runOwnedWorldSnapshot( - request, gameInstanceId, lifecycleEpoch, status, "prb:" + request.tenantId() + ":11:77"); - } - private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( StartSessionRequest request, long gameInstanceId, 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..b5a057fa28 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java @@ -0,0 +1,404 @@ +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.RunOwnedInitialAdmissionFixtureCoordinator; +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("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 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 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); + RunOwnedInitialAdmissionFixtureCoordinator coordinator = + withCoordinator ? mock(RunOwnedInitialAdmissionFixtureCoordinator.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, + RunOwnedInitialAdmissionFixtureCoordinator 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/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java index 37ca38c9d3..cd39f90220 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java @@ -3,9 +3,11 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Arrays; import java.util.HexFormat; import java.util.Objects; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; @@ -21,6 +23,8 @@ public final class RunOwnedWorldLaunchEvidence { private final RunOwnedInitialAdmissionFixtureWireCodec.Capability capability; private final RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt; private final AuthoredWorldLaunchDescriptorEvidence launchDescriptor; + private final CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult + gameSessionAssociation; private final byte[] capabilityBytes; private final byte[] sourceReceiptBytes; private final String gameSessionLeafSha256; @@ -37,7 +41,8 @@ public final class RunOwnedWorldLaunchEvidence { String gameSessionLeafSha256, String worldManagementUriSan, String worldManagementLeafSha256, - String caCertificateSha256) { + String caCertificateSha256, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation) { this.capability = Objects.requireNonNull(capability, "capability"); this.sourceReceipt = Objects.requireNonNull(sourceReceipt, "sourceReceipt"); this.launchDescriptor = Objects.requireNonNull(launchDescriptor, "launchDescriptor"); @@ -51,6 +56,8 @@ public final class RunOwnedWorldLaunchEvidence { this.worldManagementLeafSha256 = Objects.requireNonNull(worldManagementLeafSha256, "worldManagementLeafSha256"); this.caCertificateSha256 = Objects.requireNonNull(caCertificateSha256, "caCertificateSha256"); + this.gameSessionAssociation = + Objects.requireNonNull(gameSessionAssociation, "gameSessionAssociation"); } public RunOwnedInitialAdmissionFixtureWireCodec.Capability capability() { @@ -65,6 +72,20 @@ public AuthoredWorldLaunchDescriptorEvidence launchDescriptor() { return launchDescriptor; } + /** Exact authenticated allocation read from the existing Game Session launch owner. */ + public CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation() { + return gameSessionAssociation; + } + + /** The readback identifies the private Game Session keys; it grants no World write authority. */ + public void requireGameSessionAllocation(long tenantId, long gameInstanceId) { + if (tenantId != gameSessionAssociation.gameSessionTenantId() + || gameInstanceId != gameSessionAssociation.gameInstanceId()) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_GAME_SESSION_ALLOCATION_MISMATCH: request differs from authenticated Game Session owner read"); + } + } + public String gameSessionLeafSha256() { return gameSessionLeafSha256; } @@ -95,7 +116,7 @@ public void requireMatches(PreparedWorldInstanceRequest request) { || version.getVersionState() == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState .VERSION_LIFECYCLE_STATE_ACTIVE; - if (request.tenantId() != capability.tenantId() + if (request.tenantId() <= 0L || request.gameInstanceId() <= 0L || request.gameTemplateId() != capability.gameTemplateId() || !capability.operationId().equals(request.controlPlaneRequestId()) @@ -143,6 +164,53 @@ public void requireMatches(PreparedWorldInstanceRequest request) { throw new IllegalArgumentException( "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: prepared request differs from committed fixture evidence"); } + requireGameSessionAllocation(request.tenantId(), request.gameInstanceId()); + requireExactGameSessionFixtureAssociation(); + } + + private void requireExactGameSessionFixtureAssociation() { + var expectedPolicy = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest( + capability, + sourceReceipt.creationEvidence(), + sourceReceipt.sourceEvidence(), + sourceReceipt.launchReadEvidence()); + byte[] expectedPolicyBytes = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, + sourceReceipt.creationEvidence(), + sourceReceipt.sourceEvidence(), + sourceReceipt.launchReadEvidence()); + if (!gameSessionAssociation + .request() + .fixtureOperationId() + .toString() + .equals(capability.operationId()) + || !gameSessionAssociation + .request() + .targetNamespace() + .equals(sourceReceipt.sourceEvidence().targetNamespace()) + || !gameSessionAssociation + .request() + .expectedFixturePolicyEvidenceDigest() + .equals(sourceReceipt.fixturePolicySeal().evidenceDigest()) + || !gameSessionAssociation.fixturePolicySeal().equals(sourceReceipt.fixturePolicySeal()) + || !Objects.equals(gameSessionAssociation.fixturePolicyRequest(), expectedPolicy) + || !Arrays.equals(gameSessionAssociation.fixturePolicyRequestBytes(), expectedPolicyBytes) + || !gameSessionAssociation + .canonicalTenantId() + .equals(sourceReceipt.sourceEvidence().canonicalTenantId()) + || !gameSessionAssociation + .canonicalVersionId() + .toString() + .equals( + sourceReceipt + .launchReadEvidence() + .publishedReleaseBundle() + .getCanonicalVersionId())) { + throw new IllegalArgumentException( + "RUN_OWNED_WORLD_GAME_SESSION_FIXTURE_ASSOCIATION_MISMATCH: owner read differs from immutable fixture receipt"); + } } /** diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java index f5a29e382e..e6aad20b80 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.data; +import jakarta.annotation.PreDestroy; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -11,15 +12,20 @@ import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.Arrays; import java.util.Collection; import java.util.HexFormat; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; @@ -29,6 +35,7 @@ import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; @@ -37,7 +44,9 @@ * Fixed-server reader and verifier for the run-owned World launch fixture. * *

Request data cannot select paths, principals, or evidence. Every call rereads and revalidates - * the configured immutable files and performs the exact authenticated Game Design owner read. + * the configured immutable files and reads the exact authenticated Game Design and Game Session + * owner projections. The Game Session STARTING association is provenance only; it grants no World + * materialization or activation authority. */ @Component public final class RunOwnedWorldLaunchEvidenceProvider { @@ -58,7 +67,12 @@ public final class RunOwnedWorldLaunchEvidenceProvider { private final String composeProjectName; private final CommonGrpcClientProperties grpcProperties; private final GameDesignClient gameDesignClient; + private final ServiceEndpointsProperties serviceEndpoints; + private final GrpcChannelFactory grpcChannelFactory; + private final String workloadNamespace; + private volatile CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient; + @Autowired public RunOwnedWorldLaunchEvidenceProvider( @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, @@ -66,7 +80,10 @@ public RunOwnedWorldLaunchEvidenceProvider( @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, CommonGrpcClientProperties grpcProperties, - GameDesignClient gameDesignClient) { + GameDesignClient gameDesignClient, + ServiceEndpointsProperties serviceEndpoints, + GrpcChannelFactory grpcChannelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { this.enabled = enabled; this.capabilityPath = capabilityPath; this.sourceReceiptPath = sourceReceiptPath; @@ -74,6 +91,9 @@ public RunOwnedWorldLaunchEvidenceProvider( this.composeProjectName = composeProjectName; this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.serviceEndpoints = serviceEndpoints == null ? null : serviceEndpoints.copy(); + this.grpcChannelFactory = grpcChannelFactory; + this.workloadNamespace = workloadNamespace; } /** Whether the server selected the run-owned fixture mode at startup. */ @@ -82,8 +102,9 @@ public boolean isEnabled() { } /** - * Independently loads all fixed evidence and verifies the actual authenticated request context. - * This is invoked on every prepare, activate, and exact retry. + * Independently loads the fixed evidence and verifies both authenticated owner readbacks. + * Returned Game Session STARTING state is source evidence only and does not authorize World + * writes or activation. */ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { VerificationStage stage = VerificationStage.ENABLED; @@ -149,6 +170,19 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { throw invalidEvidence(); } + stage = VerificationStage.GAME_SESSION_FIXTURE_READ; + var fixtureReadRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + freshFixtureReadRequestId(UUID.fromString(capability.operationId())), + receipt.sourceEvidence().targetNamespace(), + UUID.fromString(capability.operationId()), + receipt.fixturePolicySeal().evidenceDigest()); + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation = + gameSessionFixtureClient() + .readFixture(fixtureReadRequest, capability.gameSessionLeafSha256()); + stage = VerificationStage.GAME_SESSION_FIXTURE_COMPARE; + requireFixtureReadback(capability, receipt, gameSessionAssociation); + return new RunOwnedWorldLaunchEvidence( capability, receipt, @@ -158,7 +192,8 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { capability.gameSessionLeafSha256(), worldPins.uriSan(), worldPins.leafSha256(), - worldPins.caSha256()); + worldPins.caSha256(), + gameSessionAssociation); } catch (RuntimeException exception) { if (exception instanceof InvalidRunOwnedWorldLaunchEvidenceException invalid) { throw invalid; @@ -171,6 +206,86 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { } } + private static void requireFixtureReadback( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult actual) { + var expectedPolicy = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest( + capability, + receipt.creationEvidence(), + receipt.sourceEvidence(), + receipt.launchReadEvidence()); + byte[] expectedBytes = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, + receipt.creationEvidence(), + receipt.sourceEvidence(), + receipt.launchReadEvidence()); + if (!actual.request().fixtureOperationId().toString().equals(capability.operationId()) + || !actual.request().targetNamespace().equals(receipt.sourceEvidence().targetNamespace()) + || !actual + .request() + .expectedFixturePolicyEvidenceDigest() + .equals(receipt.fixturePolicySeal().evidenceDigest()) + || !actual.fixturePolicySeal().equals(receipt.fixturePolicySeal()) + || !Objects.equals(actual.fixturePolicyRequest(), expectedPolicy) + || !Arrays.equals(actual.fixturePolicyRequestBytes(), expectedBytes) + || !actual.canonicalTenantId().equals(receipt.sourceEvidence().canonicalTenantId()) + || !actual + .canonicalVersionId() + .toString() + .equals( + receipt.launchReadEvidence().publishedReleaseBundle().getCanonicalVersionId())) { + throw invalidEvidence(); + } + } + + private static UUID freshFixtureReadRequestId(UUID fixtureOperationId) { + UUID readRequestId; + do { + readRequestId = UUID.randomUUID(); + } while (readRequestId.equals(fixtureOperationId)); + return readRequestId; + } + + private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient() { + if (gameSessionFixtureClient != null) { + return gameSessionFixtureClient; + } + if (serviceEndpoints == null || grpcChannelFactory == null || workloadNamespace == null) { + throw invalidEvidence(); + } + CanonicalGameInstanceLaunchAssociationClient created = + new CanonicalGameInstanceLaunchAssociationClient( + serviceEndpoints, grpcProperties, grpcChannelFactory, workloadNamespace); + try { + created.init(); + gameSessionFixtureClient = created; + return created; + } catch (IOException | RuntimeException failure) { + try { + created.close(); + } catch (IOException ignored) { + // Keep the fixed content-free rejection; certificate paths never enter logs. + } + throw invalidEvidence(); + } + } + + @PreDestroy + public synchronized void closeGameSessionFixtureClient() { + CanonicalGameInstanceLaunchAssociationClient current = gameSessionFixtureClient; + gameSessionFixtureClient = null; + if (current != null) { + try { + current.close(); + } catch (IOException failure) { + logger.warn("Run-owned World Game Session owner client did not close cleanly"); + } + } + } + private static AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest( RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt) { @@ -343,7 +458,9 @@ private enum VerificationStage { GAME_SESSION_PEER, DESCRIPTOR_PARSE, OWNER_DESCRIPTOR_READ, - OWNER_DESCRIPTOR_COMPARE + OWNER_DESCRIPTOR_COMPARE, + GAME_SESSION_FIXTURE_READ, + GAME_SESSION_FIXTURE_COMPARE } /** Content-free failure so malformed or secret-bearing fixture bytes never reach logs. */ diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java index 3a6c802b90..e5716cac91 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; import net.firedevops.firemud.worldmanagement.repository.RoomRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -42,9 +43,16 @@ public class TestDataSeeder implements ApplicationRunner { private final RoomRepository roomRepository; private final RoomExitRepository roomExitRepository; + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") + private boolean runOwnedFixtureMode; + @Override @Transactional public void run(ApplicationArguments args) { + if (runOwnedFixtureMode) { + throw new IllegalStateException( + "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture runtime seeding is disabled until World-owned materialization is available"); + } ensureDemoTopology(); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index 34d4f6ec2d..b7072231c8 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -14,7 +14,6 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; @@ -227,41 +226,17 @@ void initMetrics() { @Timed(value = "world.prepareInstance") public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( PreparedWorldInstanceRequest request) { - validatePrepareRequest(request); - RunOwnedWorldLaunchEvidence fixtureEvidence = configuredFixtureEvidence(); - if (fixtureEvidence != null) { - fixtureEvidence.requireMatches(request); - worldInstanceRepository.lockRunOwnedFixtureOperation( - request.tenantId(), request.controlPlaneRequestId()); - WorldInstance operationInstance = - worldInstanceRepository - .findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( - request.tenantId(), request.controlPlaneRequestId()) - .orElse(null); - if (operationInstance != null - && !operationInstance.getGameInstanceId().equals(request.gameInstanceId())) { - throw fixtureIdentityConflict(); - } + if (fixtureModeEnabled()) { + throw fixtureWritesUnavailable(); } + validatePrepareRequest(request); WorldInstance existing = - fixtureEvidence == null - ? worldInstanceRepository - .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) - .orElse(null) - : worldInstanceRepository - .findByTenantIdAndGameInstanceIdForUpdate( - request.tenantId(), request.gameInstanceId()) - .orElse(null); + worldInstanceRepository + .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) + .orElse(null); if (existing != null) { if (existing.getRunOwnedFixtureBindingSha256() != null) { - if (fixtureEvidence == null) { - throw fixtureEvidenceUnavailable(); - } - requireRunOwnedFixtureBinding(existing, fixtureEvidence, request); - return snapshot(existing); - } - if (fixtureEvidence != null) { - throw fixtureIdentityConflict(); + throw fixtureEvidenceUnavailable(); } if (!samePreparedRequest(existing, request)) { throw new IllegalArgumentException( @@ -269,9 +244,7 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( } return snapshot(existing); } - if (fixtureEvidence == null) { - validateAttestedLaunchInputs(request); - } + validateAttestedLaunchInputs(request); WorldInstance worldInstance = new WorldInstance(); worldInstance.setTenantId(request.tenantId()); worldInstance.setGameInstanceId(request.gameInstanceId()); @@ -289,10 +262,6 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( worldInstance.setRemapSetId(normalizeBlank(request.remapSetId())); worldInstance.setLifecycleEpoch(1L); worldInstance.setStatus(STATUS_PREPARING); - if (fixtureEvidence != null) { - worldInstance.setRunOwnedFixtureBindingSha256(fixtureEvidence.bindingDigest(request, 1L)); - worldInstance.setRunOwnedFixturePreparingLifecycleEpoch(1L); - } worldInstance.setCreatedAt(Instant.now()); worldInstance.setUpdatedAt(Instant.now()); WorldInstance saved = worldInstanceRepository.save(worldInstance); @@ -326,42 +295,22 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( @Timed(value = "world.activateInstance") public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { + if (fixtureModeEnabled()) { + throw fixtureWritesUnavailable(); + } WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { - if (!fixtureModeEnabled()) { - throw fixtureEvidenceUnavailable(); - } - RunOwnedWorldLaunchEvidence fixtureEvidence = - runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); - worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); - PreparedWorldInstanceRequest preparedRequest = preparedRequest(worldInstance); - requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, preparedRequest); - if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { - long preparingEpoch = worldInstance.getRunOwnedFixturePreparingLifecycleEpoch(); - if (worldInstance.getLifecycleEpoch() != preparingEpoch + 1L - || (expectedLifecycleEpoch != preparingEpoch - && expectedLifecycleEpoch != worldInstance.getLifecycleEpoch())) { - throw lifecycleEpochMismatch(); - } - return snapshot(worldInstance); - } - requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); - } else { - if (fixtureModeEnabled()) { - throw fixtureIdentityConflict(); - } - requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); - if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { - return snapshot(worldInstance); - } + throw fixtureEvidenceUnavailable(); + } + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + return snapshot(worldInstance); } if (!STATUS_PREPARING.equals(worldInstance.getStatus())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance is not in PREPARING state"); } - if (worldInstance.getRunOwnedFixtureBindingSha256() == null) { - validateAttestedLaunchInputs(preparedRequest(worldInstance)); - } + validateAttestedLaunchInputs(preparedRequest(worldInstance)); worldInstance.setStatus(STATUS_ACTIVE); worldInstance.setLifecycleEpoch(worldInstance.getLifecycleEpoch() + 1L); worldInstance.setFailureReason(null); @@ -392,30 +341,6 @@ private PreparedWorldInstanceRequest preparedRequest(WorldInstance worldInstance worldInstance.getRemapSetId()); } - private void requireRunOwnedFixtureBinding( - WorldInstance instance, - RunOwnedWorldLaunchEvidence fixtureEvidence, - PreparedWorldInstanceRequest request) { - Long preparingEpoch = instance.getRunOwnedFixturePreparingLifecycleEpoch(); - if (instance.getRunOwnedFixtureBindingSha256() == null - || preparingEpoch == null - || preparingEpoch <= 0L - || preparingEpoch != 1L - || !samePreparedRequest(instance, request) - || !instance - .getRunOwnedFixtureBindingSha256() - .equals(fixtureEvidence.bindingDigest(request, preparingEpoch))) { - throw fixtureEvidenceMismatch(); - } - } - - private RunOwnedWorldLaunchEvidence configuredFixtureEvidence() { - if (!fixtureModeEnabled()) { - return null; - } - return runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); - } - private boolean fixtureModeEnabled() { return runOwnedWorldLaunchEvidenceProvider != null && runOwnedWorldLaunchEvidenceProvider.isEnabled(); @@ -426,19 +351,9 @@ private static IllegalArgumentException fixtureEvidenceUnavailable() { "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: fixture-bound lifecycle requires verified run evidence"); } - private static IllegalArgumentException fixtureEvidenceMismatch() { - return new IllegalArgumentException( - "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: stored fixture binding or prepared identity changed"); - } - - private static IllegalArgumentException fixtureIdentityConflict() { - return new IllegalArgumentException( - "RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT: fixture operation is bound to another instance"); - } - - private static IllegalArgumentException lifecycleEpochMismatch() { + private static IllegalArgumentException fixtureWritesUnavailable() { return new IllegalArgumentException( - "WORLD_INSTANCE_LIFECYCLE_STALE: world instance lifecycle epoch mismatch"); + "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture prepare and activation are disabled until World-owned materialization is available"); } @Override 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..a101b0159a 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 @@ -2,10 +2,6 @@ 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.anyLong; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import io.grpc.Server; @@ -44,6 +40,8 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; 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.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -55,8 +53,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; @@ -66,44 +67,29 @@ 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.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest; +import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; -import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; -import net.firedevops.firemud.worldmanagement.entity.WorldInstance; -import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomRepository; -import net.firedevops.firemud.worldmanagement.repository.WorldEventRepository; -import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; -import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; -import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; -import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; -import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; -import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; +import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleRequest; +import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.SimpleTransactionStatus; import tools.jackson.databind.json.JsonMapper; -/** Socket-level proof of authenticated GS to World and World to exact GDS descriptor transport. */ +/** Socket-level proof of authenticated World launch provenance reads from GS and GDS owners. */ 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 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"; - private static final String WRONG_GS_URI = "spiffe://firemud/ns/other/sa/game-session-service"; private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; private static final String STORE_PASSWORD = "test-only-world-mtls-password"; private static final String TEST_JWT_SECRET = "testsecretkeytestsecretkeytest1234"; @@ -122,8 +108,10 @@ class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { private static TestPki pki; private Server worldServer; + private Server gameSessionOwnerServer; private Server gameDesignServer; private GameDesignClient gameDesignClient; + private RunOwnedWorldLaunchEvidenceProvider evidenceProvider; private ManagedChannel gameSessionChannel; @BeforeAll @@ -134,6 +122,10 @@ static void createCertificates() throws Exception { @AfterEach void stopTransport() throws Exception { SessionContext.clear(); + if (evidenceProvider != null) { + evidenceProvider.closeGameSessionFixtureClient(); + evidenceProvider = null; + } if (gameSessionChannel != null) { gameSessionChannel.shutdownNow(); assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); @@ -153,27 +145,46 @@ void stopTransport() throws Exception { assertThat(gameDesignServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); gameDesignServer = null; } + if (gameSessionOwnerServer != null) { + gameSessionOwnerServer.shutdownNow(); + assertThat(gameSessionOwnerServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionOwnerServer = null; + } } @Test - void physicalMtlsPrepareActivateAndOriginalEpochReplayReverifyReceiptAndOwnerDescriptor() - throws Exception { + void physicalMtlsReadsExactStartingFixtureProvenanceWithoutWorldWrites() throws Exception { Fixture fixture = Fixture.create(temporaryDirectory, pki); AtomicInteger descriptorReads = new AtomicInteger(); - AtomicReference worldAtOwner = new AtomicReference<>(); - AtomicReference worldCertificateAtOwner = new AtomicReference<>(); - AtomicReference requestAtOwner = new AtomicReference<>(); + AtomicInteger fixtureReads = new AtomicInteger(); + AtomicReference worldAtGameDesign = new AtomicReference<>(); + AtomicReference worldCertificateAtGameDesign = + new AtomicReference<>(); + AtomicReference descriptorRequestAtOwner = new AtomicReference<>(); + AtomicReference worldAtGameSession = new AtomicReference<>(); + AtomicReference worldCertificateAtGameSession = + new AtomicReference<>(); + AtomicReference + fixtureRequestAtOwner = new AtomicReference<>(); AtomicBoolean returnChangedDescriptor = new AtomicBoolean(); startGameDesignServer( fixture, descriptorReads, - worldAtOwner, - worldCertificateAtOwner, - requestAtOwner, + worldAtGameDesign, + worldCertificateAtGameDesign, + descriptorRequestAtOwner, returnChangedDescriptor); + startGameSessionOwnerServer( + fixture, + fixtureReads, + worldAtGameSession, + worldCertificateAtGameSession, + fixtureRequestAtOwner); + CommonGrpcClientProperties worldTls = pki.worldClientProperties(); ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); + endpoints.setGameSessionService("localhost:" + gameSessionOwnerServer.getPort()); gameDesignClient = new GameDesignClient( endpoints, @@ -189,22 +200,13 @@ public > T customize(T stub) { System.setProperty("firemud.grpc.tls-reload.enabled", "false"); try { ReflectionTestUtils.invokeMethod(gameDesignClient, "init"); - RunOwnedWorldLaunchEvidenceProvider evidenceProvider = fixture.provider(gameDesignClient); - AtomicReference storedWorld = new AtomicReference<>(); - AtomicInteger worldSaves = new AtomicInteger(); - WorldInstanceRepository worldRepository = mockWorldRepository(storedWorld, worldSaves); - WorldLifecycleCommandServiceImpl commandService = - newCommandService(worldRepository, evidenceProvider, gameDesignClient); - WorldInstanceActivationServiceImpl activationService = - new WorldInstanceActivationServiceImpl( - commandService, java.util.Optional.empty(), evidenceProvider, worldRepository); - AtomicReference gameSessionAtWorld = new AtomicReference<>(); - AtomicBoolean injectPlayerContext = new AtomicBoolean(); - WorldManagementGrpcService grpcService = + evidenceProvider = fixture.provider(gameDesignClient, endpoints); + AtomicReference readEvidence = new AtomicReference<>(); + WorldManagementGrpcService readOnlyHandler = new WorldManagementGrpcService( null, null, - activationService, + null, null, null, null, @@ -213,382 +215,114 @@ public > T customize(T stub) { JsonMapper.builder().build(), "dev") { @Override - public void prepareWorldInstance( - PrepareWorldInstanceRequest request, - StreamObserver< - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse> - responseObserver) { - gameSessionAtWorld.set(GrpcPeerIdentity.current()); - super.prepareWorldInstance(request, responseObserver); - } - - @Override - public void activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest request, - StreamObserver< - net.firedevops.firemud.worldmanagement.v1 - .ActivatePreparedWorldInstanceResponse> - responseObserver) { - gameSessionAtWorld.set(GrpcPeerIdentity.current()); - if (injectPlayerContext.get()) { - SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); - } + public void getWorldInstanceLifecycle( + GetWorldInstanceLifecycleRequest request, + StreamObserver responseObserver) { try { - super.activatePreparedWorldInstance(request, responseObserver); - } finally { - SessionContext.clear(); + readEvidence.set(evidenceProvider.requireAuthenticatedEvidence()); + responseObserver.onNext( + GetWorldInstanceLifecycleResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("TEST_READ_PROVENANCE_ONLY") + .setMessage( + "Controlled handler captured provenance without World reads or writes")) + .build()); + } catch (RuntimeException rejected) { + responseObserver.onNext( + GetWorldInstanceLifecycleResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_INVALID") + .setMessage("Controlled fixture provenance read was rejected")) + .build()); } + responseObserver.onCompleted(); } }; - worldServer = startWorldServer(grpcService); + worldServer = startWorldServer(readOnlyHandler); gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); - WorldManagementServiceGrpc.WorldManagementServiceBlockingStub gameSession = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel); - - var prepare = - gameSession.prepareWorldInstance( - PrepareWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setGameTemplateId("17") - .setControlPlaneRequestId(OPERATION_ID) - .setLaunchDescriptorId("launch-descriptor-fixture-11") - .setVersionId("11") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setReleaseBundleId("77") - .setPublishedReleaseBundleRef(RELEASE_REF) - .setVersionStateEpoch(77L) - .build()); - assertThat(prepare.hasError()).isFalse(); - assertThat(prepare.getWorldInstance().getStatus()) - .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); - assertThat(storedWorld.get().getRunOwnedFixtureBindingSha256()).matches("[0-9a-f]{64}"); - assertThat(storedWorld.get().getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - int writesAfterPrepare = worldSaves.get(); - var wrongReference = - gameSession.prepareWorldInstance( - PrepareWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setGameTemplateId("17") - .setControlPlaneRequestId(OPERATION_ID) - .setLaunchDescriptorId("launch-descriptor-fixture-11") - .setVersionId("11") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setReleaseBundleId("77") - .setPublishedReleaseBundleRef("11111111-1111-4111-8111-111111111111") - .setVersionStateEpoch(77L) - .build()); - assertThat(wrongReference.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterPrepare); - assertThat(descriptorReads).hasValue(2); - - var activated = - gameSession.activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(activated.hasError()).isFalse(); - assertThat(activated.getWorldInstance().getStatus()) - .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); - assertThat(activated.getWorldInstance().getLifecycleEpoch()).isEqualTo(2L); - int writesAfterActivation = worldSaves.get(); + var response = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .getWorldInstanceLifecycle( + GetWorldInstanceLifecycleRequest.newBuilder() + .setTenantId("142") + .setGameInstanceId("1001") + .build()); - var replay = - gameSession.activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(replay.hasError()).isFalse(); - assertThat(replay.getWorldInstance()).isEqualTo(activated.getWorldInstance()); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - assertThat(worldAtOwner.get()) + assertThat(response.hasError()).isTrue(); + assertThat(response.getError().getCode()).isEqualTo("TEST_READ_PROVENANCE_ONLY"); + assertThat(readEvidence.get()).isNotNull(); + assertThat(readEvidence.get().gameSessionAssociation().gameSessionTenantId()).isEqualTo(142L); + assertThat(readEvidence.get().gameSessionAssociation().gameInstanceId()).isEqualTo(1001L); + assertThat(readEvidence.get().gameSessionAssociation().currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING); + assertThat(readEvidence.get().gameSessionAssociation().fixturePolicySeal()) + .isEqualTo(fixture.policySeal); + assertThat(readEvidence.get().gameSessionAssociation().fixturePolicyRequestBytes()) + .isEqualTo( + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + fixture.capability, + fixture.creationEvidence, + fixture.source, + fixture.launchReadEvidence)); + assertThat(readEvidence.get().gameSessionAssociation().canonicalTenantId()) + .isEqualTo(fixture.source.canonicalTenantId()); + assertThat(readEvidence.get().gameSessionAssociation().canonicalVersionId().toString()) + .isEqualTo(fixture.bundle.getCanonicalVersionId()); + assertThat(fixtureReads).hasValue(1); + assertThat(descriptorReads).hasValue(1); + assertThat(fixtureRequestAtOwner.get()).isNotNull(); + assertThat(fixtureRequestAtOwner.get().fixtureOperationId().toString()) + .isEqualTo(fixture.operationId); + assertThat(fixtureRequestAtOwner.get().expectedFixturePolicyEvidenceDigest()) + .isEqualTo(fixture.policySeal.evidenceDigest()); + assertThat(worldAtGameSession.get()) .isNotNull() .extracting(GrpcPeerIdentity::uri) .isEqualTo(WORLD_URI); - assertThat(worldAtOwner.get().isService("world-management-service")).isTrue(); - assertThat(worldAtOwner.get().isInNamespace("dev")).isTrue(); - assertThat(worldCertificateAtOwner.get()) + assertThat(worldAtGameSession.get().isInNamespace("dev")).isTrue(); + assertThat(worldCertificateAtGameSession.get()) .isNotNull() .extracting(GrpcPeerCertificateEvidence::leafSha256) .isEqualTo(fingerprint(pki.worldManagement().certificate())); - assertThat(requestAtOwner.get()).isNotNull(); - assertThat(requestAtOwner.get().getRequestId()).isNotBlank(); - assertThat(requestAtOwner.get().getCanonicalTenantId()) - .isEqualTo(fixture.descriptorEvidence().request().canonicalTenantId().toString()); - assertThat(requestAtOwner.get().getWorldSlug()) - .isEqualTo(fixture.descriptorEvidence().worldSlug()); - assertThat(requestAtOwner.get().getControlPlaneRequestId()).isEqualTo(OPERATION_ID); - assertThat(requestAtOwner.get().getExpectedRequestDigest()) - .isEqualTo(fixture.descriptorEvidence().requestDigest()); - assertThat(requestAtOwner.get().getExpectedResultDigest()) - .isEqualTo(fixture.descriptorEvidence().resultDigest()); - assertThat(gameSessionAtWorld.get()) + assertThat(worldAtGameDesign.get()) .isNotNull() .extracting(GrpcPeerIdentity::uri) - .isEqualTo(GS_URI); - - injectPlayerContext.set(true); - var ordinaryCaller = - gameSession.activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - injectPlayerContext.set(false); - assertThat(ordinaryCaller.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - gameSessionChannel.shutdownNow(); - assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); - assertThatThrownBy( - () -> - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build())) - .isInstanceOf(StatusRuntimeException.class); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - gameSessionChannel.shutdownNow(); - assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - gameSessionChannel = - channel("localhost", worldServer.getPort(), pki.wrongNamespaceGameSessionClient()); - var wrongPeer = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(wrongPeer.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - gameSessionChannel.shutdownNow(); - assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - gameSessionChannel = - channel("localhost", worldServer.getPort(), pki.wrongGameSessionLeafClient()); - var wrongLeaf = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(wrongLeaf.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - gameSessionChannel.shutdownNow(); - assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - gameSessionChannel = - channel("localhost", worldServer.getPort(), pki.wrongCaGameSessionClient()); - assertThatThrownBy( - () -> - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build())) - .isInstanceOf(StatusRuntimeException.class); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - gameSessionChannel.shutdownNow(); - assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); - fixture.reset(); - Fixture.writeFieldMismatch(fixture, "caCertificateSha256", "f".repeat(64)); - var wrongCa = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(wrongCa.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - fixture.reset(); - Fixture.writeFieldMismatch(fixture, "worldManagementLeafSha256", "e".repeat(64)); - var wrongWorldRecipient = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(wrongWorldRecipient.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - fixture.reset(); - Fixture.writeFieldMismatch( - fixture, "worldManagementUriSan", "spiffe://firemud/ns/dev/sa/other-world-service"); - var wrongWorldUri = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(wrongWorldUri.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - fixture.reset(); - var unknownInstance = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("202") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(unknownInstance.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(4); - - var duplicateOperation = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .prepareWorldInstance( - PrepareWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("202") - .setGameTemplateId("17") - .setControlPlaneRequestId(OPERATION_ID) - .setLaunchDescriptorId("launch-descriptor-fixture-11") - .setVersionId("11") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setReleaseBundleId("77") - .setPublishedReleaseBundleRef(RELEASE_REF) - .setVersionStateEpoch(77L) - .build()); - assertThat(duplicateOperation.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(5); - - var staleAttempt = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(99L) - .build()); - assertThat(staleAttempt.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(6); - - fixture.reset(); - Fixture.writeReceiptFieldMismatch(fixture, "sourceGameTenantKey", "43"); - var changedSource = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(changedSource.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(6); - - fixture.reset(); - Fixture.writeFieldMismatch(fixture, "runId", "changed-run"); - var changedRun = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(changedRun.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(6); - - fixture.reset(); - Fixture.writeFieldMismatch(fixture, "composeProjectName", "different-project"); - var changedProject = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(changedProject.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(6); - - fixture.reset(); - Fixture.writeReceiptFieldMismatch( - fixture, "fixtureOperationId", "11111111-1111-4111-8111-111111111111"); - var changedReceipt = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(changedReceipt.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(6); - - fixture.reset(); - Fixture.writeReceiptFieldMismatch(fixture, "launchDescriptorBase64", "AAAA"); - var changedReceiptDescriptor = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build()); - assertThat(changedReceiptDescriptor.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(6); + .isEqualTo(WORLD_URI); + assertThat(worldCertificateAtGameDesign.get()) + .isNotNull() + .extracting(GrpcPeerCertificateEvidence::leafSha256) + .isEqualTo(fingerprint(pki.worldManagement().certificate())); + assertThat(descriptorRequestAtOwner.get()).isNotNull(); + assertThat(descriptorRequestAtOwner.get().getControlPlaneRequestId()) + .isEqualTo(fixture.operationId); + assertThat(descriptorRequestAtOwner.get().getExpectedRequestDigest()) + .isEqualTo(fixture.descriptorEvidence.requestDigest()); + assertThat(descriptorRequestAtOwner.get().getExpectedResultDigest()) + .isEqualTo(fixture.descriptorEvidence.resultDigest()); + assertThat(Files.readAllBytes(fixture.capabilityPath)) + .isEqualTo(fixture.originalCapabilityBytes); + assertThat(Files.readAllBytes(fixture.receiptPath)).isEqualTo(fixture.originalReceiptBytes); - fixture.reset(); returnChangedDescriptor.set(true); - var changedOwnerDescriptor = + var rejected = WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) + .getWorldInstanceLifecycle( + GetWorldInstanceLifecycleRequest.newBuilder() + .setTenantId("142") + .setGameInstanceId("1001") .build()); - returnChangedDescriptor.set(false); - assertThat(changedOwnerDescriptor.hasError()).isTrue(); - assertThat(worldSaves).hasValue(writesAfterActivation); - assertThat(descriptorReads).hasValue(7); + assertThat(rejected.hasError()).isTrue(); + assertThat(rejected.getError().getCode()) + .isEqualTo("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_INVALID"); + assertThat(descriptorReads).hasValue(2); + assertThat(fixtureReads).hasValue(1); + assertThat(Files.readAllBytes(fixture.capabilityPath)) + .isEqualTo(fixture.originalCapabilityBytes); + assertThat(Files.readAllBytes(fixture.receiptPath)).isEqualTo(fixture.originalReceiptBytes); } finally { if (previousReload == null) { System.clearProperty("firemud.grpc.tls-reload.enabled"); @@ -667,9 +401,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() @@ -717,6 +451,74 @@ public void getLaunchDescriptor( .start(); } + private void startGameSessionOwnerServer( + Fixture fixture, + AtomicInteger fixtureReads, + AtomicReference worldAtOwner, + AtomicReference worldCertificateAtOwner, + AtomicReference + requestAtOwner) + throws Exception { + String expectedWorldFingerprint = fingerprint(pki.worldManagement().certificate()); + var service = + new GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase() { + @Override + public void getRunOwnedFixtureLaunchAssociation( + GetRunOwnedFixtureLaunchAssociationRequest request, + StreamObserver responseObserver) { + fixtureReads.incrementAndGet(); + worldAtOwner.set(GrpcPeerIdentity.current()); + worldCertificateAtOwner.set(GrpcPeerCertificateEvidence.current()); + try { + var selector = + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request); + requestAtOwner.set(selector); + if (worldAtOwner.get() == null + || !WORLD_URI.equals(worldAtOwner.get().uri()) + || !worldAtOwner.get().isService("world-management-service") + || !worldAtOwner.get().isInNamespace("dev") + || worldCertificateAtOwner.get() == null + || !expectedWorldFingerprint.equals(worldCertificateAtOwner.get().leafSha256()) + || !"dev".equals(selector.targetNamespace()) + || !fixture.operationId.equals(selector.fixtureOperationId().toString()) + || !fixture + .policySeal + .evidenceDigest() + .equals(selector.expectedFixturePolicyEvidenceDigest())) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription( + "World peer or exact fixture launch selector did not match") + .asRuntimeException()); + return; + } + responseObserver.onNext( + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse( + fixture.fixtureAssociation(selector))); + responseObserver.onCompleted(); + } catch (RuntimeException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture owner read selector was invalid") + .asRuntimeException()); + } + } + }; + gameSessionOwnerServer = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.gameSessionClient().privateKey(), + pki.gameSessionClient().certificate())) + .trustManager(pki.caCertificateValue()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + private Server startWorldServer(WorldManagementGrpcService service) throws Exception { return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( @@ -743,192 +545,145 @@ private ManagedChannel channel(String host, int port, TestIdentity identity) thr .build(); } - private ManagedChannel channelWithoutClientIdentity(String host, int port) throws Exception { - return NettyChannelBuilder.forAddress(host, port) - .overrideAuthority("localhost") - .sslContext( - GrpcSslContexts.configure( - SslContextBuilder.forClient().trustManager(pki.caCertificateValue())) - .build()) - .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; } } - private RunOwnedWorldLaunchEvidenceProvider provider(Path directory, GameDesignClient client) { - CommonGrpcClientProperties tls = pki.worldClientProperties(); - return new RunOwnedWorldLaunchEvidenceProvider( - true, - directory.resolve("capability.json").toString(), - directory.resolve("source-receipt.json").toString(), - RUN_ID, - PROJECT, - tls, - client); - } - - private WorldInstanceRepository mockWorldRepository( - AtomicReference storedWorld, AtomicInteger worldSaves) { - WorldInstanceRepository repository = mock(WorldInstanceRepository.class); - when(repository.findByTenantIdAndGameInstanceId(anyLong(), anyLong())) - .thenAnswer( - invocation -> { - WorldInstance instance = storedWorld.get(); - return instance != null - && instance.getTenantId().equals(invocation.getArgument(0)) - && instance.getGameInstanceId().equals(invocation.getArgument(1)) - ? java.util.Optional.of(instance) - : java.util.Optional.empty(); - }); - when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) - .thenAnswer( - invocation -> { - WorldInstance instance = storedWorld.get(); - return instance != null - && instance.getTenantId().equals(invocation.getArgument(0)) - && instance.getGameInstanceId().equals(invocation.getArgument(1)) - ? java.util.Optional.of(instance) - : java.util.Optional.empty(); - }); - when(repository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( - anyLong(), any(String.class))) - .thenAnswer( - invocation -> { - WorldInstance instance = storedWorld.get(); - return instance != null - && instance.getTenantId().equals(invocation.getArgument(0)) - && instance.getControlPlaneRequestId().equals(invocation.getArgument(1)) - ? java.util.Optional.of(instance) - : java.util.Optional.empty(); - }); - when(repository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance instance = invocation.getArgument(0); - if (instance.getId() == null) { - instance.setId(101L); - } - worldSaves.incrementAndGet(); - storedWorld.set(instance); - return instance; - }); - return repository; - } - - private WorldLifecycleCommandServiceImpl newCommandService( - WorldInstanceRepository worldRepository, - RunOwnedWorldLaunchEvidenceProvider evidenceProvider, - GameDesignClient client) { - RegionInstanceRepository regionRepository = mock(RegionInstanceRepository.class); - ZoneRepository zoneRepository = mock(ZoneRepository.class); - ZoneInstanceRepository zoneInstanceRepository = mock(ZoneInstanceRepository.class); - RoomRepository roomRepository = mock(RoomRepository.class); - RoomExitRepository roomExitRepository = mock(RoomExitRepository.class); - RoomInstanceRepository roomInstanceRepository = mock(RoomInstanceRepository.class); - RoomInstanceExitRepository roomInstanceExitRepository = mock(RoomInstanceExitRepository.class); - when(regionRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); - when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) - .thenReturn(List.of()); - when(zoneInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); - when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) - .thenReturn(List.of()); - when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) - .thenReturn(List.of()); - when(roomInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); - when(roomInstanceExitRepository.save(any())) - .thenAnswer(invocation -> invocation.getArgument(0)); - WorldProperties properties = new WorldProperties(); - properties.setLocalShardId(7); - WorldLifecycleCommandServiceImpl commandService = - new WorldLifecycleCommandServiceImpl( - worldRepository, - regionRepository, - zoneRepository, - zoneInstanceRepository, - roomRepository, - roomExitRepository, - roomInstanceRepository, - roomInstanceExitRepository, - mock(WorldEventRepository.class), - properties, - client, - mock(EntityManagementClient.class), - new SimpleMeterRegistry(), - new PlatformTransactionManager() { - @Override - public SimpleTransactionStatus getTransaction(TransactionDefinition definition) { - return new SimpleTransactionStatus(); - } - - @Override - public void commit(TransactionStatus status) {} - - @Override - public void rollback(TransactionStatus status) {} - }, - evidenceProvider); - commandService.initMetrics(); - return commandService; - } - private static final class Fixture { private final TestPki pki; private final Path directory; private final Path capabilityPath; private final Path receiptPath; - private final String originalCapabilityJson; - private final String originalReceiptJson; - private String capabilityJson; - private String receiptJson; + private final String operationId; + private final String claimDigest; + private final byte[] originalCapabilityBytes; + private final byte[] originalReceiptBytes; private final AuthoredWorldSourceEvidence source; private final PublishedReleaseBundle bundle; private final VersionAssetArtifactState artifact; private final VersionStateSnapshot version; private final LaunchDescriptor launchDescriptor; private final AuthoredWorldLaunchDescriptorEvidence descriptorEvidence; + private final FreshTenantCreationEvidence creationEvidence; + private final RunOwnedInitialAdmissionFixtureWireCodec.Capability capability; + private final RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt; + private final RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence launchReadEvidence; + private final RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal policySeal; 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(); + claimDigest = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest((RUN_ID + "\n" + PROJECT + "\n").getBytes(StandardCharsets.UTF_8))); + operationId = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + claimDigest, + RUN_ID, + PROJECT, + fingerprint(pki.gameSessionClient().certificate()), + fingerprint(pki.caCertificateValue())) + .toString(); + source = sourceEvidence(operationId); bundle = publishedBundle(source); artifact = artifactState(); version = versionState(); descriptorEvidence = RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.descriptorEvidence( - source, bundle, version); + source, bundle, version, operationId); launchDescriptor = AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); - capabilityJson = capabilityJson(pki); - receiptJson = receiptJson(source, bundle, artifact, version, launchDescriptor, pki); - originalCapabilityJson = capabilityJson; - originalReceiptJson = receiptJson; - writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); - writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); + creationEvidence = creationEvidence(source); + launchReadEvidence = + new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( + RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, + 17L, + bundle, + artifact, + version, + launchDescriptor); + String policyRequestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + RunOwnedInitialAdmissionFixtureWireCodec.parseCapability( + capabilityJson(pki, operationId, claimDigest).getBytes(StandardCharsets.UTF_8)), + creationEvidence, + source, + launchReadEvidence); + policySeal = + new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, + UUID.fromString(operationId), + policyRequestDigest, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + UUID.fromString(operationId), policyRequestDigest)); + String capabilityJson = capabilityJson(pki, operationId, claimDigest); + String receiptJson = + receiptJson( + source, + bundle, + artifact, + version, + launchDescriptor, + creationEvidence, + policySeal, + operationId, + pki); + originalCapabilityBytes = capabilityJson.getBytes(StandardCharsets.UTF_8); + originalReceiptBytes = receiptJson.getBytes(StandardCharsets.UTF_8); + writeReadonly(capabilityPath, originalCapabilityBytes); + writeReadonly(receiptPath, originalReceiptBytes); + capability = + RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(originalCapabilityBytes); + sourceReceipt = + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( + originalReceiptBytes, capability); } static Fixture create(Path parent, TestPki pki) throws Exception { return new Fixture(parent, pki); } - RunOwnedWorldLaunchEvidenceProvider provider(GameDesignClient client) { - CommonGrpcClientProperties tls = pki.worldClientProperties(); + RunOwnedWorldLaunchEvidenceProvider provider( + GameDesignClient client, ServiceEndpointsProperties endpoints) { return new RunOwnedWorldLaunchEvidenceProvider( true, - directory.resolve("capability.json").toString(), - directory.resolve("source-receipt.json").toString(), + capabilityPath.toString(), + receiptPath.toString(), RUN_ID, PROJECT, - tls, - client); + pki.worldClientProperties(), + client, + endpoints, + new GrpcChannelFactory(), + "dev"); + } + + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult fixtureAssociation( + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request) { + return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + request, + 142L, + 1001L, + source.canonicalTenantId(), + UUID.fromString("20000000-0000-4000-8000-000000000011"), + UUID.fromString(bundle.getCanonicalVersionId()), + UUID.fromString("30000000-0000-4000-8000-000000000011"), + UUID.fromString("40000000-0000-4000-8000-000000000011"), + 1L, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, + 0L, + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, creationEvidence, source, launchReadEvidence), + policySeal); } LaunchDescriptor launchDescriptor() { @@ -938,47 +693,12 @@ LaunchDescriptor launchDescriptor() { AuthoredWorldLaunchDescriptorEvidence descriptorEvidence() { return descriptorEvidence; } - - void reset() throws IOException { - capabilityJson = originalCapabilityJson; - receiptJson = originalReceiptJson; - writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); - writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); - } - - static void writeFieldMismatch(Fixture fixture, String fieldName, String replacement) - throws IOException { - fixture.capabilityJson = replaceField(fixture.capabilityJson, fieldName, replacement); - fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); - writeReadonly( - fixture.capabilityPath, fixture.capabilityJson.getBytes(StandardCharsets.UTF_8)); - writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); - } - - static void writeReceiptFieldMismatch(Fixture fixture, String fieldName, String replacement) - throws IOException { - fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); - writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); - } - - private static String replaceField(String json, String fieldName, String replacement) { - String marker = "\"" + fieldName + "\":\""; - int start = json.indexOf(marker); - if (start < 0) { - throw new IllegalStateException("Fixture field was not present: " + fieldName); - } - int valueStart = start + marker.length(); - int end = json.indexOf('"', valueStart); - if (end < 0) { - throw new IllegalStateException("Fixture field value was not terminated: " + fieldName); - } - return json.substring(0, valueStart) + replacement + json.substring(end); - } } - 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"); + UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); String requestDigest = AuthoredWorldSourceDigest.requestDigest( "dev", registrationId, tenant, "fixture-tenant", "demo", "Demo World"); @@ -986,7 +706,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { 1, "dev", registrationId, - UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), + sourceOperationId, requestDigest, tenant, "fixture-tenant", @@ -998,7 +718,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { AuthoredWorldSourceDigest.evidenceDigest( "dev", registrationId, - UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), + sourceOperationId, requestDigest, tenant, "fixture-tenant", @@ -1009,6 +729,33 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { "NEW_GAME_ROW")); } + private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); + UUID creationOperationId = UUID.fromString("31e36104-3336-4cf5-899a-cb419f2f361e"); + String requestDigest = + GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, "42", "Fixture Game", null); + return new FreshTenantCreationEvidence( + 1, + "dev", + creationRequestId, + creationOperationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + "dev", + creationRequestId, + creationOperationId, + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + } + private static PublishedReleaseBundle publishedBundle(AuthoredWorldSourceEvidence source) { return PublishedReleaseBundle.newBuilder() .setId(77L) @@ -1060,10 +807,10 @@ private static VersionStateSnapshot versionState() { } private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( - AuthoredWorldSourceEvidence source) { + AuthoredWorldSourceEvidence source, String operationId) { return new AuthoredWorldLaunchDescriptorEvidence.Request( "dev", - OPERATION_ID, + operationId, source.canonicalTenantId(), source.worldSlug(), source.operationId(), @@ -1082,9 +829,10 @@ private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( AuthoredWorldSourceEvidence source, PublishedReleaseBundle bundle, - VersionStateSnapshot version) { + VersionStateSnapshot version, + String operationId) { return AuthoredWorldLaunchDescriptorEvidence.create( - expectedRequest(source), + expectedRequest(source, operationId), "launch-descriptor-fixture-11", bundle.getVersionId(), false, @@ -1098,19 +846,21 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( null); } - private static String capabilityJson(TestPki pki) throws Exception { + private static String capabilityJson(TestPki pki, String operationId, String claimDigest) + throws Exception { 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":"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","claimDigest":"%s"}\ """ .formatted( RUN_ID, PROJECT, - OPERATION_ID, + operationId, fingerprint(pki.gameSessionClient().certificate()), GS_URI, fingerprint(pki.caCertificateValue()), WORLD_URI, - fingerprint(pki.worldManagement().certificate())); + fingerprint(pki.worldManagement().certificate()), + claimDigest); } private static String receiptJson( @@ -1119,15 +869,18 @@ private static String receiptJson( VersionAssetArtifactState artifact, VersionStateSnapshot version, LaunchDescriptor descriptor, + FreshTenantCreationEvidence creation, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal seal, + String operationId, 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, + operationId, GS_URI, fingerprint(pki.gameSessionClient().certificate()), fingerprint(pki.caCertificateValue()), @@ -1147,7 +900,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(), + seal.schema(), + seal.ownerService(), + seal.operationId(), + seal.requestDigest(), + seal.evidenceDigest()); } private static String encode(byte[] bytes) { @@ -1160,14 +928,6 @@ private static String fingerprint(X509Certificate certificate) throws Exception } private static void writeReadonly(Path path, byte[] value) throws IOException { - if (Files.exists(path)) { - Files.setPosixFilePermissions( - path, - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.OWNER_WRITE, - PosixFilePermission.GROUP_READ)); - } Files.write(path, value); Files.setPosixFilePermissions( path, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); @@ -1184,10 +944,7 @@ private record TestPki( Path caCertificatePath, TestIdentity worldManagement, TestIdentity gameDesignServer, - TestIdentity gameSessionClient, - TestIdentity wrongNamespaceGameSessionClient, - TestIdentity wrongGameSessionLeafClient, - TestIdentity wrongCaGameSessionClient) { + TestIdentity gameSessionClient) { static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("world-mtls-ca.p12"); runKeytool( @@ -1233,56 +990,13 @@ static TestPki create(Path directory) throws Exception { caCertificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); } - Path wrongCaStore = directory.resolve("world-mtls-untrusted-ca.p12"); - runKeytool( - "-genkeypair", - "-alias", - "test-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=Untrusted World mTLS test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - wrongCaStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path wrongCa = directory.resolve("world-mtls-untrusted-ca.crt"); - runKeytool( - "-exportcert", - "-alias", - "test-ca", - "-keystore", - wrongCaStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - wrongCa.toString(), - "-rfc"); return new TestPki( caCertificate, ca, issueIdentity( directory, caStore, ca, "world-management", WORLD_URI, "serverAuth,clientAuth"), issueIdentity(directory, caStore, ca, "game-design", GDS_URI, "serverAuth"), - issueIdentity(directory, caStore, ca, "game-session", GS_URI, "clientAuth"), - issueIdentity(directory, caStore, ca, "wrong-game-session", WRONG_GS_URI, "clientAuth"), - issueIdentity(directory, caStore, ca, "wrong-game-session-leaf", GS_URI, "clientAuth"), - issueIdentity( - directory, wrongCaStore, wrongCa, "wrong-ca-game-session", GS_URI, "clientAuth")); + issueIdentity(directory, caStore, ca, "game-session", GS_URI, "serverAuth,clientAuth")); } CommonGrpcClientProperties worldClientProperties() { 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..2efe463ca7 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 @@ -2,15 +2,17 @@ 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.anyLong; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -27,7 +29,6 @@ import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; -import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.entity.WorldInstance; import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -41,6 +42,7 @@ import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; import org.jooq.DSLContext; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; @@ -49,6 +51,7 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; @@ -57,7 +60,8 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * Real PostgreSQL proof for fixture binding durability, uniqueness, lock serialization, and CAS. + * PostgreSQL proof of fixture lifecycle denial before effects and passive binding storage. + * Controlled storage rows do not establish World materialization or activation authority. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -84,7 +88,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AutowireCapableBeanFactory beanFactory; - @Autowired private WorldInstanceRepository repository; + @MockitoSpyBean private WorldInstanceRepository repository; @Autowired private WorldLifecycleCommandService lifecycleService; @Autowired private PlatformTransactionManager transactionManager; @@ -97,93 +101,80 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; @Test - void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurableBinding() { + void fixturePrepareAndActivationRetryAndRestartDenyBeforeReadsOrPostgresEffects() { long tenantId = 8_810_001L; long gameInstanceId = uniqueId(); PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - String binding = "a".repeat(64); - configureEvidence(binding); + // This pre-existing controlled storage row supplies no canonical association or authority. + repository.save(passiveStorageRow(request, "a".repeat(64))); + when(fixtureProvider.isEnabled()).thenReturn(true); + clearInvocations( + repository, + fixtureEvidence, + gameDesignClient, + gameSessionClient, + entityManagementClient, + bindProofClient); + Map> before = postgresState(); try { - var prepared = lifecycleService.prepareWorldInstance(request); - WorldInstance stored = - repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); - assertThat(prepared.status()).isEqualTo("PREPARING"); - assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); - assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); - assertThat(stored.getPublishedReleaseBundleRef()).isEqualTo(RELEASE_REF); - assertThat(stored.getRowVersion()).isZero(); - - var active = lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); - assertThat(active.status()).isEqualTo("ACTIVE"); - assertThat(active.lifecycleEpoch()).isEqualTo(2L); - WorldInstance activeRow = - repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); - assertThat(activeRow.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); - assertThat(activeRow.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - long activeRowVersion = activeRow.getRowVersion(); + assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixtureDenied( + () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); + assertFixtureDenied( + () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); + assertFixtureDenied( + () -> + lifecycleService.prepareWorldInstance( + request(tenantId, uniqueId(), request.controlPlaneRequestId()))); RunOwnedWorldLaunchEvidenceProvider restartedProvider = mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence restartedEvidence = mock(RunOwnedWorldLaunchEvidence.class); when(restartedProvider.isEnabled()).thenReturn(true); - when(restartedProvider.requireAuthenticatedEvidence()).thenReturn(restartedEvidence); - when(restartedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn(binding); - WorldInstanceRepository restartedRepository = new WorldInstanceRepository(dsl); + WorldInstanceRepository restartedRepository = spy(new WorldInstanceRepository(dsl)); WorldLifecycleCommandServiceImpl restartedService = restartedLifecycleService(restartedRepository, restartedProvider); + assertFixtureDenied(() -> restartedService.prepareWorldInstance(request)); + assertFixtureDenied( + () -> restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); + assertThat(postgresState()).isEqualTo(before); + verifyNoInteractions(repository, restartedRepository); + org.mockito.Mockito.verify(restartedProvider, org.mockito.Mockito.never()) + .requireAuthenticatedEvidence(); + verifyNoUpstreamReads(); + } finally { + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); + } + } - var replay = restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); - assertThat(replay).isEqualTo(active); - verify(restartedProvider).requireAuthenticatedEvidence(); + @Test + void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCas() { + clearInvocations(fixtureProvider, fixtureEvidence); + long tenantId = 8_810_004L; + long gameInstanceId = uniqueId(); + PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); + try { + WorldInstance stored = repository.save(passiveStorageRow(request, "a".repeat(64))); + assertThat(stored.getStatus()).isEqualTo("PREPARING"); + assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo("a".repeat(64)); + assertThat(stored.getPublishedReleaseBundleRef()).isEqualTo(RELEASE_REF); + assertThat(stored.getRowVersion()).isZero(); + WorldInstanceRepository restartedRepository = new WorldInstanceRepository(dsl); assertThat( - repository + restartedRepository .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow() - .getRowVersion()) - .isEqualTo(activeRowVersion); - var prepareReplay = restartedService.prepareWorldInstance(request); - assertThat(prepareReplay).isEqualTo(active); + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); assertThat( - repository - .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow() - .getRowVersion()) - .isEqualTo(activeRowVersion); - verify(restartedProvider, org.mockito.Mockito.times(2)).requireAuthenticatedEvidence(); - - RunOwnedWorldLaunchEvidenceProvider changedProvider = - mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence changedEvidence = mock(RunOwnedWorldLaunchEvidence.class); - when(changedProvider.isEnabled()).thenReturn(true); - when(changedProvider.requireAuthenticatedEvidence()).thenReturn(changedEvidence); - when(changedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn("b".repeat(64)); - assertThatThrownBy( - () -> - restartedLifecycleService(new WorldInstanceRepository(dsl), changedProvider) - .activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); - assertThat( - repository - .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow() - .getRowVersion()) - .isEqualTo(activeRowVersion); - - PreparedWorldInstanceRequest duplicateOperation = - request(tenantId, uniqueId(), request.controlPlaneRequestId()); - when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn(binding); - assertThatThrownBy(() -> lifecycleService.prepareWorldInstance(duplicateOperation)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:"); - verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); - verify(fixtureProvider, org.mockito.Mockito.atLeast(3)).requireAuthenticatedEvidence(); + restartedRepository + .findRunOwnedFixtureByTenantIdAndControlPlaneRequestId( + tenantId, request.controlPlaneRequestId()) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); assertThatThrownBy( () -> @@ -210,6 +201,13 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable gameInstanceId)) .isInstanceOf(RuntimeException.class); + assertThat( + restartedRepository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(stored); + WorldInstance staleCopy = repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); WorldInstance winningCopy = @@ -224,27 +222,19 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); assertThat(durableWinner.getFailureReason()).isEqualTo("CAS winner"); assertThat(durableWinner.getRowVersion()).isEqualTo(savedWinningCopy.getRowVersion()); - - WorldInstance duplicate = new WorldInstance(); - duplicate.setTenantId(tenantId); - duplicate.setGameInstanceId(uniqueId()); - duplicate.setGameTemplateId(17L); - duplicate.setControlPlaneRequestId(request.controlPlaneRequestId()); - duplicate.setLaunchDescriptorId("launch-descriptor-fixture-11"); - duplicate.setVersionId(11L); - duplicate.setRuntimeFlagsJson("{}"); - duplicate.setGenerationConfigRevision("genrev-11"); - duplicate.setReleaseBundleId(77L); - duplicate.setPublishedReleaseBundleRef(RELEASE_REF); - duplicate.setVersionStateEpoch(77L); - duplicate.setLifecycleEpoch(1L); - duplicate.setStatus("PREPARING"); - duplicate.setCreatedAt(Instant.now()); - duplicate.setUpdatedAt(Instant.now()); - duplicate.setRowVersion(0L); - duplicate.setRunOwnedFixtureBindingSha256("c".repeat(64)); - duplicate.setRunOwnedFixturePreparingLifecycleEpoch(1L); + assertThat(durableWinner.getRunOwnedFixtureBindingSha256()).isEqualTo("a".repeat(64)); + assertThat(durableWinner.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + WorldInstance duplicate = + passiveStorageRow( + request(tenantId, uniqueId(), request.controlPlaneRequestId()), "c".repeat(64)); assertThatThrownBy(() -> repository.save(duplicate)).isInstanceOf(RuntimeException.class); + assertThat( + restartedRepository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow()) + .usingRecursiveComparison() + .isEqualTo(durableWinner); + verifyNoInteractions(fixtureProvider, fixtureEvidence); } finally { dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); } @@ -288,51 +278,126 @@ void operationAdvisoryLockSerializesConcurrentRetriesOnPostgres() throws Excepti } @Test - void concurrentPrepareRetriesCreateOneFixtureBoundWorldInstance() throws Exception { + void concurrentFixturePrepareAndActivationRetriesDenyWithoutPostgresOrUpstreamEffects() + throws Exception { long tenantId = 8_810_003L; long gameInstanceId = uniqueId(); PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - configureEvidence("d".repeat(64)); + when(fixtureProvider.isEnabled()).thenReturn(true); + clearInvocations( + repository, + fixtureEvidence, + gameDesignClient, + gameSessionClient, + entityManagementClient, + bindProofClient); + Map> before = postgresState(); CountDownLatch ready = new CountDownLatch(2); CountDownLatch start = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { - Future first = + Future first = executor.submit( () -> { ready.countDown(); await(start); - return lifecycleService.prepareWorldInstance(request); + assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixtureDenied( + () -> + lifecycleService.activatePreparedWorldInstance( + tenantId, gameInstanceId, 1L)); }); - Future second = + Future second = executor.submit( () -> { ready.countDown(); await(start); - return lifecycleService.prepareWorldInstance(request); + assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); + assertFixtureDenied( + () -> + lifecycleService.activatePreparedWorldInstance( + tenantId, gameInstanceId, 1L)); }); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); - - var firstResult = first.get(20, TimeUnit.SECONDS); - var secondResult = second.get(20, TimeUnit.SECONDS); - assertThat(firstResult).isEqualTo(secondResult); - assertThat(firstResult.status()).isEqualTo("PREPARING"); - WorldInstance stored = - repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); - assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo("d".repeat(64)); - assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - verify(fixtureProvider, org.mockito.Mockito.atLeast(2)).requireAuthenticatedEvidence(); + first.get(20, TimeUnit.SECONDS); + second.get(20, TimeUnit.SECONDS); + assertThat(postgresState()).isEqualTo(before); + verifyNoInteractions(repository); + verifyNoUpstreamReads(); } finally { start.countDown(); - dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); } } - private void configureEvidence(String binding) { - when(fixtureProvider.isEnabled()).thenReturn(true); - when(fixtureProvider.requireAuthenticatedEvidence()).thenReturn(fixtureEvidence); - when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn(binding); + private static void assertFixtureDenied( + org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { + assertThatThrownBy(call) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:"); + } + + private void verifyNoUpstreamReads() { + org.mockito.Mockito.verify(fixtureProvider, org.mockito.Mockito.never()) + .requireAuthenticatedEvidence(); + verifyNoInteractions( + fixtureEvidence, + gameDesignClient, + gameSessionClient, + entityManagementClient, + bindProofClient); + } + + private Map> postgresState() { + String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + assertThat(schema).isEqualTo("world_management_service"); + List tables = + dsl.fetch("SELECT tablename FROM pg_tables WHERE schemaname = ? ORDER BY tablename", schema) + .getValues(0, String.class); + assertThat(tables).isNotEmpty().contains("world_instance"); + Map> state = new LinkedHashMap<>(); + for (String table : tables) { + // Entire rows and xmin retain source/resource bytes as well as lifecycle/CAS state. + state.put( + table, + dsl.fetch( + "SELECT to_jsonb(retained)::text || ':xmin=' || retained.xmin::text FROM " + + DSL.name(schema, table) + + " retained ORDER BY 1") + .getValues(0, String.class)); + } + List sequences = + dsl.fetch( + "SELECT to_jsonb(retained)::text FROM (SELECT sequencename, last_value " + + "FROM pg_sequences WHERE schemaname = ? ORDER BY sequencename) retained", + schema) + .getValues(0, String.class); + assertThat(sequences).isNotEmpty(); + state.put("sequences", sequences); + return state; + } + + private static WorldInstance passiveStorageRow( + PreparedWorldInstanceRequest request, String binding) { + WorldInstance row = new WorldInstance(); + row.setTenantId(request.tenantId()); + row.setGameInstanceId(request.gameInstanceId()); + row.setGameTemplateId(request.gameTemplateId()); + row.setControlPlaneRequestId(request.controlPlaneRequestId()); + row.setLaunchDescriptorId(request.launchDescriptorId()); + row.setVersionId(request.versionId()); + row.setRuntimeFlagsJson(request.runtimeFlagsJson()); + row.setGenerationConfigRevision(request.generationConfigRevision()); + row.setReleaseBundleId(request.releaseBundleId()); + row.setPublishedReleaseBundleRef(request.publishedReleaseBundleRef()); + row.setVersionStateEpoch(request.versionStateEpoch()); + row.setLifecycleEpoch(1L); + row.setStatus("PREPARING"); + row.setCreatedAt(Instant.now()); + row.setUpdatedAt(Instant.now()); + row.setRowVersion(0L); + row.setRunOwnedFixtureBindingSha256(binding); + row.setRunOwnedFixturePreparingLifecycleEpoch(1L); + return row; } private WorldLifecycleCommandServiceImpl restartedLifecycleService( 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..38328a1538 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 @@ -9,13 +9,19 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.util.Set; import java.util.UUID; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; 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.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState; @@ -31,11 +37,27 @@ @ExtendWith(OutputCaptureExtension.class) class RunOwnedWorldLaunchEvidenceProviderTest { - private static final String OPERATION_ID = "7f1e5306-e9a7-46d9-b5cf-75348e20ffbd"; + private static final String CLAIM_DIGEST = controlledClaimDigest(); + 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; + private static String controlledClaimDigest() { + try { + // Exact controlled fixture bytes; this is not a physical run claim. + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest("fixture-run\nfiremud-fixture-run\n".getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } + @Test void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); @@ -45,11 +67,29 @@ void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { assertThat(evidence.bindingDigest(request(" ", " "), 1L)).isEqualTo(absent); } + @Test + void launchEvidenceBindsStartingAllocationPrivateKeysFromOwnerProjection() { + RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); + + evidence.requireMatches(request(null, null)); + assertThat(evidence.gameSessionAssociation().gameSessionTenantId()).isEqualTo(142L); + assertThat(evidence.gameSessionAssociation().gameInstanceId()).isEqualTo(1001L); + assertThat(evidence.gameSessionAssociation().currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING); + assertThat(evidence.capability().tenantId()).isEqualTo(42L); + assertThat(evidence.gameSessionAssociation().gameSessionTenantId()) + .isNotEqualTo(evidence.capability().tenantId()); + assertThatThrownBy(() -> evidence.requireGameSessionAllocation(42L, 1001L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_ALLOCATION_MISMATCH:"); + } + @Test void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign(CapturedOutput output) { GameDesignClient gameDesignClient = mock(GameDesignClient.class); RunOwnedWorldLaunchEvidenceProvider provider = - new RunOwnedWorldLaunchEvidenceProvider( + provider( false, temporaryDirectory.resolve("missing-capability.json").toString(), temporaryDirectory.resolve("missing-receipt.json").toString(), @@ -81,7 +121,7 @@ void malformedWireLogsOnlyTheFixedVerificationStageAndPreservesWireError(Capture Files.setPosixFilePermissions( receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); RunOwnedWorldLaunchEvidenceProvider provider = - new RunOwnedWorldLaunchEvidenceProvider( + provider( true, capability.toString(), receipt.toString(), @@ -124,7 +164,7 @@ void enabledFixtureRejectsRelativeCapabilityPathAtFileReadStage(CapturedOutput o String relativeCapabilityPath = workingDirectory.relativize(capability.toAbsolutePath().normalize()).toString(); RunOwnedWorldLaunchEvidenceProvider provider = - new RunOwnedWorldLaunchEvidenceProvider( + provider( true, relativeCapabilityPath, receipt.toString(), @@ -151,7 +191,7 @@ void enabledFixtureRejectsWritableCapabilityAtFileReadStage(CapturedOutput outpu Files.setPosixFilePermissions( receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); RunOwnedWorldLaunchEvidenceProvider provider = - new RunOwnedWorldLaunchEvidenceProvider( + provider( true, capability.toString(), receipt.toString(), @@ -182,7 +222,7 @@ void enabledFixtureRejectsCapabilitySymlinkAtFileReadStage(CapturedOutput output receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); Files.createSymbolicLink(capability, target.getFileName()); RunOwnedWorldLaunchEvidenceProvider provider = - new RunOwnedWorldLaunchEvidenceProvider( + provider( true, capability.toString(), receipt.toString(), @@ -206,8 +246,8 @@ private static void assertFileRejectionStoppedBeforeWireParse(CapturedOutput out private static PreparedWorldInstanceRequest request(String patch, String remap) { return new PreparedWorldInstanceRequest( - 42L, - 101L, + 142L, + 1001L, 17L, OPERATION_ID, "launch-descriptor-fixture-11", @@ -292,21 +332,30 @@ 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) .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) .setVersionStateEpoch(77L) + .setUpdatedAt("2026-10-11T10:00:00Z") .build(); RunOwnedInitialAdmissionFixtureWireCodec.Capability capability = new RunOwnedInitialAdmissionFixtureWireCodec.Capability( @@ -330,7 +379,54 @@ 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); + // Controlled constructor data remains untrusted; these commitments do not prove owner writes. + UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); + UUID creationOperationId = UUID.fromString("31e36104-3336-4cf5-899a-cb419f2f361e"); + String creationRequestDigest = + GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, "42", "Fixture Game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + "dev", + creationRequestId, + creationOperationId, + creationRequestDigest, + canonicalTenantId, + 29L, + "42", + "NEW_GAME_ROW", + 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 policySeal = + 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 +440,31 @@ 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, + policySeal); + var policyRequestBytes = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability, creation, source, launchRead); + UUID readRequestId = UUID.fromString("5d85bfbe-ae28-4a86-a72a-57471a5761bf"); + var associationRequest = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( + readRequestId, "dev", UUID.fromString(OPERATION_ID), policySeal.evidenceDigest()); + var association = + new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + associationRequest, + 142L, + 1001L, + canonicalTenantId, + UUID.fromString("20000000-0000-4000-8000-000000000011"), + UUID.fromString(bundle.getCanonicalVersionId()), + UUID.fromString("30000000-0000-4000-8000-000000000011"), + UUID.fromString("40000000-0000-4000-8000-000000000011"), + 1L, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, + 0L, + policyRequestBytes, + policySeal); return new RunOwnedWorldLaunchEvidence( capability, receipt, @@ -361,6 +474,28 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { "a".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, "c".repeat(64), - "b".repeat(64)); + "b".repeat(64), + association); + } + + private static RunOwnedWorldLaunchEvidenceProvider provider( + boolean enabled, + String capabilityPath, + String receiptPath, + String runId, + String composeProjectName, + CommonGrpcClientProperties grpcProperties, + GameDesignClient gameDesignClient) { + return new RunOwnedWorldLaunchEvidenceProvider( + enabled, + capabilityPath, + receiptPath, + runId, + composeProjectName, + grpcProperties, + gameDesignClient, + null, + null, + "dev"); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java index c7b61de93d..2bc0a3aa69 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.List; @@ -25,6 +26,7 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.test.util.ReflectionTestUtils; class TestDataSeederTest { @Mock RegionRepository regionRepository; @@ -107,6 +109,19 @@ void runSeedsCanonicalTopologyWhenMissing() throws Exception { assertEquals(1021L, exitCaptor.getAllValues().get(1).getToRoom().getId()); } + @Test + void fixtureModeRefusesBeforeAnyRepositoryReadOrWrite() { + ReflectionTestUtils.setField(seeder, "runOwnedFixtureMode", true); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + verifyNoInteractions(regionRepository, zoneRepository, roomRepository, roomExitRepository); + } + @Test void runReassertsCanonicalTopologyWhenRowsAlreadyExist() throws Exception { Region existingRegion = new Region(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 9f66c370a0..99182918b5 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -9,7 +9,6 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -32,10 +31,8 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; -import net.firedevops.firemud.worldmanagement.entity.RegionInstance; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; import net.firedevops.firemud.worldmanagement.entity.RoomInstance; @@ -752,241 +749,52 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { } @Test - void fixturePrepareBindsOriginalPreparingEpochAndExactRetryDoesNotRepeatMaterialization() { + void fixturePrepareRefusesBeforeProviderEvidenceOrRepositoryInteraction() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); - when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); - when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn("a".repeat(64)); - AtomicReference persisted = new AtomicReference<>(); - when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( - 42L, "cp-1")) - .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); - when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); - when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance submitted = invocation.getArgument(0); - submitted.setId(101L); - persisted.set(copyWorldInstance(submitted)); - return submitted; - }); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); - PreparedWorldInstanceRequest request = ordinaryPreparedRequest(); - - var prepared = fixtureService.prepareWorldInstance(request); - - assertEquals("PREPARING", prepared.status()); - assertEquals(1L, prepared.lifecycleEpoch()); - assertEquals("a".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); - assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); - verify(evidence).requireMatches(request); - verify(worldInstanceRepository).lockRunOwnedFixtureOperation(42L, "cp-1"); - verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); - verify(gameDesignClient, never()).getVersionAssetArtifactState(42L, 11L); - verify(gameDesignClient, never()).getVersionState(42L, 11L); - - var retry = fixtureService.prepareWorldInstance(request); - - assertEquals(prepared, retry); - persisted.get().setStatus("ACTIVE"); - persisted.get().setLifecycleEpoch(2L); - - var activeReplay = fixtureService.prepareWorldInstance(request); - - assertEquals("ACTIVE", activeReplay.status()); - assertEquals(2L, activeReplay.lifecycleEpoch()); - assertEquals("a".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); - assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); - verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); - verify(regionInstanceRepository, org.mockito.Mockito.times(1)).save(any(RegionInstance.class)); - verify(roomInstanceRepository, org.mockito.Mockito.times(1)).save(any(RoomInstance.class)); - verify(evidence, org.mockito.Mockito.times(3)).requireMatches(request); - } - - @Test - void fixturePrepareRejectsChangedBindingForExistingActiveRow() { - RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); - when(provider.isEnabled()).thenReturn(true); - when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); - when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn("d".repeat(64)); - WorldInstance active = boundFixtureInstance("ACTIVE", 2L); - when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( - 42L, "cp-1")) - .thenReturn(Optional.of(active)); - when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenReturn(Optional.of(active)); IllegalArgumentException error = assertThrows( IllegalArgumentException.class, - () -> fixtureService(provider).prepareWorldInstance(ordinaryPreparedRequest())); + () -> fixtureService.prepareWorldInstance(ordinaryPreparedRequest())); - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:")); - verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + verify(provider).isEnabled(); + verify(provider, never()).requireAuthenticatedEvidence(); + verifyNoWorldRepositoryOrOwnerInteraction(); } @Test - void fixtureOperationCannotBeAssignedToASecondWorldInstance() { + void fixtureActivationRefusesBeforeWorldReadOrProviderEvidence() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); - when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); - when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn("b".repeat(64)); - WorldInstance operationInstance = new WorldInstance(); - operationInstance.setGameInstanceId(101L); - when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( - 42L, "cp-1")) - .thenReturn(Optional.of(operationInstance)); - - IllegalArgumentException error = - assertThrows( - IllegalArgumentException.class, - () -> - fixtureService(provider) - .prepareWorldInstance( - new PreparedWorldInstanceRequest( - 42L, - 202L, - 7L, - "cp-1", - "ld-1", - 11L, - null, - "{}", - "genrev-11", - 77L, - PUBLISHED_RELEASE_BUNDLE_REF, - 77L))); - - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:")); - verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); - verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); - } - - @Test - void fixtureActivationVerifiesBindingThenAllowsOnlyOriginalEpochActiveReplayWithoutWrite() { - RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); - when(provider.isEnabled()).thenReturn(true); - when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); - when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn("c".repeat(64)); - WorldInstance preparing = boundFixtureInstance("PREPARING", 1L); - AtomicReference persisted = new AtomicReference<>(copyWorldInstance(preparing)); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) - .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); - when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); - when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance submitted = invocation.getArgument(0); - submitted.setRowVersion(submitted.getRowVersion() + 1L); - persisted.set(copyWorldInstance(submitted)); - return copyWorldInstance(submitted); - }); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); - var active = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); - assertEquals("ACTIVE", active.status()); - assertEquals(2L, active.lifecycleEpoch()); - assertEquals("c".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); - - var replay = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); - assertEquals(active, replay); - verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); - verify(provider, org.mockito.Mockito.times(2)).requireAuthenticatedEvidence(); - verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); - - var inOrder = inOrder(provider, worldInstanceRepository); - inOrder.verify(provider).requireAuthenticatedEvidence(); - inOrder.verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); - inOrder.verify(provider).requireAuthenticatedEvidence(); - inOrder.verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); - } - - @Test - void configuredFixtureRejectsUnboundExistingRowsAndStaleActiveReplayEpoch() { - RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); - when(provider.isEnabled()).thenReturn(true); - when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); - when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn("c".repeat(64)); - WorldInstance unbound = activeWorldInstance(); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) - .thenReturn(Optional.of(unbound)); - when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenReturn(Optional.of(unbound)); - - IllegalArgumentException unboundError = + IllegalArgumentException error = assertThrows( IllegalArgumentException.class, - () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 2L)); - assertTrue(unboundError.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:")); - verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + () -> fixtureService.activatePreparedWorldInstance(42L, 101L, 1L)); - WorldInstance active = boundFixtureInstance("ACTIVE", 2L); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) - .thenReturn(Optional.of(active)); - when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenReturn(Optional.of(active)); - IllegalArgumentException stale = - assertThrows( - IllegalArgumentException.class, - () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 0L)); - assertTrue(stale.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); - verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + verify(provider).isEnabled(); + verify(provider, never()).requireAuthenticatedEvidence(); + verifyNoWorldRepositoryOrOwnerInteraction(); } - @Test - void fixtureActivationRejectsOriginalEpochForNonActiveRowsWithoutWrites() { - RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); - RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); - when(provider.isEnabled()).thenReturn(true); - when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); - when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) - .thenReturn("c".repeat(64)); - WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); - AtomicReference currentRow = new AtomicReference<>(); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) - .thenAnswer(invocation -> Optional.of(currentRow.get())); - when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenAnswer(invocation -> Optional.of(currentRow.get())); - - String[] statuses = {"FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"}; - long[] lifecycleEpochs = {2L, 3L, 4L}; - for (int index = 0; index < statuses.length; index++) { - WorldInstance row = boundFixtureInstance(statuses[index], lifecycleEpochs[index]); - currentRow.set(row); - - IllegalArgumentException stale = - assertThrows( - IllegalArgumentException.class, - () -> fixtureService.activatePreparedWorldInstance(42L, 101L, 1L)); - - assertTrue(stale.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); - assertEquals(statuses[index], row.getStatus()); - assertEquals(lifecycleEpochs[index], row.getLifecycleEpoch()); - } - - verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); - verify(regionInstanceRepository, never()).save(any()); - verify(zoneInstanceRepository, never()).save(any()); - verify(roomInstanceRepository, never()).save(any()); - verify(roomInstanceExitRepository, never()).save(any()); - verify(worldEventRepository, never()).save(any()); - verify(regionInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); - verify(zoneInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); - verify(roomInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); - verify(roomInstanceExitRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); - verify(worldEventRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + private void verifyNoWorldRepositoryOrOwnerInteraction() { + org.mockito.Mockito.verifyNoInteractions( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + gameDesignClient, + entityManagementClient); } private WorldLifecycleCommandServiceImpl fixtureService( @@ -1030,15 +838,6 @@ private static PreparedWorldInstanceRequest ordinaryPreparedRequest() { 77L); } - private WorldInstance boundFixtureInstance(String status, long lifecycleEpoch) { - WorldInstance instance = activeWorldInstance(); - instance.setLifecycleEpoch(lifecycleEpoch); - instance.setStatus(status); - instance.setRunOwnedFixtureBindingSha256("c".repeat(64)); - instance.setRunOwnedFixturePreparingLifecycleEpoch(1L); - return instance; - } - private WorldInstance activeWorldInstance() { WorldInstance instance = new WorldInstance(); instance.setId(101L); From 3e3cd7902cf238cb2756682502f8f45833e37df7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:24:10 +1300 Subject: [PATCH 02/26] Record qualified launch-owner proof and remaining runtime gaps --- .../world-management-service/runtime-and-data.md | 4 ++-- .../game-session-runtime-and-tick-coordination.md | 2 +- .../implementation-tracking/world-runtime-and-movement.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) 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 e065701359..bfdf4abc9d 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 forward-only migrations are `V23.1` and `V24`–`V27.2`; they 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). An unpublished guarded graph/capture candidate includes the ordinary schema-3 digest writer; its exact checkpoint producer and focused proof are incomplete and are recorded in the tracker. 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 forward-only migrations are `V23.1` and `V24`–`V27.2`; they 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 graph/capture owner includes the ordinary schema-3 digest writer and bounded storage/retention proof; its authenticated complete-checkpoint producer and packaged runtime remain incomplete, as recorded in the tracker. 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 current run-owned fixture independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation. World fixture bootstrap and prepare/activate refuse before repository effects pending actual World source/Version materialization, association, fixed-preset preparation and holds. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [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/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 2414e2f3a6..9f0d66c0c6 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 @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick The successor to the guarded World owner stage prepares the closed Game Design fixture-policy receipt and actual Game Session fresh association, catalog and canonical `STARTING` launch. The scheduler completes only that independently read owner phase. Its authenticated fixed World read echoes the original policy request/seal and owner-allocated private identities; it neither writes an admission pointer nor reports an active World. -The obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the same existing default-off fixture configuration. World materialization, holds, first `OPEN`, packaged producer-to-consumer execution and all four genuine handoffs remain open. Current-stage formatting, affected whole service checks and physical PostgreSQL proof are pending; earlier full-carrier unit/native results do not qualify these authored postimages. The canonical receipt and phase ordering remain in [Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence). +The obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the same existing default-off fixture configuration. World materialization, holds, first `OPEN`, packaged producer-to-consumer execution and all four genuine handoffs remain open. The selected owner stage freshly passed 2,202 Game Session unit cases with zero skips and retained the prior 39 cross-service cases. Its latest whole-service check remained failed: 260 fresh integration results included nine failures, comprising one remaining 120-character snapshot validator and eight database/initialization failures; container-disposal caller evidence does not settle the initiating database failure. The snapshot guard now matches the installed V34.3 128-character column. After the exact #3203 parent carry, the actual PostgreSQL 121/128-character reservations and SQL rejection above 128 passed, together with Game Session formatting/static checks and the whole World consumer gate. The seven current Human containment/retention cases, including actual pre-1006 COMMITTED/ABORTED history upgraded without changing original fields/bytes/`xmin`, passed in the preceding fresh native gates. These results qualify their stated owner boundaries; a completely successful current-head Game Session native suite, exact published-source CI, review and rebuilt packaged runtime remain separate. Earlier full-carrier results do not qualify these authored postimages. The canonical receipt and phase ordering remain in [Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence). ### Run-owned canonical source handoff 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 9d13bb0955..c8a15e2341 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -The canonical launch-owner successor adds authenticated fixed Game Session `STARTING` allocation readback. World bootstrap and fixture prepare/activate refuse before owner effects until actual World materialization and holds are composed. That source read grants no World lifecycle, first admission, Entity or operational-region authority. The successor World whole-service check, formatting, static analysis and documentation checks passed on parent `b41a1f8c9853e87592e09f0b4194dca8965b2cc0`. Its 65 freshly executed service integration cases comprise 63 PostgreSQL-backed cases and two controlled mTLS socket tests; 271 unit cases retained their preceding execution attribution. The socket tests qualify authentication and exact echo against controlled remote handlers, while the database cases qualify before-effects refusal and independent passive storage, retained rows and constraints. They do not establish a live remote Game Session producer, complete-commit producer, World activation or packaged runtime. The preceding guarded graph owner's proof retains its own published-source attribution. All four genuine handoffs remain open. +The canonical launch-owner successor adds authenticated fixed Game Session `STARTING` allocation readback. World bootstrap and fixture prepare/activate refuse before owner effects until actual World materialization and holds are composed. That source read grants no World lifecycle, first admission, Entity or operational-region authority. After the ordinary carry of [PR #3203](https://github.com/benhook1013/FireMUD/pull/3203) at `3ae5fffd4aec52101739c78d89cd6bd0ce5f9935`, the selected successor at `4cee3da213ad2b4d1ba27a4bbb7e418efee88a8a` passed its World whole-service check, formatting, static analysis and documentation checks in 2m43s: 292 fresh unit cases and 65 fresh service integration cases, with zero failures, errors or skips. The integration cases comprise 63 PostgreSQL-backed cases and two controlled mTLS socket tests. The socket cases qualify authentication and exact echo against controlled remote handlers; the database cases qualify before-effects refusal and independent passive storage, original rows/bytes/`xmin`, constraints and CAS. They establish neither a live remote Game Session producer, complete-commit producer, World activation nor packaged runtime. All four genuine handoffs remain open. ### Guarded graph capture and frozen owner stage From b96aff35d283b957ebc97f131724ca1f7f113cfc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:19:55 +1300 Subject: [PATCH 03/26] Allow canonical Game Session CI proof its full cleanup budget --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1dae6562cd..4965ac821c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -989,8 +989,8 @@ jobs: permissions: contents: read id-token: write - # Account and World PostgreSQL proofs can run close to 20 minutes before Gradle post-job cleanup. - timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'world-management-service') && 30 || 20 }} + # Account, World and Game Session proofs can run close to 20 minutes before Gradle post-job cleanup. + timeout-minutes: ${{ (matrix.module == 'account-service' || matrix.module == 'world-management-service' || matrix.module == 'game-session-service') && 30 || 20 }} strategy: fail-fast: false matrix: From 39a52bd4d4ba7533663be6edf3d6c1cafcfd3e58 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:20:56 +1300 Subject: [PATCH 04/26] Fix canonical fixture launch review findings --- .../v1/game_session_service.proto | 2 +- ...nstanceLaunchAssociationReadGrpcCodec.java | 9 +- ...dInitialAdmissionFixtureWireCodecTest.java | 63 ++++--- ...meInstanceLaunchAssociationRepository.java | 13 +- ...essionCanonicalRealmCatalogRepository.java | 172 ++---------------- ...ssionFreshTenantAssociationRepository.java | 15 ++ ...tAssociationRepositoryIntegrationTest.java | 3 +- ...nitialAdmissionFixtureCoordinatorTest.java | 6 +- ...stanceLaunchAssociationRepositoryTest.java | 2 +- ...eLaunchAssociationReadGrpcServiceTest.java | 4 +- .../data/RunOwnedWorldLaunchEvidence.java | 9 +- .../RunOwnedWorldLaunchEvidenceProvider.java | 37 ---- ...nOwnedWorldLaunchEvidenceProviderTest.java | 24 ++- 13 files changed, 118 insertions(+), 241 deletions(-) diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 792771a2d4..7bc0c36677 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -669,7 +669,7 @@ message GetRunOwnedFixtureLaunchAssociationResponse { string canonical_version_id = 9; string canonical_realm_id = 10; string playable_state_namespace_id = 11; - string playable_state_scope = 12; + entity_management.v1.PlayableStateScope playable_state_scope = 12; int64 catalog_revision = 13; string current_game_instance_status = 14; int64 current_row_version = 15; 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 bd897d68ba..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 @@ -66,7 +66,9 @@ private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} .setCanonicalVersionId(result.canonicalVersionId().toString()) .setCanonicalRealmId(result.canonicalRealmId().toString()) .setPlayableStateNamespaceId(result.playableStateNamespaceId().toString()) - .setPlayableStateScope("SHARED") + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) .setCatalogRevision(result.catalogRevision()) .setCurrentGameInstanceStatus(result.currentGameInstanceStatus().name()) .setCurrentRowVersion(result.currentRowVersion()) @@ -90,7 +92,10 @@ private CanonicalGameInstanceLaunchAssociationReadGrpcCodec() {} response.getTargetNamespace(), parseCanonicalNonNilUuid(response.getFixtureOperationId(), "fixtureOperationId"), response.getExpectedFixturePolicyEvidenceDigest()); - if (!expected.equals(actual) || !"SHARED".equals(response.getPlayableStateScope())) { + 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"); } 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 f30175fbfd..cc0cb0678f 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 @@ -147,28 +147,31 @@ void rejectsRecursiveUnknownProtoFieldsAndDescriptorProjectionMismatches() { .setUnknownFields(UNKNOWN_FIELD_SET)) .build(); assertInvalidReceipt( - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorWithNestedUnknownFields)); + () -> + sourceReceiptJson( + sourceEvidence(), + bundle(), + artifactState(), + versionState(), + descriptorWithNestedUnknownFields)); assertInvalidReceipt( - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorFor(12L, bundle().getId(), bundle().getPublishedReleaseBundleRef()))); + () -> + sourceReceiptJson( + sourceEvidence(), + bundle(), + artifactState(), + versionState(), + descriptorFor(12L, bundle().getId(), bundle().getPublishedReleaseBundleRef()))); assertInvalidReceipt( - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorFor( - bundle().getVersionId(), bundle().getId(), "different-owner-release-ref"))); + () -> + sourceReceiptJson( + sourceEvidence(), + bundle(), + artifactState(), + versionState(), + descriptorFor( + bundle().getVersionId(), bundle().getId(), "different-owner-release-ref"))); } @Test @@ -244,6 +247,13 @@ void closedFixtureAllocationReadRejectsChangedIdentitySealAndVersion() { 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( @@ -323,6 +333,11 @@ private static void assertInvalidCapabilityBytes(byte[] bytes) { .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); } + private static void assertInvalidReceipt(java.util.function.Supplier json) { + assertThatThrownBy(() -> parseSourceReceipt(json.get(), capability())) + .isInstanceOf(IllegalArgumentException.class); + } + private static void assertInvalidReceipt(String json) { assertInvalidReceiptBytes(json.getBytes(StandardCharsets.UTF_8)); } @@ -398,13 +413,13 @@ private static String sourceReceiptJson( new LaunchReadEvidence( RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, 17L, - bundle(), - artifactState(), - versionState(), - launchDescriptor()); + bundle, + artifactState, + versionState, + descriptor); String requestDigest = RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( - capability(), creationEvidence(), sourceEvidence(), launch); + capability(), creationEvidence(), source, launch); var seal = new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, 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 0786f8447e..827ca3963c 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,18 +58,9 @@ 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) { - requireWritableReadCommittedOwnerTransaction(); - throw new IllegalStateException( - "Original StartSession tuple is required for canonical launch capture"); - } - - /** Captures the exact Human tuple and actual catalog owner identity with the STARTING row. */ public CanonicalGameInstanceLaunchAssociation capture( FreshGameSessionTenantAssociation tenantAssociation, long gameInstanceId, 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 2899a59553..45ac237c3d 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 @@ -1,9 +1,6 @@ package net.firedevops.firemud.gamesession.repository; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; @@ -13,12 +10,10 @@ import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.util.Arrays; -import java.util.HashSet; import java.util.HexFormat; 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.gamedesign.RealmPolicyPublishedEvidence; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; @@ -33,6 +28,7 @@ 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; @@ -1463,20 +1459,6 @@ private static String completeCatalogRequestDigest(String requestDigest, byte[] HexFormat.of().formatHex(policyBytes)); } - private static final ObjectMapper JSON = new ObjectMapper(); - private static final Set CREATION_EVIDENCE_FIELDS = - Set.of( - "schemaVersion", - "targetNamespace", - "creationRequestId", - "operationId", - "requestDigest", - "canonicalTenantId", - "sourceGameRowId", - "sourceGameTenantKey", - "provenanceKind", - "evidenceDigest"); - private final String workloadNamespace; private final TransactionTemplate writeTransaction; private final TransactionTemplate readTransaction; @@ -1503,81 +1485,25 @@ public GameSessionCanonicalRealmCatalogRepository( private FreshTenantAssociation verifyStoredFreshAssociation( AuthoredWorldSourceEvidence source, UUID canonicalTenantId) { - Record row = - dsl.fetchOne( - "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" - + " WHERE fresh.target_namespace = ? AND fresh.canonical_tenant_id = ?", - source.targetNamespace(), - canonicalTenantId); - if (row == null) { - throw new InvalidCanonicalRealmCatalogException( - "Fresh canonical realm requires an existing complete Game Session tenant association"); - } try { - String requestIdText = required(row, "association_request_id", UUID.class).toString(); - UUID associationOperationId = required(row, "association_operation_id", UUID.class); - UUID tenantId = required(row, "canonical_tenant_id", UUID.class); - long numericTenantId = required(row, "legacy_game_session_tenant_id", Long.class); - FreshTenantCreationEvidence creation = - parseCreationEvidence(required(row, "complete_source_evidence", String.class)); - if (!source.targetNamespace().equals(required(row, "target_namespace", String.class)) - || !source - .targetNamespace() - .equals(required(row, "source_target_namespace", String.class)) - || !requestIdText.equals(required(row, "source_request_id", UUID.class).toString()) - || !tenantId.equals(required(row, "source_canonical_tenant_id", UUID.class)) - || required(row, "source_schema_version", Integer.class) != creation.schemaVersion() - || required(row, "source_game_row_id", Long.class) != creation.sourceGameRowId() - || !required(row, "source_game_tenant_key", String.class) - .equals(creation.sourceGameTenantKey()) - || !required(row, "provenance_kind", String.class).equals(creation.provenanceKind()) - || !"FRESH_SOURCE_BOUND".equals(required(row, "association_kind", String.class)) - || !creation.targetNamespace().equals(source.targetNamespace()) - || !creation - .creationRequestId() - .equals(required(row, "association_request_id", UUID.class)) - || !creation.canonicalTenantId().equals(tenantId) - || !creation.targetNamespace().equals(source.targetNamespace()) + FreshTenantAssociation association = + new GameSessionFreshTenantAssociationRepository(dsl) + .readCanonicalTenantAssociationSnapshot(source.targetNamespace(), canonicalTenantId) + .orElseThrow( + () -> + new InvalidCanonicalRealmCatalogException( + "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()) - || !"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)) - || !source.targetNamespace().equals(required(row, "claim_namespace", String.class)) - || !tenantId.equals(required(row, "claim_canonical_tenant_id", UUID.class)) - || numericTenantId != required(row, "claim_tenant_id", Long.class) - || !associationOperationId.equals(required(row, "claim_operation_id", UUID.class)) - || !required(row, "association_request_id", UUID.class) - .equals(required(row, "claim_request_id", UUID.class)) - || associationOperationId.equals(creation.operationId())) { + || !creation.provenanceKind().equals(source.provenanceKind())) { throw new InvalidCanonicalRealmCatalogException( "Stored fresh tenant association differs from complete source receipt or canonical claim"); } - return new FreshTenantAssociation( - source.targetNamespace(), tenantId, numericTenantId, associationOperationId, creation); - } catch (IllegalArgumentException invalid) { + return association; + } catch (InvalidFreshTenantAssociationException | IllegalArgumentException invalid) { throw new InvalidCanonicalRealmCatalogException( "Stored fresh tenant association contains invalid complete source evidence", invalid); } @@ -1622,72 +1548,6 @@ private static SelectedPolicy selectPolicy( return new SelectedPolicy(selected.policyId(), selected.policyDigest(), policy); } - /** ADR0047 UTF-8 byte-length framing; every input segment has an unambiguous byte boundary. */ - private static FreshTenantCreationEvidence parseCreationEvidence(String serializedEvidence) { - try { - JsonNode json = JSON.readTree(serializedEvidence); - if (json == null || !json.isObject() || json.size() != CREATION_EVIDENCE_FIELDS.size()) { - throw new IllegalArgumentException( - "Complete creation evidence must be one closed JSON object"); - } - HashSet fields = new HashSet<>(); - json.fieldNames().forEachRemaining(fields::add); - if (!fields.equals(CREATION_EVIDENCE_FIELDS)) { - throw new IllegalArgumentException( - "Complete creation evidence has unknown or missing fields"); - } - 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 invalid) { - throw new InvalidCanonicalRealmCatalogException( - "Stored complete Game Design creation evidence is invalid", invalid); - } - } - - private static String requiredText(JsonNode json, String field) { - JsonNode value = json.get(field); - if (value == null || !value.isTextual()) { - throw new IllegalArgumentException("Complete creation 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 creation 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 creation 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) || NIL_UUID.equals(parsed)) { - throw new IllegalArgumentException( - "Complete creation evidence UUID must be canonical and nonnil"); - } - return parsed; - } - private static T required(Record row, String field, Class type) { T value = row.get(field, type); if (value == null) { @@ -1697,12 +1557,6 @@ private static T required(Record row, String field, Class type) { return value; } - private static void sourceRequireNonNil(UUID id, String label) { - if (id == null || NIL_UUID.equals(id)) { - throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); - } - } - private static void requireNoActiveOwnerTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive()) { throw new IllegalStateException( 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 2c0461fb58..6c8817a671 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 @@ -498,6 +498,9 @@ FreshTenantAssociation associateVerifiedFixtureInOwnerTransaction( private FreshTenantAssociation commitAssociation( FreshTenantCreationEvidence sourceEvidence, UUID requestedOperationId) { requireOwnerTransaction(); + if (requestedOperationId != null) { + lockAssociationOperation(requestedOperationId); + } lockSourceIdentity(sourceEvidence); Optional prior = @@ -514,6 +517,12 @@ private FreshTenantAssociation commitAssociation( } 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 @@ -583,6 +592,12 @@ private FreshTenantAssociation commitAssociation( 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"); } 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 d044ab765e..690b977d61 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 @@ -19,6 +19,7 @@ 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.FreshTenantAssociationConflictException; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantSourceException; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; @@ -127,7 +128,7 @@ void rejectsSameOperationWithDifferentSourceOrNamespaceAsAnIdempotencyConflict() FreshGameSessionTenantAssociation committed = fixture.associate(associationOperationId, NAMESPACE, firstSource); assertThatThrownBy(() -> fixture.associate(associationOperationId, NAMESPACE, secondSource)) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + .isExactlyInstanceOf(FreshTenantAssociationConflictException.class); assertThatThrownBy( () -> fixture.associate(associationOperationId, NAMESPACE + "-other", firstSource)) .isInstanceOf(InvalidFreshTenantSourceException.class); 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 f1fca96135..c9bf4676e1 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 @@ -329,7 +329,11 @@ void scheduledRetryDoesNotOverlapAnInProgressLaunchOwnerAttempt() throws Excepti }); assertThat(enteredOwner.await(5, TimeUnit.SECONDS)).isTrue(); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); + try (MockedStatic mainLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + stubFixtureLoaders(mainLoader, fixture, fixture.sourceReceipt); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } verify(fixture.launchOwner, times(1)).createVerifiedFixtureStartingLaunch(any()); releaseOwner.countDown(); 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/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java index b5a057fa28..634e202804 100644 --- 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 @@ -96,7 +96,9 @@ void returnsTheExactStartingCatalogPrivateKeysCreationSourceAndSeal() { response.getCanonicalVersionId()); assertEquals(REALM_ID.toString(), response.getCanonicalRealmId()); assertEquals(PLAYABLE_NAMESPACE_ID.toString(), response.getPlayableStateNamespaceId()); - assertEquals("SHARED", response.getPlayableStateScope()); + 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()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java index cd39f90220..3374f44131 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java @@ -58,6 +58,8 @@ public final class RunOwnedWorldLaunchEvidence { this.caCertificateSha256 = Objects.requireNonNull(caCertificateSha256, "caCertificateSha256"); this.gameSessionAssociation = Objects.requireNonNull(gameSessionAssociation, "gameSessionAssociation"); + requireExactGameSessionFixtureAssociation( + this.capability, this.sourceReceipt, this.gameSessionAssociation); } public RunOwnedInitialAdmissionFixtureWireCodec.Capability capability() { @@ -165,10 +167,13 @@ public void requireMatches(PreparedWorldInstanceRequest request) { "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: prepared request differs from committed fixture evidence"); } requireGameSessionAllocation(request.tenantId(), request.gameInstanceId()); - requireExactGameSessionFixtureAssociation(); + requireExactGameSessionFixtureAssociation(capability, sourceReceipt, gameSessionAssociation); } - private void requireExactGameSessionFixtureAssociation() { + static void requireExactGameSessionFixtureAssociation( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt, + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation) { var expectedPolicy = new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest( capability, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java index e6aad20b80..b0c89c1d91 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -12,7 +12,6 @@ import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.util.Arrays; import java.util.Collection; import java.util.HexFormat; import java.util.List; @@ -181,7 +180,6 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { gameSessionFixtureClient() .readFixture(fixtureReadRequest, capability.gameSessionLeafSha256()); stage = VerificationStage.GAME_SESSION_FIXTURE_COMPARE; - requireFixtureReadback(capability, receipt, gameSessionAssociation); return new RunOwnedWorldLaunchEvidence( capability, @@ -206,41 +204,6 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { } } - private static void requireFixtureReadback( - RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, - RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt, - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult actual) { - var expectedPolicy = - new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest( - capability, - receipt.creationEvidence(), - receipt.sourceEvidence(), - receipt.launchReadEvidence()); - byte[] expectedBytes = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( - capability, - receipt.creationEvidence(), - receipt.sourceEvidence(), - receipt.launchReadEvidence()); - if (!actual.request().fixtureOperationId().toString().equals(capability.operationId()) - || !actual.request().targetNamespace().equals(receipt.sourceEvidence().targetNamespace()) - || !actual - .request() - .expectedFixturePolicyEvidenceDigest() - .equals(receipt.fixturePolicySeal().evidenceDigest()) - || !actual.fixturePolicySeal().equals(receipt.fixturePolicySeal()) - || !Objects.equals(actual.fixturePolicyRequest(), expectedPolicy) - || !Arrays.equals(actual.fixturePolicyRequestBytes(), expectedBytes) - || !actual.canonicalTenantId().equals(receipt.sourceEvidence().canonicalTenantId()) - || !actual - .canonicalVersionId() - .toString() - .equals( - receipt.launchReadEvidence().publishedReleaseBundle().getCanonicalVersionId())) { - throw invalidEvidence(); - } - } - private static UUID freshFixtureReadRequestId(UUID fixtureOperationId) { UUID readRequestId; do { 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 38328a1538..f920b7cdf7 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 @@ -85,6 +85,13 @@ void launchEvidenceBindsStartingAllocationPrivateKeysFromOwnerProjection() { .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_ALLOCATION_MISMATCH:"); } + @Test + void launchEvidenceConstructorRejectsMismatchedGameSessionFixtureAssociation() { + assertThatThrownBy(() -> fixtureEvidence(true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_FIXTURE_ASSOCIATION_MISMATCH:"); + } + @Test void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign(CapturedOutput output) { GameDesignClient gameDesignClient = mock(GameDesignClient.class); @@ -262,6 +269,10 @@ private static PreparedWorldInstanceRequest request(String patch, String remap) } private static RunOwnedWorldLaunchEvidence fixtureEvidence() { + return fixtureEvidence(false); + } + + private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSeal) { UUID registrationId = UUID.fromString(OPERATION_ID); UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); @@ -427,6 +438,17 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { policyRequestDigest, RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( UUID.fromString(OPERATION_ID), policyRequestDigest)); + UUID otherSealOperation = UUID.fromString("20000000-0000-4000-8000-000000000012"); + var receiptSeal = + mismatchedSeal + ? new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( + policySeal.schema(), + policySeal.ownerService(), + otherSealOperation, + policySeal.requestDigest(), + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + otherSealOperation, policySeal.requestDigest())) + : policySeal; var receipt = new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, @@ -442,7 +464,7 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { source, launchRead, creation, - policySeal); + receiptSeal); var policyRequestBytes = RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( capability, creation, source, launchRead); From eef2c317cac61211a5619badc70e3380f5696995 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:17:50 +1300 Subject: [PATCH 05/26] Fix fixture review findings and strict claim-bound capability carriage --- .../world-runtime-and-movement.md | 6 +- dev-tools/smoke/run-owned-compose.sh | 15 +- ...d-initial-admission-capability-contract.sh | 39 ++- .../gamedesign/data/TestDataSeeder.java | 3 +- .../gamedesign/data/TestDataSeederTest.java | 81 +++++++ ...essionCanonicalRealmCatalogRepository.java | 25 +- .../GameSessionControlPlaneGrpcService.java | 2 +- ...InitialAdmissionFixtureCapabilityTest.java | 227 ++++++++++-------- ...alInitialAdmissionHoldPreparationTest.java | 191 ++------------- .../worldmanagement/data/TestDataSeeder.java | 7 +- .../data/TestDataSeederTest.java | 9 +- 11 files changed, 296 insertions(+), 309 deletions(-) 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 45452db131..c458d010fc 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -36,7 +36,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. Earlier coordinator-driven holds and World fixture PREPARING/ACTIVE binding belong to predecessor revisions. The current run-owned coordinator completes canonical Game Session STARTING allocation and independent readback only; World fixture bootstrap, prepare and activate refuse before owner effects. World’s authenticated Game Session read verifies immutable fixture provenance and private allocation identity and grants no 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. @@ -56,7 +56,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 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. | World retains lifecycle and initial-admission hold storage and read boundaries. The current run-owned fixture path verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation; fixture bootstrap skips all seeding with a diagnostic, and prepare/activate refuse before materialization, lifecycle, hold or first-OPEN effects. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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) | Current fixture materialization, activation, continuous Account protection, hold acquisition and first OPEN remain unavailable. 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. | @@ -147,7 +147,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). +- The current run-owned Compose coordinator completes canonical Game Session STARTING allocation/readback only. World fixture bootstrap, prepare and activate remain unavailable before effects; materialization, activation, holds and first OPEN are explicit gaps. Earlier coordinator/hold implementation and proof are historical. 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) 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/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 c8b36019b6..c9956062a4 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 @@ -552,7 +552,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"); } 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 9d39fbb03a..03cf9f6a44 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; @@ -488,6 +493,82 @@ 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"); + + var creationRepository = + mock(net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository.class); + var fixturePolicyProducer = mock(RunOwnedFixturePolicyProducer.class); + ReflectionTestUtils.setField(seeder, "creationRepository", creationRepository); + ReflectionTestUtils.setField(seeder, "fixturePolicyProducer", fixturePolicyProducer); + + 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/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index 45ac237c3d..8218a475b2 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 @@ -1477,6 +1477,7 @@ public GameSessionCanonicalRealmCatalogRepository( 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); @@ -1491,7 +1492,7 @@ private FreshTenantAssociation verifyStoredFreshAssociation( .readCanonicalTenantAssociationSnapshot(source.targetNamespace(), canonicalTenantId) .orElseThrow( () -> - new InvalidCanonicalRealmCatalogException( + new InvalidCatalogEvidenceException( "Fresh canonical realm requires an existing complete Game Session tenant association")); FreshTenantCreationEvidence creation = association.sourceEvidence(); if (!creation.targetNamespace().equals(source.targetNamespace()) @@ -1499,12 +1500,12 @@ private FreshTenantAssociation verifyStoredFreshAssociation( || creation.sourceGameRowId() != source.sourceGameRowId() || !creation.sourceGameTenantKey().equals(source.sourceGameTenantKey()) || !creation.provenanceKind().equals(source.provenanceKind())) { - throw new InvalidCanonicalRealmCatalogException( + throw new InvalidCatalogEvidenceException( "Stored fresh tenant association differs from complete source receipt or canonical claim"); } return association; } catch (InvalidFreshTenantAssociationException | IllegalArgumentException invalid) { - throw new InvalidCanonicalRealmCatalogException( + throw new InvalidCatalogEvidenceException( "Stored fresh tenant association contains invalid complete source evidence", invalid); } } @@ -1523,7 +1524,7 @@ private static SelectedPolicy selectPolicy( .targetNamespace() .equals(source.targetNamespace()) || !"NEW_GAME_ROW".equals(publishedSet.target().sourceProvenanceKind())) { - throw new InvalidCanonicalRealmCatalogException( + throw new InvalidCatalogEvidenceException( "Published policy target or operation namespace differs from exact fresh authored-world source identity"); } List publicPolicies = @@ -1535,14 +1536,14 @@ private static SelectedPolicy selectPolicy( .toList(); if (publishedSet.policyCount() != publishedSet.policies().size() || publicPolicies.size() != 1) { - throw new InvalidCanonicalRealmCatalogException( + 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 InvalidCanonicalRealmCatalogException( + throw new InvalidCatalogEvidenceException( "Public-production policy must exactly match the authored world"); } return new SelectedPolicy(selected.policyId(), selected.policyDigest(), policy); @@ -1551,7 +1552,7 @@ private static SelectedPolicy selectPolicy( private static T required(Record row, String field, Class type) { T value = row.get(field, type); if (value == null) { - throw new InvalidCanonicalRealmCatalogException( + throw new InvalidCatalogEvidenceException( "Stored canonical realm catalog is missing required evidence: " + field); } return value; @@ -1572,14 +1573,4 @@ private static void requireOwnerTransaction() { } private record SelectedPolicy(UUID policyId, String policyDigest, RealmEntryPolicy policy) {} - - public static final class InvalidCanonicalRealmCatalogException extends IllegalStateException { - public InvalidCanonicalRealmCatalogException(String message) { - super(message); - } - - public InvalidCanonicalRealmCatalogException(String message, Throwable cause) { - super(message, cause); - } - } } 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 0e59e58c80..dcf1eef8b2 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 @@ -385,7 +385,7 @@ public void getRunOwnedFixtureLaunchAssociation( .withDescription("Exact fixed fixture launch owner read is unavailable") .asRuntimeException()); } catch (RuntimeException failure) { - logger.error("GetRunOwnedFixtureLaunchAssociation failed"); + logger.error("GetRunOwnedFixtureLaunchAssociation failed", failure); responseObserver.onError( Status.INTERNAL.withDescription("Fixture launch owner read failed").asRuntimeException()); } 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 1771c71fd9..baefbfa134 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,6 +18,7 @@ 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; @@ -202,23 +203,26 @@ void rejectsOpenDuplicateMismatchedAndMalformedSourceReceiptFields() { assertInvalidSourceReceipt(json.replace(canonicalBundle, nonCanonicalBundle)); assertInvalidSourceReceipt(json.replace(canonicalBundle, encode(new byte[] {10, 5}))); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), - launchBundle().toBuilder() - .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") - .build())); + () -> + validSourceReceiptJson( + sourceEvidence(), + launchBundle().toBuilder() + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .build())); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setArtifactStateValue(999).build(), - launchVersionState())); + () -> + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState().toBuilder().setArtifactStateValue(999).build(), + launchVersionState())); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setVersionStateValue(999).build())); + () -> + validSourceReceiptJson( + sourceEvidence(), + launchBundle(), + launchArtifactState(), + launchVersionState().toBuilder().setVersionStateValue(999).build())); } @Test @@ -236,7 +240,9 @@ void rejectsLaunchDescriptorThatDoesNotMatchOwnerReadSnapshots() { .build()); assertInvalidSourceReceipt( - validSourceReceiptJson(source, bundle, artifactState, versionState, mismatchedDescriptor)); + () -> + validSourceReceiptJson( + source, bundle, artifactState, versionState, mismatchedDescriptor)); } @Test @@ -245,62 +251,75 @@ 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"), + () -> + 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())); invalidReceipts.forEach( RunOwnedInitialAdmissionFixtureCapabilityTest::assertInvalidSourceReceipt); @@ -314,12 +333,13 @@ void rejectsNonpositiveVersionStateSnapshotEpochFromRawMalformedReceiptEvidence( var versionState = launchVersionState().toBuilder().setVersionStateEpoch(0L).build(); assertInvalidSourceReceipt( - validSourceReceiptJson( - source, - bundle, - artifactState, - versionState, - rawLaunchDescriptorForMalformedVersionStateSnapshot(source, bundle, versionState))); + () -> + validSourceReceiptJson( + source, + bundle, + artifactState, + versionState, + rawLaunchDescriptorForMalformedVersionStateSnapshot(source, bundle, versionState))); } @Test @@ -338,7 +358,7 @@ void rejectsArtifactSnapshotMissingTheBundlesRequiredManifestKey() { assertThat(bundle.getRequiredManifestAssetKeysList()).containsExactly("manifest.json"); assertThat(missingKeys.getExportedManifestAssetKeysList()).isEmpty(); assertInvalidSourceReceipt( - validSourceReceiptJson(sourceEvidence(), bundle, missingKeys, launchVersionState())); + () -> validSourceReceiptJson(sourceEvidence(), bundle, missingKeys, launchVersionState())); } @Test @@ -354,7 +374,7 @@ void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { .setUnknownFields(unknownFields) .build()) .build(); - assertInvalidSourceReceipt(validSourceReceiptJson(sourceEvidence(), nestedUnknownBundle)); + assertInvalidSourceReceipt(() -> validSourceReceiptJson(sourceEvidence(), nestedUnknownBundle)); var nestedUnknownParticipant = launchBundle().toBuilder() .addParticipantDigests( @@ -362,10 +382,13 @@ void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { .setUnknownFields(unknownFields) .build()) .build(); - assertInvalidSourceReceipt(validSourceReceiptJson(sourceEvidence(), nestedUnknownParticipant)); assertInvalidSourceReceipt( - validSourceReceiptJson( - sourceEvidence(), launchBundle().toBuilder().setUnknownFields(unknownFields).build())); + () -> validSourceReceiptJson(sourceEvidence(), nestedUnknownParticipant)); + assertInvalidSourceReceipt( + () -> + validSourceReceiptJson( + sourceEvidence(), + launchBundle().toBuilder().setUnknownFields(unknownFields).build())); } @Test @@ -689,29 +712,9 @@ private static RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixtur artifactState, versionState, descriptor); - String requestDigest; - try { - requestDigest = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( - capability, creation, source, launchReadEvidence); - } catch (IllegalArgumentException invalidNegativeTestEvidence) { - AuthoredWorldSourceEvidence validSource = sourceEvidence(); - var validBundle = launchBundle(); - var validArtifactState = launchArtifactState(); - var validVersionState = launchVersionState(); - var validCreation = creationEvidence(validSource); - var validLaunchReadEvidence = - new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( - RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, - capability.gameTemplateId(), - validBundle, - validArtifactState, - validVersionState, - launchDescriptor(validSource, validBundle, validVersionState)); - requestDigest = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( - capability, validCreation, validSource, validLaunchReadEvidence); - } + String requestDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( + capability, creation, source, launchReadEvidence); UUID fixtureOperationId = UUID.fromString(capability.operationId()); return new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, @@ -938,6 +941,18 @@ private static void assertInvalidSourceReceipt(String json) { assertInvalidSourceReceiptBytes(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); } + private static void assertInvalidSourceReceipt(Supplier receiptJson) { + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + receiptJson.get().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + capability(), + pins())) + .isInstanceOf(IllegalArgumentException.class); + } + private static void assertInvalidSourceReceiptBytes(byte[] bytes) { assertThatThrownBy( () -> 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 215e740db5..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 @@ -4,25 +4,22 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; 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; @@ -45,97 +42,26 @@ void clearTransactionContext() { TransactionSynchronizationManager.clear(); } - @Test - void freshHumanRequestDeniesBeforeIntentTransactionOrWorldAccess() { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); + @ParameterizedTest + @MethodSource("humanRequestAndLifecycleVariants") + void humanRequestVariantsDenyBeforeOwnerAccessOrTransaction( + Request request, WorldCanonicalInstanceLifecycleEvidence.Request lifecycle) { + assertHumanUnavailable(new Fixtures(), request, lifecycle); } - @Test - void unavailableIntentOwnerCannotMoveDenialAfterReservation() { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenThrow(new IllegalStateException("reserve failed")); - assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); + 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 failingTransactionManagerCannotBeginUnprotectedHumanReservation() { - Fixtures fixtures = new Fixtures(new ArrayList<>(), true); - assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); - } - - @Test - void repeatedHumanRequestDoesNotReserveOrAcquireAfterRemoteFailure() { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenThrow(new IllegalStateException("World unavailable")); - for (int retry = 0; retry < 2; retry++) { - assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); - } - } - - @Test - void configuredWorldIdentityAndAttachFailureCannotBypassHumanProtection() { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - HoldIdentity acquired = identity(HOLD_REQUEST, 9); - when(fixtures.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(acquired); - when(fixtures.repository.attach(HOLD_REQUEST, acquired)) - .thenThrow(new IllegalStateException("attach changed")); - assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); - } - - @Test - void attachedOrTerminalReadbackCannotAuthorizeNewHumanPreparation() { - for (IntentState state : List.of(IntentState.HOLD_ATTACHED, IntentState.TERMINAL)) { - Fixtures fixtures = new Fixtures(new ArrayList<>()); - // Controlled readback input is never queried and establishes no live admission authority. - var retained = snapshot(state, identity(HOLD_REQUEST, 10), HOLD_REQUEST, LIFECYCLE_REQUEST); - when(fixtures.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)).thenReturn(retained); - assertHumanUnavailable(fixtures, HOLD_REQUEST, LIFECYCLE_REQUEST); - } - } - - @Test - void changedRequestLifecycleSnapshotAndWorldIdentityCannotBypassEarlyHumanDenial() { - Fixtures wrongIdentity = new Fixtures(new ArrayList<>()); - when(wrongIdentity.worldClient.acquire(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn(identity(holdRequest("different-request"), 11)); - assertHumanUnavailable(wrongIdentity, HOLD_REQUEST, LIFECYCLE_REQUEST); - - Fixtures changedSnapshot = new Fixtures(new ArrayList<>()); - when(changedSnapshot.repository.reserve(HOLD_REQUEST, LIFECYCLE_REQUEST)) - .thenReturn( - snapshot( - IntentState.PENDING_HOLD, - null, - HOLD_REQUEST, - lifecycleRequestWithChangedIdentity())); - assertHumanUnavailable(changedSnapshot, HOLD_REQUEST, LIFECYCLE_REQUEST); - - Fixtures changedAttach = new Fixtures(new ArrayList<>()); - HoldIdentity acquired = identity(HOLD_REQUEST, 12); - when(changedAttach.repository.attach(HOLD_REQUEST, acquired)) - .thenReturn( - snapshot( - IntentState.HOLD_ATTACHED, - identity(HOLD_REQUEST, 14), - HOLD_REQUEST, - LIFECYCLE_REQUEST)); - assertHumanUnavailable(changedAttach, HOLD_REQUEST, LIFECYCLE_REQUEST); - assertHumanUnavailable( - new Fixtures(new ArrayList<>()), - holdRequest("different-request"), - lifecycleRequestWithChangedIdentity()); - assertHumanUnavailable( - new Fixtures(new ArrayList<>()), - holdRequest("closed-origin-request", InitialAdmissionOrigin.EXPECT_CLOSED, 1L), - LIFECYCLE_REQUEST); - } - - @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) @@ -143,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) @@ -162,48 +88,6 @@ private static void assertHumanUnavailable( .hasMessageContaining("Account terminal protection"); verifyNoInteractions(fixtures.repository, fixtures.worldClient); assertThat(fixtures.transactionManager.transactionDefinitions).isEmpty(); - assertThat(fixtures.transactionManager.events).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) { @@ -281,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)); } @@ -297,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); } @@ -310,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() { @@ -328,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/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java index e5716cac91..e132c8f914 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.worldmanagement.data; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import net.firedevops.firemud.worldmanagement.entity.Region; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; @@ -24,6 +25,7 @@ havingValue = "true", matchIfMissing = false) @RequiredArgsConstructor +@Slf4j public class TestDataSeeder implements ApplicationRunner { private static final long DEMO_TENANT_ID = 1L; private static final long DEMO_VERSION_ID = 1L; @@ -50,8 +52,9 @@ public class TestDataSeeder implements ApplicationRunner { @Transactional public void run(ApplicationArguments args) { if (runOwnedFixtureMode) { - throw new IllegalStateException( - "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture runtime seeding is disabled until World-owned materialization is available"); + log.warn( + "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture runtime seeding skipped until World-owned materialization is available"); + return; } ensureDemoTopology(); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java index 2bc0a3aa69..dee68973b3 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java @@ -110,15 +110,10 @@ void runSeedsCanonicalTopologyWhenMissing() throws Exception { } @Test - void fixtureModeRefusesBeforeAnyRepositoryReadOrWrite() { + void fixtureModeSkipsSeedingWithoutPreventingStartupOrAccessingRepositories() { ReflectionTestUtils.setField(seeder, "runOwnedFixtureMode", true); - IllegalStateException error = - assertThrows( - IllegalStateException.class, - () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); - - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); + seeder.run(new DefaultApplicationArguments(new String[] {})); verifyNoInteractions(regionRepository, zoneRepository, roomRepository, roomExitRepository); } From 5949689ce2954e25546707db1c31ad0f4636a6c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:26:17 +1300 Subject: [PATCH 06/26] Fix canonical launch terminal protection and reviewed proof boundaries --- .../world-management-service/api-contracts.md | 6 +- .../runtime-and-data.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 +- .../world-runtime-and-movement.md | 4 +- ...unOwnedInitialAdmissionLaunchEvidence.java | 5 +- .../service/impl/GameInstanceServiceImpl.java | 48 +- ...anonical_launch_exact_catalog_identity.sql | 2 +- ..._initial_admission_terminal_protection.sql | 10 +- ...ialAdmissionRepositoryIntegrationTest.java | 112 ++++ ...unchPreparationServiceIntegrationTest.java | 3 +- .../RunOwnedWorldLaunchEvidenceProvider.java | 42 +- ...nOwnedWorldLaunchEvidenceProviderTest.java | 577 +++++++++++++++++- 12 files changed, 733 insertions(+), 80 deletions(-) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 5e97cfb62c..0bdf8fbf32 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -275,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 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. The current run-owned coordinator completes Game Session STARTING allocation and readback only; it does not acquire a World hold or authorize the first admission pointer. 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. @@ -283,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). +Current fixture bootstrap skips runtime seeding; prepare and activate refuse before repository effects because World-owned materialization remains unavailable. The provider’s bounded descriptor and authenticated Game Session read exist as source capability, with controlled proof, but no current production lifecycle caller invokes them. 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 f14f1b6f4a..4190123aa8 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -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 current run-owned fixture independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation. World fixture bootstrap and prepare/activate refuse before repository effects pending actual World source/Version materialization, association, fixed-preset preparation and holds. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). +- The current run-owned fixture independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation. World fixture bootstrap skips seeding and prepare/activate refuse before repository effects pending actual World source/Version materialization, association, fixed-preset preparation and holds. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [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/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 9f0d66c0c6..0ddbcfc14b 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 @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick The successor to the guarded World owner stage prepares the closed Game Design fixture-policy receipt and actual Game Session fresh association, catalog and canonical `STARTING` launch. The scheduler completes only that independently read owner phase. Its authenticated fixed World read echoes the original policy request/seal and owner-allocated private identities; it neither writes an admission pointer nor reports an active World. -The obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the same existing default-off fixture configuration. World materialization, holds, first `OPEN`, packaged producer-to-consumer execution and all four genuine handoffs remain open. The selected owner stage freshly passed 2,202 Game Session unit cases with zero skips and retained the prior 39 cross-service cases. Its latest whole-service check remained failed: 260 fresh integration results included nine failures, comprising one remaining 120-character snapshot validator and eight database/initialization failures; container-disposal caller evidence does not settle the initiating database failure. The snapshot guard now matches the installed V34.3 128-character column. After the exact #3203 parent carry, the actual PostgreSQL 121/128-character reservations and SQL rejection above 128 passed, together with Game Session formatting/static checks and the whole World consumer gate. The seven current Human containment/retention cases, including actual pre-1006 COMMITTED/ABORTED history upgraded without changing original fields/bytes/`xmin`, passed in the preceding fresh native gates. These results qualify their stated owner boundaries; a completely successful current-head Game Session native suite, exact published-source CI, review and rebuilt packaged runtime remain separate. Earlier full-carrier results do not qualify these authored postimages. The canonical receipt and phase ordering remain in [Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence). +The obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the existing default-off fixture configuration; World materialization, holds, first `OPEN` and all four genuine handoffs remain open. 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 separate operational dependency-readiness correction remains pending and these results do not prove an admitted `LOOK`. The canonical receipt and phase ordering remain in [Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence). ### Run-owned canonical source handoff 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 c458d010fc..54d2156be6 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -36,7 +36,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 retained initial-admission code includes the typed Game Session workload-only acquire RPC, durable World holds, lifecycle-row termination serialization and fail-closed reconciliation. Earlier coordinator-driven holds and World fixture PREPARING/ACTIVE binding belong to predecessor revisions. The current run-owned coordinator completes canonical Game Session STARTING allocation and independent readback only; World fixture bootstrap, prepare and activate refuse before owner effects. World’s authenticated Game Session read verifies immutable fixture provenance and private allocation identity and grants no 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 retained initial-admission code includes the typed Game Session workload-only acquire RPC, durable World holds, lifecycle-row termination serialization and fail-closed reconciliation. Earlier coordinator-driven holds and World fixture PREPARING/ACTIVE binding belong to predecessor revisions. The current run-owned coordinator completes canonical Game Session STARTING allocation and independent readback only; World fixture bootstrap skips seeding, and prepare/activate refuse before owner effects. The World provider’s authenticated Game Session read verifies immutable fixture provenance and private allocation identity, but has no production lifecycle caller in this phase; it grants no 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. @@ -56,7 +56,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. | World retains lifecycle and initial-admission hold storage and read boundaries. The current run-owned fixture path verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation; fixture bootstrap skips all seeding with a diagnostic, and prepare/activate refuse before materialization, lifecycle, hold or first-OPEN effects. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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) | Current fixture materialization, activation, continuous Account protection, hold acquisition and first OPEN remain unavailable. 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.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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The World provider implements a bounded authenticated Game Session read, but the current lifecycle has no caller because prepare/activate refuse before effects; controlled provider proof is not production execution. Fixture bootstrap skips seeding without granting 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 current run-owned fixture path verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation; fixture bootstrap skips all seeding with a diagnostic, and prepare/activate refuse before materialization, lifecycle, hold or first-OPEN effects. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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) | Current fixture materialization, activation, continuous Account protection, hold acquisition and first OPEN remain unavailable. 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. | 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 cb2bf08918..d6aac679f5 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 @@ -143,8 +143,9 @@ private VerifiedFixture verified() { versionState, launchDescriptor)); var seal = fixture.receipt().fixturePolicySeal(); - if (!"firemud.run-owned-fixture-policy-seal.v1".equals(seal.schema()) - || !"game-design-service".equals(seal.ownerService()) + 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( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index de1d767ee0..246784ac10 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -6,8 +6,6 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.saga.SagaBuilder; import net.firedevops.firemud.common.saga.SagaException; import net.firedevops.firemud.common.saga.SagaRunner; @@ -235,8 +233,8 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace } /** - * Starts or resumes a local fixture launch under a durable, tenant/request-bound owner identity. - * This method has no transport binding; the run-owned fixture coordinator is its only caller. + * Validates verified fixture launch evidence, then refuses before World materialization or first + * OPEN admission. Canonical STARTING allocation is owned by the fixture coordinator. */ @Override @Timed(value = "gamesession.run_owned_initial_launch") @@ -766,48 +764,6 @@ private void requireRunOwnedSourceMatchesRequest( } } - private AuthoredWorldLaunchDescriptorEvidence requireExactAuthoredWorldDescriptorRequest( - StartSessionRequest request, - AuthoredWorldSourceEvidence sourceEvidence, - ResolveLaunchDescriptorResponse response) { - if (response == null) { - throw new IllegalStateException("launch descriptor authority returned no response"); - } - if (response.hasError()) { - return null; - } - if (!response.hasLaunchDescriptor()) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); - } - AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = - new AuthoredWorldLaunchDescriptorEvidence.Request( - sourceEvidence.targetNamespace(), - request.controlPlaneRequestId(), - sourceEvidence.canonicalTenantId(), - sourceEvidence.worldSlug(), - sourceEvidence.operationId(), - sourceEvidence.evidenceDigest(), - request.gameTemplateId(), - false, - null, - false, - null, - false, - null, - false, - null); - try { - return AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( - expectedRequest, response.getLaunchDescriptor()); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException( - "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design response is not bound to the" - + " exact source request", - exception); - } - } - private void validatePublishedAssetProof( long tenantId, long versionId, 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 index 368bdf1847..eb697866f2 100644 --- 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 @@ -62,7 +62,7 @@ BEGIN END; $$; -CREATE TRIGGER game_session_canonical_instance_launch_complete_catalog_identity +CREATE TRIGGER gs_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 index ef093cb726..8595aacdf8 100644 --- 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 @@ -42,20 +42,24 @@ ALTER TABLE game_session_canonical_initial_admission_attempt 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 + 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 reclassifying immutable pre1006 history. 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); + OR (account_protection_evidence_version IS NOT NULL + AND account_protection_evidence_version = 1)) NOT VALID; CREATE UNIQUE INDEX uq_gs_initial_admission_protected_original_attempt ON game_session_canonical_initial_admission_attempt (target_namespace, original_owner_attempt_id) 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 1976055064..35bbe3822c 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 @@ -11,6 +11,7 @@ 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; @@ -53,6 +54,7 @@ import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; @@ -509,6 +511,107 @@ void unprotectedHumanAbortAndCommitRetryLeaveTheExactPendingOwnerUnchanged() { .isZero(); } + @Test + void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { + Fixture fixture = fixture(); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT count(*) FROM pg_trigger WHERE tgrelid = " + + "'game_session_canonical_instance_launch'::regclass " + + "AND tgname = 'gs_canonical_instance_launch_complete_catalog_identity'") + .get(0, Long.class)) + .isEqualTo(1L); + PreparedAdmission prepared = prepareAdmission(fixture); + var request = + initialAdmissionRequest( + prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); + fixture.transactions.executeWithoutResult( + status -> fixture.initialAdmissionRepository.reserve(request)); + 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")); + + // Isolate the declarative constraint in this disposable schema. All other triggers, + // source bindings and constraints stay enabled; each failed write rolls back separately. + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_initial_admission_attempt DISABLE TRIGGER " + + "game_session_canonical_initial_admission_v44_terminal_evidence"); + try { + 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( + "violates check constraint \"chk_gs_initial_admission_terminal_requires_protection\""); + }); + 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 -> { + assertThat(exception.sqlState()).isEqualTo("23514"); + assertThat(exception) + .hasStackTraceContaining( + "violates check constraint \"chk_gs_initial_admission_terminal_requires_protection\""); + }); + } finally { + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_initial_admission_attempt ENABLE TRIGGER " + + "game_session_canonical_initial_admission_v44_terminal_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 pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Exception { for (boolean committed : List.of(true, false)) { @@ -550,6 +653,15 @@ void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Ex "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); 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 a52551f44c..4c08f03959 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 @@ -1009,7 +1009,8 @@ void requireHistoricalRowsRetained() { assertThatThrownBy( () -> catalogRepository.readByRequest(NAMESPACE, preV24Catalog.creationRequestId())) .isInstanceOf( - GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException.class); + GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException.class) + .hasMessage("Exactly one complete catalog policy provenance required"); } IntakeReceipt registerFreshSource() { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java index b0c89c1d91..9217e60db8 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -68,6 +68,7 @@ public final class RunOwnedWorldLaunchEvidenceProvider { private final GameDesignClient gameDesignClient; private final ServiceEndpointsProperties serviceEndpoints; private final GrpcChannelFactory grpcChannelFactory; + private final GameSessionFixtureClientFactory gameSessionFixtureClientFactory; private final String workloadNamespace; private volatile CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient; @@ -83,6 +84,34 @@ public RunOwnedWorldLaunchEvidenceProvider( ServiceEndpointsProperties serviceEndpoints, GrpcChannelFactory grpcChannelFactory, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this( + enabled, + capabilityPath, + sourceReceiptPath, + runId, + composeProjectName, + grpcProperties, + gameDesignClient, + serviceEndpoints, + grpcChannelFactory, + workloadNamespace, + (endpoints, properties, factory, namespace) -> + new CanonicalGameInstanceLaunchAssociationClient( + endpoints, properties, factory, namespace)); + } + + RunOwnedWorldLaunchEvidenceProvider( + boolean enabled, + String capabilityPath, + String sourceReceiptPath, + String runId, + String composeProjectName, + CommonGrpcClientProperties grpcProperties, + GameDesignClient gameDesignClient, + ServiceEndpointsProperties serviceEndpoints, + GrpcChannelFactory grpcChannelFactory, + String workloadNamespace, + GameSessionFixtureClientFactory gameSessionFixtureClientFactory) { this.enabled = enabled; this.capabilityPath = capabilityPath; this.sourceReceiptPath = sourceReceiptPath; @@ -92,6 +121,8 @@ public RunOwnedWorldLaunchEvidenceProvider( this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); this.serviceEndpoints = serviceEndpoints == null ? null : serviceEndpoints.copy(); this.grpcChannelFactory = grpcChannelFactory; + this.gameSessionFixtureClientFactory = + Objects.requireNonNull(gameSessionFixtureClientFactory, "gameSessionFixtureClientFactory"); this.workloadNamespace = workloadNamespace; } @@ -220,7 +251,7 @@ private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFix throw invalidEvidence(); } CanonicalGameInstanceLaunchAssociationClient created = - new CanonicalGameInstanceLaunchAssociationClient( + gameSessionFixtureClientFactory.create( serviceEndpoints, grpcProperties, grpcChannelFactory, workloadNamespace); try { created.init(); @@ -411,6 +442,15 @@ private static InvalidRunOwnedWorldLaunchEvidenceException invalidEvidence() { private record CertificatePins(String leafSha256, String uriSan, String caSha256) {} + @FunctionalInterface + interface GameSessionFixtureClientFactory { + CanonicalGameInstanceLaunchAssociationClient create( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace); + } + private enum VerificationStage { ENABLED, RUN_BINDING, 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 f920b7cdf7..d812f599f0 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 @@ -2,21 +2,41 @@ 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.anyString; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import io.grpc.Context; +import java.io.IOException; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; +import java.security.KeyPair; +import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.Base64; +import java.util.Date; import java.util.HexFormat; import java.util.Set; import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; @@ -28,7 +48,20 @@ import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; @@ -40,12 +73,16 @@ class RunOwnedWorldLaunchEvidenceProviderTest { private static final String CLAIM_DIGEST = controlledClaimDigest(); private static final String OPERATION_ID = RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( - CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "b".repeat(64)) + CLAIM_DIGEST, "fixture-run", "firemud-fixture-run", "a".repeat(64), "c".repeat(64)) .toString(); private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; @TempDir Path temporaryDirectory; + static { + Security.addProvider(new BouncyCastleProvider()); + } + private static String controlledClaimDigest() { try { // Exact controlled fixture bytes; this is not a physical run claim. @@ -245,12 +282,350 @@ void enabledFixtureRejectsCapabilitySymlinkAtFileReadStage(CapturedOutput output assertFileRejectionStoppedBeforeWireParse(output); } + @Test + void fixtureOwnerReadFailureIsContentFreeAndLogsTheReadStage(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + when(fixtureClient.readFixture(any(), anyString())) + .thenThrow(new IllegalStateException("secret-owner-response")); + RunOwnedWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } finally { + provider.closeGameSessionFixtureClient(); + } + + verify(fixtureClient) + .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).close(); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") + .doesNotContain("secret-owner-response", "IllegalStateException", "Caused by:"); + } + + @Test + void validFixtureOwnerReadReachesCompareAndReturnsStartingEvidence(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + when(fixtureClient.readFixture(any(), anyString())) + .thenAnswer(invocation -> fixture.association(invocation.getArgument(0))); + RunOwnedWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); + + RunOwnedWorldLaunchEvidence result; + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + result = provider.requireAuthenticatedEvidence(); + } finally { + provider.closeGameSessionFixtureClient(); + } + + assertThat(result.gameSessionAssociation().currentGameInstanceStatus()) + .isEqualTo( + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING); + verify(fixtureClient) + .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).close(); + assertThat(output) + .doesNotContain("Run-owned World launch evidence verification rejected", "Caused by:"); + } + + // The controlled owner-client return is valid for its alternate policy; the real common client + // rejects its different request digest before this provider comparison boundary. + @Test + void validAlternateFixtureAssociationIsRejectedAtCompareStage(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + RunOwnedWorldLaunchEvidence alternateFixture = + fixtureEvidence( + false, + fixture.gameSessionLeafSha256(), + fingerprint(fixture.pki().worldManagementCertificate()), + fingerprint(fixture.pki().caCertificate()), + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6e")); + when(fixtureClient.readFixture(any(), anyString())) + .thenReturn(alternateFixture.gameSessionAssociation()); + RunOwnedWorldLaunchEvidenceProvider provider = + provider( + fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } finally { + provider.closeGameSessionFixtureClient(); + } + + verify(fixtureClient) + .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); + verify(fixtureClient).close(); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_COMPARE") + .doesNotContain( + "fixture-run", "firemud-fixture-run", "IllegalArgumentException", "Caused by:"); + } + + @Test + void fixtureClientInitializationFailureClosesPartialClient(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + doThrow(new IOException("private-init-detail")).when(fixtureClient).init(); + RunOwnedWorldLaunchEvidenceProvider provider = + new RunOwnedWorldLaunchEvidenceProvider( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + "fixture-run", + "firemud-fixture-run", + fixture.tlsProperties(), + gameDesignClient, + fixture.endpoints(), + new GrpcChannelFactory(), + "dev", + (endpoints, tls, channelFactory, namespace) -> fixtureClient); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verify(fixtureClient).init(); + verify(fixtureClient).close(); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") + .doesNotContain("private-init-detail", "IOException", "Caused by:"); + } + + @Test + void fixtureClientMissingConfigurationFailsAtReadStageWithoutCreatingClient(CapturedOutput output) + throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + RunOwnedWorldLaunchEvidenceProvider provider = + provider(fixture, gameDesignClient, null, null, fixture.tlsProperties(), factory); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verifyNoInteractions(factory); + assertThat(output) + .contains( + "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") + .doesNotContain("fixture-run", "firemud-fixture-run"); + } + private static void assertFileRejectionStoppedBeforeWireParse(CapturedOutput output) { assertThat(output) .contains("Run-owned World launch evidence verification rejected; stage=CAPABILITY_FILE") .doesNotContain("stage=WIRE_PARSE"); } + private RunOwnedWorldLaunchEvidenceProvider provider( + ProviderFixture fixture, + GameDesignClient gameDesignClient, + CanonicalGameInstanceLaunchAssociationClient fixtureClient, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties) { + return provider( + fixture, + gameDesignClient, + fixtureClient, + endpoints, + tlsProperties, + (ignoredEndpoints, ignoredTls, ignoredChannelFactory, ignoredNamespace) -> fixtureClient); + } + + private RunOwnedWorldLaunchEvidenceProvider provider( + ProviderFixture fixture, + GameDesignClient gameDesignClient, + CanonicalGameInstanceLaunchAssociationClient fixtureClient, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory) { + return new RunOwnedWorldLaunchEvidenceProvider( + true, + fixture.capabilityPath().toString(), + fixture.receiptPath().toString(), + "fixture-run", + "firemud-fixture-run", + tlsProperties, + gameDesignClient, + endpoints, + new GrpcChannelFactory(), + "dev", + factory); + } + + private ProviderFixture providerFixture() throws Exception { + Path directory = + Files.createDirectories(temporaryDirectory.resolve("provider-" + UUID.randomUUID())); + TestPki pki = TestPki.create(); + String gameSessionLeaf = fingerprint(pki.gameSessionCertificate()); + String worldManagementLeaf = fingerprint(pki.worldManagementCertificate()); + String caFingerprint = fingerprint(pki.caCertificate()); + RunOwnedWorldLaunchEvidence evidence = + fixtureEvidence(false, gameSessionLeaf, worldManagementLeaf, caFingerprint); + Path capability = directory.resolve("capability.json"); + Path receipt = directory.resolve("receipt.json"); + Files.writeString(capability, capabilityJson(evidence.capability()), StandardCharsets.UTF_8); + Files.writeString(receipt, receiptJson(evidence.sourceReceipt()), StandardCharsets.UTF_8); + Set immutablePermissions = + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.GROUP_READ, + PosixFilePermission.OTHERS_READ); + Files.setPosixFilePermissions(capability, immutablePermissions); + Files.setPosixFilePermissions(receipt, immutablePermissions); + Path worldCertificate = directory.resolve("world-management.crt"); + Path caCertificate = directory.resolve("ca.crt"); + Files.writeString( + worldCertificate, pem(pki.worldManagementCertificate()), StandardCharsets.UTF_8); + Files.writeString(caCertificate, pem(pki.caCertificate()), StandardCharsets.UTF_8); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(worldCertificate.toString()); + tls.setCaCert(caCertificate.toString()); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("localhost:6565"); + return new ProviderFixture(evidence, capability, receipt, pki, tls, endpoints, gameSessionLeaf); + } + + private static GameDesignClient mockDescriptorReader(RunOwnedWorldLaunchEvidence evidence) { + GameDesignClient client = mock(GameDesignClient.class); + var message = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toLaunchDescriptorMessage(evidence.launchDescriptor()); + when(client.getLaunchDescriptor(any())) + .thenReturn(new LaunchDescriptorReadback(message, evidence.launchDescriptor())); + return client; + } + + private static String capabilityJson( + RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { + return """ + {"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"}%n\ + """ + .formatted( + 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 String receiptJson( + RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt) { + var source = receipt.sourceEvidence(); + var creation = receipt.creationEvidence(); + var launch = receipt.launchReadEvidence(); + var seal = receipt.fixturePolicySeal(); + 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"},"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"}}%n\ + """ + .formatted( + receipt.schema(), + receipt.runId(), + receipt.composeProjectName(), + receipt.fixtureOperationId(), + receipt.ownerService(), + receipt.gameSessionUriSan(), + receipt.gameSessionLeafSha256(), + receipt.caCertificateSha256(), + receipt.worldManagementUriSan(), + receipt.worldManagementLeafSha256(), + 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(), + launch.schema(), + launch.gameTemplateId(), + base64(launch.publishedReleaseBundle().toByteArray()), + base64(launch.versionAssetArtifactState().toByteArray()), + base64(launch.versionState().toByteArray()), + base64(launch.launchDescriptor().toByteArray()), + creation.schemaVersion(), + creation.targetNamespace(), + creation.creationRequestId(), + creation.operationId(), + creation.requestDigest(), + creation.canonicalTenantId(), + creation.sourceGameRowId(), + creation.sourceGameTenantKey(), + creation.provenanceKind(), + creation.evidenceDigest(), + seal.schema(), + seal.ownerService(), + seal.operationId(), + seal.requestDigest(), + seal.evidenceDigest()); + } + + private static String base64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String pem(X509Certificate certificate) throws Exception { + return "-----BEGIN CERTIFICATE-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(certificate.getEncoded()) + + "\n-----END CERTIFICATE-----\n"; + } + + private static String fingerprint(X509Certificate certificate) throws Exception { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } + private static PreparedWorldInstanceRequest request(String patch, String remap) { return new PreparedWorldInstanceRequest( 142L, @@ -273,9 +648,38 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { } private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSeal) { - UUID registrationId = UUID.fromString(OPERATION_ID); + return fixtureEvidence(mismatchedSeal, "a".repeat(64), "b".repeat(64), "c".repeat(64)); + } + + private static RunOwnedWorldLaunchEvidence fixtureEvidence( + boolean mismatchedSeal, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256) { + return fixtureEvidence( + mismatchedSeal, + gameSessionLeafSha256, + worldManagementLeafSha256, + caCertificateSha256, + UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d")); + } + + private static RunOwnedWorldLaunchEvidence fixtureEvidence( + boolean mismatchedSeal, + String gameSessionLeafSha256, + String worldManagementLeafSha256, + String caCertificateSha256, + UUID canonicalTenantId) { + String operationId = + RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( + CLAIM_DIGEST, + "fixture-run", + "firemud-fixture-run", + gameSessionLeafSha256, + caCertificateSha256) + .toString(); + UUID registrationId = UUID.fromString(operationId); UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); - UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); String requestDigest = AuthoredWorldSourceDigest.requestDigest( "dev", registrationId, canonicalTenantId, "fixture-tenant", "demo", "Demo World"); @@ -310,7 +714,7 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSea var descriptorRequest = new AuthoredWorldLaunchDescriptorEvidence.Request( "dev", - OPERATION_ID, + operationId, canonicalTenantId, "demo", sourceOperationId, @@ -373,10 +777,10 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSea RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, "fixture-run", "firemud-fixture-run", - OPERATION_ID, + operationId, 42L, 17L, - 9L, + 1L, "demo", "Demo World", "production", @@ -386,11 +790,11 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSea false, "SHARED", "ALLOW_NEW", - "a".repeat(64), + gameSessionLeafSha256, RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - "b".repeat(64), + caCertificateSha256, RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), + worldManagementLeafSha256, CLAIM_DIGEST); // Controlled constructor data remains untrusted; these commitments do not prove owner writes. UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); @@ -434,10 +838,10 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSea new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, - UUID.fromString(OPERATION_ID), + UUID.fromString(operationId), policyRequestDigest, RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - UUID.fromString(OPERATION_ID), policyRequestDigest)); + UUID.fromString(operationId), policyRequestDigest)); UUID otherSealOperation = UUID.fromString("20000000-0000-4000-8000-000000000012"); var receiptSeal = mismatchedSeal @@ -454,13 +858,13 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSea RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, "fixture-run", "firemud-fixture-run", - OPERATION_ID, + operationId, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - "a".repeat(64), - "b".repeat(64), + gameSessionLeafSha256, + caCertificateSha256, RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), + worldManagementLeafSha256, source, launchRead, creation, @@ -471,7 +875,7 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSea UUID readRequestId = UUID.fromString("5d85bfbe-ae28-4a86-a72a-57471a5761bf"); var associationRequest = new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( - readRequestId, "dev", UUID.fromString(OPERATION_ID), policySeal.evidenceDigest()); + readRequestId, "dev", UUID.fromString(operationId), policySeal.evidenceDigest()); var association = new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( associationRequest, @@ -493,10 +897,10 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSea descriptor, new byte[] {1}, new byte[] {2}, - "a".repeat(64), + gameSessionLeafSha256, RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), - "b".repeat(64), + worldManagementLeafSha256, + caCertificateSha256, association); } @@ -520,4 +924,139 @@ private static RunOwnedWorldLaunchEvidenceProvider provider( null, "dev"); } + + private record ProviderFixture( + RunOwnedWorldLaunchEvidence evidence, + Path capabilityPath, + Path receiptPath, + TestPki pki, + CommonGrpcClientProperties tlsProperties, + ServiceEndpointsProperties endpoints, + String gameSessionLeafSha256) { + private CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult association( + CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request) { + var original = evidence.gameSessionAssociation(); + return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( + request, + original.gameSessionTenantId(), + original.gameInstanceId(), + original.canonicalTenantId(), + original.gameInstanceUuid(), + original.canonicalVersionId(), + original.canonicalRealmId(), + original.playableStateNamespaceId(), + original.catalogRevision(), + original.currentGameInstanceStatus(), + original.currentRowVersion(), + original.fixturePolicyRequestBytes(), + original.fixturePolicySeal()); + } + + private PeerContext attachGameSessionPeer() throws Exception { + Context context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, + "dev", + "game-session-service")) + .withValue( + GrpcPeerCertificateEvidence.CONTEXT_KEY, + GrpcPeerCertificateEvidence.fromCertificate(pki.gameSessionCertificate()) + .orElseThrow()); + return new PeerContext(context.attach()); + } + } + + private record PeerContext(io.grpc.Context previous) implements AutoCloseable { + @Override + public void close() { + Context.current().detach(previous); + } + } + + private record TestPki( + X509Certificate caCertificate, + X509Certificate worldManagementCertificate, + X509Certificate gameSessionCertificate) { + private static TestPki create() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair caKey = generator.generateKeyPair(); + X500Name caName = new X500Name("CN=World provider test CA"); + X509Certificate ca = issueCertificate(caName, caKey.getPublic(), caName, caKey, true, null); + X509Certificate world = + issueLeaf( + caName, + caKey, + generator, + "world-management-service", + RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN); + X509Certificate gameSession = + issueLeaf( + caName, + caKey, + generator, + "game-session-service", + RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN); + return new TestPki(ca, world, gameSession); + } + + private static X509Certificate issueLeaf( + X500Name caName, + KeyPair caKey, + KeyPairGenerator generator, + String service, + String workloadUri) + throws Exception { + KeyPair leafKey = generator.generateKeyPair(); + GeneralNames names = + new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri)); + return issueCertificate( + new X500Name("CN=" + service), leafKey.getPublic(), caName, caKey, false, names); + } + + private static X509Certificate issueCertificate( + X500Name subject, + java.security.PublicKey publicKey, + X500Name issuer, + KeyPair issuerKey, + boolean ca, + GeneralNames subjectAltNames) + throws Exception { + Instant now = Instant.now().minusSeconds(60); + JcaX509v3CertificateBuilder builder = + new JcaX509v3CertificateBuilder( + issuer, + BigInteger.valueOf(Math.abs(UUID.randomUUID().getMostSignificantBits()) + 1L), + Date.from(now), + Date.from(now.plusSeconds(86400L)), + subject, + publicKey); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); + if (ca) { + builder.addExtension( + Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + } else { + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); + } + return new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate( + builder.build( + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuerKey.getPrivate()))); + } + } } From 80a8622dff8ae2fd1e29d855a8ed4c500c86be20 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:54:37 +1300 Subject: [PATCH 07/26] Bind fixture provenance and exercise receipt parser refusals --- ...OwnedInitialAdmissionFixtureWireCodec.java | 1 + ...dInitialAdmissionFixtureWireCodecTest.java | 87 ++++++++++++------- ...essionCanonicalRealmCatalogRepository.java | 9 -- 3 files changed, 56 insertions(+), 41 deletions(-) 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 99101b0a72..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 @@ -393,6 +393,7 @@ private static void requireFixtureBinding( || !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()) 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 cc0cb0678f..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 @@ -146,32 +146,44 @@ void rejectsRecursiveUnknownProtoFieldsAndDescriptorProjectionMismatches() { launchDescriptor().getAuthoredWorldBinding().toBuilder() .setUnknownFields(UNKNOWN_FIELD_SET)) .build(); + assertInvalidReceipt(receiptWithSubstitutedDescriptor(descriptorWithNestedUnknownFields)); assertInvalidReceipt( - () -> - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorWithNestedUnknownFields)); - - assertInvalidReceipt( - () -> - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorFor(12L, bundle().getId(), bundle().getPublishedReleaseBundleRef()))); + receiptWithSubstitutedDescriptor( + descriptorFor(12L, bundle().getId(), bundle().getPublishedReleaseBundleRef()))); assertInvalidReceipt( - () -> - sourceReceiptJson( - sourceEvidence(), - bundle(), - artifactState(), - versionState(), - descriptorFor( - bundle().getVersionId(), bundle().getId(), "different-owner-release-ref"))); + 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(), + 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 @@ -333,11 +345,6 @@ private static void assertInvalidCapabilityBytes(byte[] bytes) { .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); } - private static void assertInvalidReceipt(java.util.function.Supplier json) { - assertThatThrownBy(() -> parseSourceReceipt(json.get(), capability())) - .isInstanceOf(IllegalArgumentException.class); - } - private static void assertInvalidReceipt(String json) { assertInvalidReceiptBytes(json.getBytes(StandardCharsets.UTF_8)); } @@ -370,6 +377,14 @@ 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, @@ -456,6 +471,10 @@ private static FreshTenantCreationEvidence creationEvidence() { } 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; @@ -482,7 +501,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { worldDisplayName, 13L, "7", - "NEW_GAME_ROW"); + provenanceKind); return new AuthoredWorldSourceEvidence( 1, namespace, @@ -495,7 +514,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence() { worldDisplayName, 13L, "7", - "NEW_GAME_ROW", + provenanceKind, evidenceDigest); } @@ -556,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-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 8218a475b2..c4d79b4f8e 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 @@ -138,15 +138,6 @@ public GameSessionCanonicalRealmCatalogRepository(DSLContext dsl) { * The returned opaque prepared value can only be constructed by this repository and is verified * again against the locked immutable owner rows during creation. */ - @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) - public PreparedInitialPublicProduction prepareInitialPublicProduction( - CreateCanonicalRealmCatalogRequest request) { - Objects.requireNonNull(request, "request"); - requireCommittedRead(); - throw new InvalidCatalogEvidenceException( - "Complete immutable published policy evidence is required"); - } - @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) public PreparedInitialPublicProduction prepareInitialPublicProduction( CreateCanonicalRealmCatalogRequest request, From bfece7a30d2b38b8fde0e7788eb1fb9f386f0844 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:30:29 +1300 Subject: [PATCH 08/26] Preserve original launch migrations and tighten guards forward --- ...e-session-runtime-and-tick-coordination.md | 4 +- ...anonical_launch_exact_catalog_identity.sql | 2 +- ..._initial_admission_terminal_protection.sql | 10 +- ...erminal_protection_history_safe_guards.sql | 140 +++++ ...ialAdmissionRepositoryIntegrationTest.java | 493 ++++++++++++++---- 5 files changed, 544 insertions(+), 105 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1011__canonical_launch_and_terminal_protection_history_safe_guards.sql 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 0ddbcfc14b..1e8e23ba4a 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 @@ -10,7 +10,9 @@ This is a non-normative implementation tracker for Game Session runtime and tick The successor to the guarded World owner stage prepares the closed Game Design fixture-policy receipt and actual Game Session fresh association, catalog and canonical `STARTING` launch. The scheduler completes only that independently read owner phase. Its authenticated fixed World read echoes the original policy request/seal and owner-allocated private identities; it neither writes an admission pointer nor reports an active World. -The obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the existing default-off fixture configuration; World materialization, holds, first `OPEN` and all four genuine handoffs remain open. 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 separate operational dependency-readiness correction remains pending and these results do not prove 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 obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the existing default-off fixture configuration; World materialization, holds, first `OPEN` and all four genuine handoffs remain open. 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. 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 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 index eb697866f2..368bdf1847 100644 --- 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 @@ -62,7 +62,7 @@ BEGIN END; $$; -CREATE TRIGGER gs_canonical_instance_launch_complete_catalog_identity +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 index 8595aacdf8..ef093cb726 100644 --- 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 @@ -42,24 +42,20 @@ ALTER TABLE game_session_canonical_initial_admission_attempt 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 + 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 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 reclassifying immutable pre1006 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; + 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) 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/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 35bbe3822c..76e1b8d323 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 @@ -7,7 +7,10 @@ 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; @@ -514,13 +517,13 @@ void unprotectedHumanAbortAndCommitRetryLeaveTheExactPendingOwnerUnchanged() { @Test void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { Fixture fixture = fixture(); + migration(fixture, null).validate(); + launchGuardProjection(fixture, true); assertThat( fixture .dsl .fetchSingle( - "SELECT count(*) FROM pg_trigger WHERE tgrelid = " - + "'game_session_canonical_instance_launch'::regclass " - + "AND tgname = 'gs_canonical_instance_launch_complete_catalog_identity'") + "SELECT count(*) FROM flyway_schema_history WHERE version = '1011' AND success") .get(0, Long.class)) .isEqualTo(1L); PreparedAdmission prepared = prepareAdmission(fixture); @@ -594,6 +597,64 @@ void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { .hasStackTraceContaining( "violates check constraint \"chk_gs_initial_admission_terminal_requires_protection\""); }); + 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( + "violates check constraint \"chk_gs_initial_admission_account_protection_evidence_complete\""); + }); + 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 -> { + assertThat(exception.sqlState()).isEqualTo("23514"); + assertThat(exception) + .hasStackTraceContaining( + "violates check constraint \"chk_gs_initial_admission_account_protection_evidence_complete\""); + }); + } } finally { fixture.dsl.execute( "ALTER TABLE game_session_canonical_initial_admission_attempt ENABLE TRIGGER " @@ -612,104 +673,279 @@ void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { .isZero(); } + @Test + void originalProtectionMigrationBytesRemainUnchanged() throws Exception { + assertOriginalMigrationBlob( + "V1005__canonical_launch_exact_catalog_identity.sql", + "368bdf18472699e82f1bccd8b956b62f058b2a12"); + assertOriginalMigrationBlob( + "V1006__canonical_initial_admission_terminal_protection.sql", + "ef093cb7262929d9e962f717220088e378f21e6d"); + } + + 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); + } + @Test void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Exception { - 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 schema = predecessor.dsl.fetchSingle("SELECT current_schema()").get(0, String.class); - var migration = - Flyway.configure() - .dataSource(Objects.requireNonNull(predecessor.transactionManager.getDataSource())) - .schemas(schema) - .defaultSchema(schema) - .table("flyway_schema_history") - .locations(MIGRATION_LOCATION) - .load(); - migration.migrate(); - 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(); + 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, null).migrate(); + migration(predecessor, null).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); + } + 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), null)); + assertHumanProtectionUnavailable( + () -> + predecessor.initialAdmissionRepository.abort( + request, null, "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); } - assertThat( - predecessor + } + } + + @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 - .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), null)); - assertHumanProtectionUnavailable( - () -> - predecessor.initialAdmissionRepository.abort( - request, null, "Current Human retry remains unprotected")); - assertThat(predecessorAttemptProjection(predecessor, request)).isEqualTo(originalAttempt); - assertThat(pointerAndAuditProjection(predecessor)).isEqualTo(originalPointerAndAudit); - assertThat(predecessorSourceProjection(predecessor)).isEqualTo(originalSources); + .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 + .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); + } + + 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. */ @@ -1250,6 +1486,71 @@ private static String pointerAndAuditProjection(Fixture fixture) { .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 + .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); } From 493990e46f6f98785ed9f834633d97ca68c56022 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:18:35 +1300 Subject: [PATCH 09/26] Fix fixture owner injection, RPC errors and decisive parser proof --- design/project-management/ai-observations.md | 3 +- .../data/RunOwnedFixtureLaunchReadback.java | 9 +- .../data/RunOwnedFixturePolicyProducer.java | 2 +- .../gamedesign/data/TestDataSeeder.java | 8 +- .../data/TestDataSeederIntegrationTest.java | 6 +- .../gamedesign/data/TestDataSeederTest.java | 19 +- .../GameSessionControlPlaneGrpcService.java | 31 ++- ...InitialAdmissionFixtureCapabilityTest.java | 230 +++++++----------- ...eLaunchAssociationReadGrpcServiceTest.java | 28 +++ 9 files changed, 166 insertions(+), 170 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fdfdb3479b..ea7fb8a3c3 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -272,6 +272,7 @@ Entry format: - 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. The database still reported the lease live, so the intended post-expiry race was not established. + - 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. 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 20b0a98459..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,9 +51,7 @@ public class RunOwnedFixtureLaunchReadback { private final VersionService versionService; private final VersionAssetArtifactService artifactService; private final LaunchDescriptorService launchDescriptorService; - - @org.springframework.beans.factory.annotation.Autowired - private net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + private final net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository creationRepository; @SuppressFBWarnings( @@ -68,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; @@ -77,6 +77,7 @@ public RunOwnedFixtureLaunchReadback( this.versionService = versionService; this.artifactService = artifactService; this.launchDescriptorService = launchDescriptorService; + this.creationRepository = creationRepository; } @Transactional(propagation = Propagation.MANDATORY, readOnly = true) 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 index de329a7415..8b67423952 100644 --- 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 @@ -18,7 +18,7 @@ /** Fixed-capability fixture authority only; never emits human selected-publication evidence. */ @Service -final class RunOwnedFixturePolicyProducer { +public final class RunOwnedFixturePolicyProducer { private static final String SCHEMA = "firemud.run-owned-fixture-policy-seal.v1"; private static final String OWNER = "game-design-service"; private final DSLContext dsl; 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 c9956062a4..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,13 +83,9 @@ public class TestDataSeeder implements ApplicationRunner { private final VersionAssetArtifactRepository versionAssetArtifactRepository; private final RunOwnedFixtureLaunchReadback launchReadback; private final ObjectMapper objectMapper; - - @org.springframework.beans.factory.annotation.Autowired - private net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository + private final net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository creationRepository; - - @org.springframework.beans.factory.annotation.Autowired - private RunOwnedFixturePolicyProducer fixturePolicyProducer; + private final RunOwnedFixturePolicyProducer fixturePolicyProducer; @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") private boolean initialAdmissionFixtureEnabled; 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 c0066cc8a3..bdc9fd89d2 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 @@ -1491,7 +1491,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/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 03cf9f6a44..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 @@ -60,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 @@ -75,7 +80,9 @@ void setup() { publishedReleaseBundleRepository, versionAssetArtifactRepository, launchReadback, - new ObjectMapper()); + new ObjectMapper(), + creationRepository, + fixturePolicyProducer); } @Test @@ -310,8 +317,8 @@ void independentlyReadsExactCommittedCreationAndRejectsChangedOrMissingOwnerEvid org.mockito.Mockito.mock( net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService.class), org.mockito.Mockito.mock( - net.firedevops.firemud.gamedesign.service.LaunchDescriptorService.class)); - ReflectionTestUtils.setField(readback, "creationRepository", creationRepository); + 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(); @@ -546,12 +553,6 @@ void rejectsWrongOwnerAccountBeforeAnySeederOwnerWrites(@TempDir Path directory) ReflectionTestUtils.setField(seeder, "caCertPath", directory.resolve("ca.crt").toString()); ReflectionTestUtils.setField(seeder, "workloadNamespace", "dev"); - var creationRepository = - mock(net.firedevops.firemud.gamedesign.repository.GameTenantCreationRepository.class); - var fixturePolicyProducer = mock(RunOwnedFixturePolicyProducer.class); - ReflectionTestUtils.setField(seeder, "creationRepository", creationRepository); - ReflectionTestUtils.setField(seeder, "fixturePolicyProducer", fixturePolicyProducer); - assertThatThrownBy(() -> seeder.run(new DefaultApplicationArguments(new String[] {}))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("does not match the configured Game Design scope"); 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 dcf1eef8b2..9b08c9b2b6 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 @@ -327,14 +327,26 @@ public void getRunOwnedFixtureLaunchAssociation( "Fixture launch owner read cannot run inside an ambient transaction"); } if (request == null) { - throw new IllegalArgumentException("Fixture launch owner request is required"); + 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 = runOwnedFixtureCoordinator.loadFixedVerifiedEvidenceForWorldPeer(); - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest selector = - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request); + 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 @@ -345,8 +357,11 @@ public void getRunOwnedFixtureLaunchAssociation( .fixturePolicySeal() .evidenceDigest() .equals(selector.expectedFixturePolicyEvidenceDigest())) { - throw new IllegalArgumentException( - "Fixture launch owner selector differs from the fixed verified source"); + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Fixture launch owner selector is invalid") + .asRuntimeException()); + return; } var launch = runOwnedFixtureCoordinator.readFixedFixtureLaunch(evidence); @@ -374,10 +389,10 @@ public void getRunOwnedFixtureLaunchAssociation( Status.PERMISSION_DENIED .withDescription("Fixture launch owner read is not authorized") .asRuntimeException()); - } catch (IllegalArgumentException malformed) { + } catch (IllegalArgumentException invalidOwnerState) { responseObserver.onError( - Status.INVALID_ARGUMENT - .withDescription("Fixture launch owner selector is invalid") + Status.FAILED_PRECONDITION + .withDescription("Exact fixed fixture launch owner read is unavailable") .asRuntimeException()); } catch (IllegalStateException unavailable) { responseObserver.onError( 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 baefbfa134..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 @@ -203,33 +203,26 @@ void rejectsOpenDuplicateMismatchedAndMalformedSourceReceiptFields() { assertInvalidSourceReceipt(json.replace(canonicalBundle, nonCanonicalBundle)); assertInvalidSourceReceipt(json.replace(canonicalBundle, encode(new byte[] {10, 5}))); assertInvalidSourceReceipt( - () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle().toBuilder() - .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") - .build())); + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", + launchBundle().toBuilder() + .setCanonicalTenantId("11111111-1111-4111-8111-111111111111") + .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( @@ -240,9 +233,8 @@ void rejectsLaunchDescriptorThatDoesNotMatchOwnerReadSnapshots() { .build()); assertInvalidSourceReceipt( - () -> - validSourceReceiptJson( - source, bundle, artifactState, versionState, mismatchedDescriptor)); + sourceReceiptWithLaunchReadEvidenceProto( + "launchDescriptorBase64", mismatchedDescriptor.toByteArray())); } @Test @@ -255,71 +247,62 @@ void rejectsOwnerReadProjectionScopeAndStateMismatches() { () -> validSourceReceiptJson().replace("\"gameTemplateId\":17", "\"gameTemplateId\":18"), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setTenantId("8").build(), - launchVersionState()), + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder().setTenantId("8").build().toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setVersionId(12L).build(), - launchVersionState()), + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder().setVersionId(12L).build().toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setStateEpoch(0L).build(), - launchVersionState()), + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder().setStateEpoch(0L).build().toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", launchArtifactState().toBuilder() .setArtifactState( net.firedevops.firemud.gamedesign.v1.ArtifactState .ARTIFACT_STATE_TOMBSTONED) - .build(), - launchVersionState()), + .build() + .toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", launchArtifactState().toBuilder() .setManifestHash("sha256:" + "c".repeat(64)) - .build(), - launchVersionState()), + .build() + .toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setTenantId("8").build()), + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder().setTenantId("8").build().toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setVersionId(12L).build()), + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder().setVersionId(12L).build().toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", launchBundle().toBuilder() .setCanonicalVersionId("not-a-canonical-uuid") - .build()), + .build() + .toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState().toBuilder().setUnknownFields(unknownFields).build(), - launchVersionState()), + sourceReceiptWithLaunchReadEvidenceProto( + "versionAssetArtifactStateBase64", + launchArtifactState().toBuilder() + .setUnknownFields(unknownFields) + .build() + .toByteArray()), () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle(), - launchArtifactState(), - launchVersionState().toBuilder().setUnknownFields(unknownFields).build())); + sourceReceiptWithLaunchReadEvidenceProto( + "versionStateBase64", + launchVersionState().toBuilder() + .setUnknownFields(unknownFields) + .build() + .toByteArray())); invalidReceipts.forEach( RunOwnedInitialAdmissionFixtureCapabilityTest::assertInvalidSourceReceipt); @@ -327,19 +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 @@ -358,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 @@ -374,7 +349,9 @@ void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { .setUnknownFields(unknownFields) .build()) .build(); - assertInvalidSourceReceipt(() -> validSourceReceiptJson(sourceEvidence(), nestedUnknownBundle)); + assertInvalidSourceReceipt( + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", nestedUnknownBundle.toByteArray())); var nestedUnknownParticipant = launchBundle().toBuilder() .addParticipantDigests( @@ -383,12 +360,12 @@ void rejectsUnknownProtobufFieldsRecursivelyInOwnerReadEvidence() { .build()) .build(); assertInvalidSourceReceipt( - () -> validSourceReceiptJson(sourceEvidence(), nestedUnknownParticipant)); + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", nestedUnknownParticipant.toByteArray())); assertInvalidSourceReceipt( - () -> - validSourceReceiptJson( - sourceEvidence(), - launchBundle().toBuilder().setUnknownFields(unknownFields).build())); + sourceReceiptWithLaunchReadEvidenceProto( + "publishedReleaseBundleBase64", + launchBundle().toBuilder().setUnknownFields(unknownFields).build().toByteArray())); } @Test @@ -536,38 +513,11 @@ 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 = @@ -730,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, @@ -798,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); @@ -942,15 +894,13 @@ private static void assertInvalidSourceReceipt(String json) { } private static void assertInvalidSourceReceipt(Supplier receiptJson) { + byte[] bytes = receiptJson.get().getBytes(java.nio.charset.StandardCharsets.UTF_8); assertThatThrownBy( () -> RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( - receiptJson.get().getBytes(java.nio.charset.StandardCharsets.UTF_8), - RUN_ID, - PROJECT_NAME, - capability(), - pins())) - .isInstanceOf(IllegalArgumentException.class); + bytes, RUN_ID, PROJECT_NAME, capability(), pins())) + .isInstanceOf( + RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); } private static void assertInvalidSourceReceiptBytes(byte[] bytes) { 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 index 634e202804..1da48f7e0c 100644 --- 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 @@ -136,6 +136,18 @@ void loadsFixedWorldEvidenceBeforeRejectingUnknownRequestFieldsWithoutReadingLau 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); @@ -152,6 +164,22 @@ void rejectsChangedSelectorAfterLoadingFixedEvidenceAndBeforeLaunchOwnerRead() { 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); From 8822bdff57c74f39b49c8b9f74a4ef5897af323f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:52:26 +1300 Subject: [PATCH 10/26] Clarify launch fixture source capability and coordinator proof --- .../microservices/world-management-service/runtime-and-data.md | 2 +- design/architecture/system-architecture-testing.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 4190123aa8..94675a4035 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -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 current run-owned fixture independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation. World fixture bootstrap skips seeding and prepare/activate refuse before repository effects pending actual World source/Version materialization, association, fixed-preset preparation and holds. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). +- The prepared run-owned fixture provider independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation as source capability; no current production lifecycle caller invokes those reads. World fixture bootstrap skips seeding and prepare/activate refuse before repository effects pending actual World source/Version materialization, association, fixed-preset preparation and holds. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [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 f6b4bb721b..ed81f9b5e7 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -189,7 +189,7 @@ The immutable source receipt has exactly fourteen envelope fields, including `cr 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 trusted data-package coordinator validates this complete fixed capability and receipt before creating the typed fixture carrier. Preflight exact-compares authenticated `ResolveLaunchDescriptor` with the retained projections without invoking the three production release/version/artifact read RPCs. 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. +Game Session's trusted data-package coordinator validates this complete fixed capability and receipt before creating the typed fixture carrier. 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. From 7bf0e6a0fad825b79c37d3704c4debb1adcae704 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:07:05 +1300 Subject: [PATCH 11/26] Remove orphaned unavailable admission test helpers --- ...eCanonicalInitialAdmissionServiceTest.java | 113 +----------------- .../impl/GameInstanceServiceImplTest.java | 81 ------------- 2 files changed, 1 insertion(+), 193 deletions(-) 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 a071e9dd26..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 @@ -16,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; @@ -36,7 +35,7 @@ class DatabaseCanonicalInitialAdmissionServiceTest { mock(GameSessionCanonicalAdmissionPointerRepository.class); private final CanonicalInitialAdmissionWorldVerifier worldVerifier = mock(CanonicalInitialAdmissionWorldVerifier.class); - private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(0); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); private final DatabaseCanonicalInitialAdmissionService service = new DatabaseCanonicalInitialAdmissionService( repository, pointerRepository, worldVerifier, transactionManager); @@ -106,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"); @@ -174,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( @@ -230,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); } @@ -289,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) { @@ -314,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 71e9694b54..c8a976c581 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 @@ -30,7 +30,6 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; @@ -48,7 +47,6 @@ import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; -import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.junit.jupiter.api.BeforeEach; @@ -1780,85 +1778,6 @@ private void configureWorldActivation() { .build()); } - private AtomicReference configureRunOwnedWorld( - StartSessionRequest request) { - AtomicReference worldState = new AtomicReference<>(); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenAnswer( - invocation -> { - if (worldState.get() == null) { - worldState.set( - runOwnedWorldSnapshot( - request, - invocation.getArgument(1, Long.class), - 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING, - runOwnedBundleRef(request.tenantId()))); - } - return PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance(worldState.get()) - .build(); - }); - when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) - .thenAnswer( - invocation -> - GetWorldInstanceLifecycleResponse.newBuilder() - .setWorldInstance(worldState.get()) - .build()); - when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> { - WorldInstanceLifecycleSnapshot active = - runOwnedWorldSnapshot( - request, - invocation.getArgument(1, Long.class), - invocation.getArgument(2, Long.class) + 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, - runOwnedBundleRef(request.tenantId())); - worldState.set(active); - return net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance(active) - .build(); - }); - return worldState; - } - - private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( - StartSessionRequest request, - long gameInstanceId, - long lifecycleEpoch, - WorldInstanceLifecycleStatus status, - String publishedReleaseBundleRef) { - return WorldInstanceLifecycleSnapshot.newBuilder() - .setTenantId(Long.toString(request.tenantId())) - .setGameInstanceId(Long.toString(gameInstanceId)) - .setGameTemplateId(Long.toString(request.gameTemplateId())) - .setControlPlaneRequestId(request.controlPlaneRequestId()) - .setLaunchDescriptorId("launch-descriptor-fixture-11") - .setVersionId("11") - .setReleaseBundleId("77") - .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef(publishedReleaseBundleRef) - .setVersionStateEpoch(77L) - .setLifecycleEpoch(lifecycleEpoch) - .setStatus(status) - .build(); - } - private GameInstance persistExisting( Long id, Long tenantId, From 683f5079de05cb9a46d06afaef9d480280d637a3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:50:46 +1300 Subject: [PATCH 12/26] Prove fixture-enabled seeder first-entry commit and rollback --- .../data/TestDataSeederIntegrationTest.java | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) 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 bdc9fd89d2..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 @@ -182,7 +182,7 @@ void fixtureRefusesExistingUnownedDemoInsteadOfBackfillingCreation(@TempDir Path @Test void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( @TempDir Path testDirectory) throws Exception { - Fixture fixture = prepareFixture(testDirectory); + Fixture fixture = prepareFixture(testDirectory, false); configureSeeder(fixture); Path receiptPath = fixture.receiptPath(); @@ -200,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(); @@ -255,6 +263,8 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( 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"), @@ -819,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"); @@ -1029,13 +1044,15 @@ private Fixture prepareFixture(Path testDirectory) throws Exception { // Disposable test schema only: create the real fixture owner from inception, never backfill. flyway.clean(); flyway.migrate(); - 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[] {})); + 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; } From b8db8c52a70cd3040e9fb1a9cbdee4dd5dc2db9c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:30:20 +1300 Subject: [PATCH 13/26] fix: enforce fixture client composition and exact server identity --- ...ame-authoring-publishing-and-activation.md | 2 + .../GameDesignFreshTenantCreationClient.java | 68 ++- ...essionCanonicalRealmCatalogRepository.java | 9 + ...ssionFreshTenantAssociationRepository.java | 8 + ...nantCreationClientMtlsIntegrationTest.java | 462 ++++++++++++++++++ ...meDesignFreshTenantCreationClientTest.java | 145 ++++++ ...onCanonicalRealmCatalogRepositoryTest.java | 19 + ...nFreshTenantAssociationRepositoryTest.java | 14 + .../RunOwnedWorldLaunchEvidenceProvider.java | 5 +- ...nOwnedWorldLaunchEvidenceProviderTest.java | 71 ++- 10 files changed, 775 insertions(+), 28 deletions(-) create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java 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 635cc9253e..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 @@ -18,6 +18,8 @@ The successor to the guarded World owner stage uses Game Design's existing fresh 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/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 index 9157338eed..8210a9ee2f 100644 --- 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 @@ -9,8 +9,10 @@ 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; @@ -28,6 +30,8 @@ public final class GameDesignFreshTenantCreationClient private final String workloadNamespace; private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; + private volatile boolean initialized; + private volatile boolean closed; public GameDesignFreshTenantCreationClient( ServiceEndpointsProperties endpoints, @@ -48,8 +52,18 @@ public GameDesignFreshTenantCreationClient( } /** Initializes this client only when the owning Game Session composition explicitly uses it. */ - public void init() throws SSLException, IOException { + 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 @@ -65,17 +79,38 @@ protected String defaultTarget() { @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"); @@ -88,7 +123,7 @@ public FreshTenantCreationEvidence resolveCreation( } ResolveFreshTenantCreationResponse response = - stub() + currentStub .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .resolveFreshTenantCreation( ResolveFreshTenantCreationRequest.newBuilder() @@ -156,29 +191,10 @@ private static IllegalStateException invalidOwnerEvidence(String message, Throwa private static CommonGrpcClientProperties requireGameSessionMtls( CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null) { - throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); - } - if (tlsProperties.isPlaintext()) { - throw new IllegalArgumentException( - "Fresh tenant identity reads require Game Session workload mTLS"); - } - if (!hasText(tlsProperties.getCertChain()) - || !hasText(tlsProperties.getPrivateKey()) - || !hasText(tlsProperties.getCaCert())) { - throw new IllegalArgumentException( - "Fresh tenant identity reads require Game Session certificate, key, and CA files"); - } - if (tlsProperties.getCertChain().trim().startsWith("classpath:") - || tlsProperties.getPrivateKey().trim().startsWith("classpath:") - || tlsProperties.getCaCert().trim().startsWith("classpath:")) { - throw new IllegalArgumentException( - "Fresh tenant identity reads require file-backed Game Session workload mTLS"); - } - return tlsProperties; - } - - private static boolean hasText(String value) { - return value != null && !value.isBlank(); + 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/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index c4d79b4f8e..9900ab0b00 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 @@ -1327,6 +1327,7 @@ private void validateRetainedFixturePolicy( /** 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())) { @@ -1371,6 +1372,7 @@ public FixtureCanonicalRealmCatalog establishVerifiedFixtureRealm( public FixtureCanonicalRealmCatalog readVerifiedFixtureRealm( RunOwnedInitialAdmissionLaunchEvidence evidence) { + requireFixtureComposition(); requireNoActiveOwnerTransaction(); evidence.requireVerifiedFixture(); FixtureCanonicalRealmCatalog readback = @@ -1454,6 +1456,13 @@ private static String completeCatalogRequestDigest(String requestDigest, byte[] 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 = 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 6c8817a671..003228cb7a 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 @@ -411,6 +411,13 @@ public FreshTenantAssociationConflictException(String message) { 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 = @@ -479,6 +486,7 @@ public FreshTenantAssociation associateFreshTenant( /** 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"); } 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/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/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/GameSessionFreshTenantAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryTest.java index d003c5c09e..ff9ea0a6f7 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; @@ -42,4 +43,17 @@ void rejectsReadOnlyOwnerTransactionBeforeTouchingStorage() { 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/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java index 9217e60db8..42bfeb4d6c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -38,6 +38,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; /** * Fixed-server reader and verifier for the run-owned World launch fixture. @@ -247,7 +248,9 @@ private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFix if (gameSessionFixtureClient != null) { return gameSessionFixtureClient; } - if (serviceEndpoints == null || grpcChannelFactory == null || workloadNamespace == null) { + if (serviceEndpoints == null + || grpcChannelFactory == null + || !StringUtils.hasText(workloadNamespace)) { throw invalidEvidence(); } CanonicalGameInstanceLaunchAssociationClient created = 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 d812f599f0..0a7dcd61d7 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 @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -440,6 +441,62 @@ void fixtureClientMissingConfigurationFailsAtReadStageWithoutCreatingClient(Capt .doesNotContain("fixture-run", "firemud-fixture-run"); } + @Test + void blankWorkloadNamespaceFailsBeforeCreatingFixtureClient() throws Exception { + ProviderFixture fixture = providerFixture(); + for (String namespace : new String[] {null, "", " "}) { + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + RunOwnedWorldLaunchEvidenceProvider provider = + provider( + fixture, + gameDesignClient, + null, + fixture.endpoints(), + fixture.tlsProperties(), + factory, + namespace); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + assertThatThrownBy(provider::requireAuthenticatedEvidence) + .isInstanceOf( + RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException + .class) + .hasMessage("Run-owned World launch evidence is invalid"); + } + + verifyNoInteractions(factory); + } + } + + @Test + void configuredWorkloadNamespaceIsPassedToFixtureClientFactory() throws Exception { + ProviderFixture fixture = providerFixture(); + GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); + CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); + when(fixtureClient.readFixture(any(), anyString())) + .thenAnswer(invocation -> fixture.association(invocation.getArgument(0))); + RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); + when(factory.create(any(), any(), any(), anyString())).thenReturn(fixtureClient); + RunOwnedWorldLaunchEvidenceProvider provider = + provider( + fixture, + gameDesignClient, + fixtureClient, + fixture.endpoints(), + fixture.tlsProperties(), + factory, + "dev"); + + try (PeerContext ignored = fixture.attachGameSessionPeer()) { + provider.requireAuthenticatedEvidence(); + } finally { + provider.closeGameSessionFixtureClient(); + } + + verify(factory).create(any(), any(), any(), eq("dev")); + } + private static void assertFileRejectionStoppedBeforeWireParse(CapturedOutput output) { assertThat(output) .contains("Run-owned World launch evidence verification rejected; stage=CAPABILITY_FILE") @@ -468,6 +525,18 @@ private RunOwnedWorldLaunchEvidenceProvider provider( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory) { + return provider( + fixture, gameDesignClient, fixtureClient, endpoints, tlsProperties, factory, "dev"); + } + + private RunOwnedWorldLaunchEvidenceProvider provider( + ProviderFixture fixture, + GameDesignClient gameDesignClient, + CanonicalGameInstanceLaunchAssociationClient fixtureClient, + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory, + String namespace) { return new RunOwnedWorldLaunchEvidenceProvider( true, fixture.capabilityPath().toString(), @@ -478,7 +547,7 @@ private RunOwnedWorldLaunchEvidenceProvider provider( gameDesignClient, endpoints, new GrpcChannelFactory(), - "dev", + namespace, factory); } From 544297c961d2f7d3211c4d7aa77b1ea1654603fe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 02:45:34 +1300 Subject: [PATCH 14/26] Preserve catalog discovery alongside retained historical rows --- ...e-session-runtime-and-tick-coordination.md | 2 +- ...essionCanonicalRealmCatalogRepository.java | 16 +- ...RealmCatalogRepositoryIntegrationTest.java | 304 ++++++++++++++++++ .../impl/GameInstanceServiceImplTest.java | 20 -- ...LaunchEvidencePostgresIntegrationTest.java | 7 + 5 files changed, 327 insertions(+), 22 deletions(-) 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 1e8e23ba4a..88a7f32a63 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 @@ -69,7 +69,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 retained pointer/audit components plus typed owner-proof reads are wired locally. The opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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/intent and retained pointer/audit components plus typed owner-proof reads are wired locally. The opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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). The opt-in run-owned fixture preparation and canonical launch persistence are covered by [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java) and [GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.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.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. | 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 9900ab0b00..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 @@ -456,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); 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 33b3615bca..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 @@ -255,6 +255,117 @@ 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); @@ -874,6 +985,199 @@ private Fixture fixture(boolean seedRetainedNumericRows, MigrationVersion target 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) { return uuid(100 + value); } 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 c8a976c581..3929689f4a 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 @@ -34,7 +34,6 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; -import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.client.GameDesignClient; @@ -1285,25 +1284,6 @@ private void configureLaunchPreflight() { .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); - when(gameDesignClient.resolveLaunchDescriptor( - any(Long.class), any(Long.class), anyString(), any(AuthoredWorldSourceEvidence.class))) - .thenAnswer( - invocation -> { - long tenantId = invocation.getArgument(0, Long.class); - long gameTemplateId = invocation.getArgument(1, Long.class); - String controlPlaneRequestId = invocation.getArgument(2, String.class); - AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); - LaunchDescriptor descriptor = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - new StartSessionRequest( - tenantId, gameTemplateId, controlPlaneRequestId, 42L), - sourceEvidence, - runOwnedBundleRef(tenantId)) - .launchDescriptor(); - return ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor(descriptor) - .build(); - }); when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() 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 2efe463ca7..d3a1a8894e 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 @@ -40,6 +40,9 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +import net.firedevops.firemud.worldmanagement.service.impl.InitialAdmissionBindHoldReconciler; +import net.firedevops.firemud.worldmanagement.service.impl.InstanceServiceImpl; +import net.firedevops.firemud.worldmanagement.service.impl.WorldEventServiceImpl; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; import org.jooq.DSLContext; import org.jooq.impl.DSL; @@ -99,6 +102,10 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + // Keep unrelated scheduled writers inert so whole-schema snapshots measure fixture effects. + @MockitoBean private InitialAdmissionBindHoldReconciler initialAdmissionBindHoldReconciler; + @MockitoBean private WorldEventServiceImpl worldEventService; + @MockitoBean private InstanceServiceImpl instanceService; @Test void fixturePrepareAndActivationRetryAndRestartDenyBeforeReadsOrPostgresEffects() { From c58677def55a1728c03a61d81e2ae3bdad9c9cd3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 04:54:34 +1300 Subject: [PATCH 15/26] Guard human launch provenance and close fixture review findings --- design/project-management/ai-observations.md | 5 + ...ssionFreshTenantAssociationRepository.java | 91 ----- .../GameSessionControlPlaneGrpcService.java | 2 + ...nonical_human_launch_policy_provenance.sql | 98 +++++ ...ialAdmissionRepositoryIntegrationTest.java | 38 +- ...unchRepositoryPostgresIntegrationTest.java | 383 +++++++++++++++++- ...nFreshTenantAssociationRepositoryTest.java | 4 +- ...nOwnedWorldLaunchEvidenceProviderTest.java | 18 + 8 files changed, 534 insertions(+), 105 deletions(-) create mode 100644 services/game-session-service/src/main/resources/db/migration/V1011.1__canonical_human_launch_policy_provenance.sql diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 549fec7615..bef7ec5f83 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -295,3 +295,8 @@ Entry format: - Observation: the next CLI review exposed the unchanged row. Documentation hygiene checks had passed because they do not verify that a requested semantic target changed. The original native fix record therefore overstated its proof. - 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.** + - Observation: A CLI finding claimed World accepted non-STARTING fixture allocations. 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. + - Consequence and 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. + - Reusable lesson: 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. 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 003228cb7a..f6e9e7de33 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 @@ -39,7 +39,6 @@ */ public class GameSessionFreshTenantAssociationRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); - private static final String FRESH_KIND = "FRESH_SOURCE_BOUND"; private final DSLContext dsl; @@ -56,21 +55,6 @@ public GameSessionFreshTenantAssociationRepository(DSLContext dsl) { 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. - */ - @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) - public FreshGameSessionTenantAssociation associateFresh( - UUID associationOperationId, String targetNamespace, IntakeReceipt expectedSourceReceipt) { - requireWritableReadCommittedOwnerTransaction(); - throw new InvalidFreshTenantSourceException( - "Complete immutable Game Design fresh-creation evidence is required before association"); - } - /** Creates the existing owner association only from both exact committed source receipts. */ @Transactional(propagation = Propagation.MANDATORY, isolation = Isolation.READ_COMMITTED) public FreshGameSessionTenantAssociation associateFresh( @@ -227,31 +211,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 " @@ -266,56 +225,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 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()) { 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 9b08c9b2b6..f6aac311a5 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 @@ -390,11 +390,13 @@ public void getRunOwnedFixtureLaunchAssociation( .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") 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/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 76e1b8d323..664e20c01a 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 @@ -725,8 +725,8 @@ void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Ex assertThat(pointerAndAuditProjection(predecessor)).isEqualTo(originalPointerAndAudit); assertThat(predecessorSourceProjection(predecessor)).isEqualTo(originalSources); } - migration(predecessor, null).migrate(); - migration(predecessor, null).validate(); + migration(predecessor, "1011").migrate(); + migration(predecessor, "1011").validate(); assertThat(migrationHistoryProjection(predecessor, stagedOriginalHistory ? "1010" : "1005")) .isEqualTo(originalHistory); assertThat( @@ -743,6 +743,40 @@ void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Ex } 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 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 index 7e0a6d6d31..656dd26b06 100644 --- 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 @@ -292,6 +292,360 @@ private static FixtureCanonicalInstanceLaunch contender( 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 = + historicalDigest( + java.util.List.of( + "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", + historicalDigest( + java.util.List.of( + "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 String historicalDigest(java.util.List 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 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 = @@ -447,6 +801,10 @@ private static UUID uuid(int value) { } private static Fixture fixture() { + return fixture(null); + } + + private static Fixture fixture(String targetVersion) { String schema = "gs_run_owned_launch_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); @@ -454,14 +812,15 @@ private static 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(targetVersion); + migration.load().migrate(); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); TransactionTemplate transactions = new TransactionTemplate(transactionManager); @@ -482,7 +841,9 @@ private static Fixture fixture() { sourceRepository, tenantAssociationRepository, catalogRepository, - launchRepository); + launchRepository, + dataSource, + schema); } private record Fixture( @@ -491,7 +852,9 @@ private record Fixture( GameSessionAuthoredWorldSourceRepository sourceRepository, GameSessionFreshTenantAssociationRepository tenantAssociationRepository, GameSessionCanonicalRealmCatalogRepository catalogRepository, - GameSessionCanonicalInstanceLaunchRepository launchRepository) {} + GameSessionCanonicalInstanceLaunchRepository launchRepository, + DriverManagerDataSource dataSource, + String schema) {} private record OwnerRows( int sourceRows, 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 ff9ea0a6f7..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 @@ -22,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"); @@ -37,7 +37,7 @@ 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"); 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 0a7dcd61d7..d5d7b7b000 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 @@ -130,6 +130,24 @@ void launchEvidenceConstructorRejectsMismatchedGameSessionFixtureAssociation() { .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_FIXTURE_ASSOCIATION_MISMATCH:"); } + @Test + void fixtureOwnerWireResultRejectsNonStartingAllocationsBeforeWorldConsumption() { + var original = fixtureEvidence().gameSessionAssociation(); + var response = + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(original); + for (var status : java.util.List.of("RUNNING", "STOPPED")) { + var changed = response.toBuilder().setCurrentGameInstanceStatus(status).build(); + assertThatThrownBy( + () -> + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + original.request(), changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Fixture launch association read requires the current STARTING snapshot"); + } + } + @Test void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign(CapturedOutput output) { GameDesignClient gameDesignClient = mock(GameDesignClient.class); From 98a8418d0c6f0435bd1885c2560544a1b14766f7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:54:56 +1300 Subject: [PATCH 16/26] Fix Human association retry isolation and fixture review findings --- design/project-management/ai-observations.md | 9 +- ...e-session-runtime-and-tick-coordination.md | 2 +- ...alGameInstanceLaunchAssociationClient.java | 11 +- .../data/RunOwnedFixturePolicyProducer.java | 6 +- ...ssionFreshTenantAssociationRepository.java | 2 + ...tAssociationRepositoryIntegrationTest.java | 143 ++++++++++++++++++ ...nitialAdmissionFixtureCoordinatorTest.java | 14 +- 7 files changed, 177 insertions(+), 10 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index bef7ec5f83..279455d306 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -296,7 +296,8 @@ 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.** - - Observation: A CLI finding claimed World accepted non-STARTING fixture allocations. 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. - - Consequence and 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. - - Reusable lesson: 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`: 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. 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 88a7f32a63..654028425a 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 @@ -69,7 +69,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 retained pointer/audit components plus typed owner-proof reads are wired locally. The opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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). The opt-in run-owned fixture preparation and canonical launch persistence are covered by [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java) and [GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.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/intent and retained pointer/audit components plus typed owner-proof reads are wired locally. The opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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 refusal boundary is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java): prepare, commit, and abort refuse before intent, World hold, pointer, or audit effects; this unit proof does not establish durable Human terminal settlement. 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 opt-in run-owned fixture preparation and canonical launch persistence are covered by [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java) and [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); [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.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. | 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 469da3a7ce..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 @@ -104,8 +104,15 @@ public CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult readFixt .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer, expectedLeafSha256)) .getRunOwnedFixtureLaunchAssociation( CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureRequest(request)); - var result = - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse(request, response); + 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( 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 index 8b67423952..b3040cc534 100644 --- 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 @@ -19,8 +19,10 @@ /** Fixed-capability fixture authority only; never emits human selected-publication evidence. */ @Service public final class RunOwnedFixturePolicyProducer { - private static final String SCHEMA = "firemud.run-owned-fixture-policy-seal.v1"; - private static final String OWNER = "game-design-service"; + 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; 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 f6e9e7de33..61a27aa895 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 @@ -25,6 +25,7 @@ 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; @@ -345,6 +346,7 @@ public GameSessionFreshTenantAssociationRepository( } 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); } 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 690b977d61..ba55c7adfa 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,14 +16,17 @@ 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; @@ -32,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; @@ -94,6 +103,68 @@ void allocatesPrivateIdentityAndReturnsTheOriginalExactAssociationOnRetry() { .isEqualTo("FRESH_SOURCE_BOUND"); } + @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(); @@ -568,4 +639,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/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 c9bf4676e1..fdda9e7306 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 @@ -210,7 +210,19 @@ void rejectsReceiptWithChangedFixturePolicySealBeforeOwnerWrite() { void disabledCoordinatorDoesNotReadFixturePathsOrWriteLaunchOwner() { Fixture fixture = fixture(false); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); + try (MockedStatic loader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + + loader.verify( + () -> RunOwnedInitialAdmissionFixtureCapability.load(any(), any(), any(), any()), + never()); + loader.verify( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(), any(), any(), any(), any()), + never()); + } verifyNoInteractions(fixture.launchOwner); } From 5561f6b729fde481224dfd0a1bba5464fa48f7fb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:17:22 +1300 Subject: [PATCH 17/26] Record Human launch policy provenance guard and retained history limits --- .../game-session-runtime-and-tick-coordination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 654028425a..42c146d7fb 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 @@ -12,7 +12,7 @@ The successor to the guarded World owner stage prepares the closed Game Design f The obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the existing default-off fixture configuration; World materialization, holds, first `OPEN` and all four genuine handoffs remain open. 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. 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. +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 From cbf471187091e307bf7a0e6328c20d008aad4cc8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:55:27 +1300 Subject: [PATCH 18/26] Fix launch replay isolation and deny unprotected intent reservation --- .../game-session-service/api-contracts.md | 2 +- .../system-architecture-testing.md | 4 +- ...e-session-runtime-and-tick-coordination.md | 2 +- .../CanonicalInitialAdmissionRepository.java | 96 +--- ...sionCanonicalInstanceLaunchRepository.java | 1 + ...icalHumanPublicationOwnerTestFixtures.java | 15 + ...ialAdmissionRepositoryIntegrationTest.java | 454 +++++++----------- ...unchRepositoryPostgresIntegrationTest.java | 235 ++++++--- ...unchPreparationServiceIntegrationTest.java | 20 +- ...nonicalInitialAdmissionRepositoryTest.java | 7 +- 10 files changed, 387 insertions(+), 449 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index b6998f71a7..67cfdc72fa 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -10,7 +10,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat The bounded run-owned owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. Under the existing default-off fixture configuration, the coordinator prepares the actual canonical Game Session fresh association, catalog and `STARTING` launch, then compares an independent committed owner readback. Game Design source keys and Game Session's allocated private tenant/runtime keys are separate. The earlier numeric fixture allocator is removed. The fixture lifecycle method refuses the unavailable World continuation before owner effects; it returns no active or 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#run-owned-canonical-source-handoff). +`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, holds and the later first-`OPEN` phase remain unavailable in this stage. The coordinator's completed launch-preparation phase is not a completed admission. Generic `StartSession` cannot construct the verified fixture carrier, and this stage grants no Human activation or production Game Design release-read permission. diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index ed81f9b5e7..b87175b223 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -183,7 +183,7 @@ Current bounded implementation stops after the closed Game Design producer and i 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. -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 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. `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. @@ -199,7 +199,7 @@ The existing `world_instance` row retains its original SHA-256 fixture binding a 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#run-owned-canonical-source-handoff) 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. +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/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 42c146d7fb..f9cd4d6e62 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 @@ -69,7 +69,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 retained pointer/audit components plus typed owner-proof reads are wired locally. The opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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 refusal boundary is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java): prepare, commit, and abort refuse before intent, World hold, pointer, or audit effects; this unit proof does not establish durable Human terminal settlement. 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 opt-in run-owned fixture preparation and canonical launch persistence are covered by [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java) and [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); [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 opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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 opt-in run-owned fixture preparation and canonical launch persistence are covered by [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java) and [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); [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.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. | 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 a908c77dd6..f4ef1d9e12 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 @@ -11,7 +11,6 @@ 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; @@ -87,102 +86,11 @@ public CanonicalInitialAdmissionRepository( Objects.requireNonNull(eventRepository, "eventRepository"); } - /** Persists the immutable request identity before remote World verification is attempted. */ + /** Denies fresh Human intent before owner effects while Account protection is unavailable. */ @Transactional(isolation = Isolation.READ_COMMITTED) 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(); } /** 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 index 627eccc1e0..6c37a0458d 100644 --- 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 @@ -44,6 +44,7 @@ public GameSessionCanonicalInstanceLaunchRepository( 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); 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 index 91d483fa71..d1284bc81d 100644 --- 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 @@ -48,6 +48,21 @@ public final class CanonicalHumanPublicationOwnerTestFixtures { 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)); } 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 664e20c01a..7f0055b5a1 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 @@ -60,6 +60,7 @@ 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; @@ -98,102 +99,46 @@ class CanonicalInitialAdmissionRepositoryIntegrationTest { new PostgreSQLContainer<>(TestContainerImages.postgres()); @Test - void reservesExactHumanIntentButDeniesCommitAndAbortBeforePointerOrAuditEffects() { - 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); + void freshHumanReservationDeniesBeforeEffectsAndRetainedPendingCannotCommit() throws Exception { + Fixture fixture = fixture("1005"); + PredecessorAdmission predecessor = preparePre1006Admission(fixture); + PreparedAdmission prepared = predecessor.prepared(); CanonicalInitialAdmissionRequest request = initialAdmissionRequest( - catalog, - completeBinding, - fixture - .launchRepository - .read(CONTROL_PLANE_REQUEST_ID) - .orElseThrow() - .gameInstanceUuid()); - assertThat(tenantAssociation.legacyGameSessionTenantId()) - .isNotEqualTo(source.source().sourceGameRowId()); - assertThat(request.playableStateNamespaceId()).isEqualTo(catalog.playableStateNamespaceId()); - CanonicalInitialAdmissionWorldProof worldProof = testWorldProof(request); + 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); @@ -257,17 +202,13 @@ void reservesExactHumanIntentButDeniesCommitAndAbortBeforePointerOrAuditEffects( DSL.field(DSL.name("representation_version"), Integer.class).eq(3))) .isZero(); - CanonicalInitialAdmissionOwnerProof pending = - fixture - .initialAdmissionRepository - .read(NAMESPACE, request.initialAdmissionRequestId()) - .orElseThrow(); - String before = attemptProjection(fixture, request); for (int retry = 0; retry < 2; retry++) { assertHumanProtectionUnavailable( () -> fixture.transactions.executeWithoutResult( - status -> fixture.initialAdmissionRepository.commit(request, worldProof, null))); + status -> + fixture.initialAdmissionRepository.commit( + request, testWorldProof(request), null))); assertHumanProtectionUnavailable( () -> fixture.transactions.executeWithoutResult( @@ -287,7 +228,7 @@ void reservesExactHumanIntentButDeniesCommitAndAbortBeforePointerOrAuditEffects( } @Test - void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { + void denies128CharacterFreshHumanIntentBeforeReservation() { Fixture fixture = fixture(); PreparedAdmission prepared = prepareAdmission(fixture); String requestId = "r".repeat(128); @@ -302,31 +243,21 @@ void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { 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 competingNoPriorPointerReservationCannotReplacePendingUnprotectedHumanIntent() { + void competingFreshHumanReservationsDenyBeforeIntentOrPointerEffects() { Fixture fixture = fixture(); PreparedAdmission prepared = prepareAdmission(fixture); CanonicalInitialAdmissionRequest first = initialAdmissionRequest( prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); - fixture.transactions.executeWithoutResult( - status -> fixture.initialAdmissionRepository.reserve(first)); - assertHumanProtectionUnavailable( - () -> fixture.initialAdmissionRepository.commit(first, testWorldProof(first), null)); CanonicalInitialAdmissionRequest competing = initialAdmissionRequest( prepared.catalog(), @@ -337,33 +268,25 @@ void competingNoPriorPointerReservationCannotReplacePendingUnprotectedHumanInten null, uuid(117), uuid(118)); - assertThatThrownBy( - () -> - fixture.transactions.executeWithoutResult( - status -> fixture.initialAdmissionRepository.reserve(competing))) - .isInstanceOf( - CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException.class) - .hasMessageContaining("pending realm attempt"); + + 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("game_session_canonical_initial_admission_attempt")), - DSL.field(DSL.name("status"), String.class).eq("PENDING"))) - .isEqualTo(1); - assertThat( - fixture.initialAdmissionRepository.read(NAMESPACE, first.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.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 expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { + void freshExpectedClosedHumanIntentDeniesBeforeEffects() { Fixture fixture = fixture(); PreparedAdmission preparedAdmission = prepareAdmission(fixture); CanonicalRealmCatalogSnapshot catalog = preparedAdmission.catalog(); @@ -395,18 +318,11 @@ void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { 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( @@ -418,42 +334,26 @@ void expectedClosedReservationRequiresExactCurrentOriginalClosedEvidence() { 1L, uuid(121), uuid(122)); - fixture.transactions.execute( - status -> { - fixture.initialAdmissionRepository.reserve(firstOpenRequest); - return null; - }); - assertThat( - fixture.initialAdmissionRepository.read( - NAMESPACE, firstOpenRequest.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertHumanProtectionUnavailable( + () -> fixture.initialAdmissionRepository.reserve(firstOpenRequest)); + assertNoAttemptAndNoPending(fixture, firstOpenRequest); var preparedExpectedClosed = fixture.pointerRepository.prepareExpectedClosedForRealm( NAMESPACE, TENANT, catalog.realmId(), 1L, catalog.catalogRevision()); - String closedBefore = pointerAndAuditProjection(fixture); - String pendingBefore = attemptProjection(fixture, firstOpenRequest); assertHumanProtectionUnavailable( () -> - fixture.transactions.executeWithoutResult( - status -> - fixture.initialAdmissionRepository.commit( - firstOpenRequest, - testWorldProof(firstOpenRequest), - preparedExpectedClosed))); + fixture.initialAdmissionRepository.commit( + firstOpenRequest, testWorldProof(firstOpenRequest), preparedExpectedClosed)); assertHumanProtectionUnavailable( () -> - fixture.transactions.executeWithoutResult( - status -> - fixture.initialAdmissionRepository.abort( - firstOpenRequest, preparedExpectedClosed, "Missing protection"))); + fixture.initialAdmissionRepository.abort( + firstOpenRequest, preparedExpectedClosed, "Missing protection")); assertThat(pointerAndAuditProjection(fixture)).isEqualTo(closedBefore); - assertThat(attemptProjection(fixture, firstOpenRequest)).isEqualTo(pendingBefore); + assertNoAttemptAndNoPending(fixture, firstOpenRequest); assertThat( fixture.initialAdmissionRepository.read( NAMESPACE, firstOpenRequest.initialAdmissionRequestId())) - .map(CanonicalInitialAdmissionOwnerProof::outcome) - .contains(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + .isEmpty(); } @Test @@ -482,41 +382,40 @@ void directlyConstructedHumanServiceDeniesBeforeReservationOrWorldVerification() } @Test - void unprotectedHumanAbortAndCommitRetryLeaveTheExactPendingOwnerUnchanged() { + void freshHumanReserveCommitAndAbortRetriesLeaveNoOwnerEffects() { Fixture fixture = fixture(); PreparedAdmission prepared = prepareAdmission(fixture); var request = initialAdmissionRequest( prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); - fixture.transactions.executeWithoutResult( - status -> fixture.initialAdmissionRepository.reserve(request)); - var pending = - fixture - .initialAdmissionRepository - .read(NAMESPACE, request.initialAdmissionRequestId()) - .orElseThrow(); - String before = attemptProjection(fixture, request); for (int retry = 0; retry < 2; retry++) { + assertHumanProtectionUnavailable(() -> fixture.initialAdmissionRepository.reserve(request)); assertHumanProtectionUnavailable( () -> fixture.initialAdmissionRepository.abort(request, null, "World hold expired")); assertHumanProtectionUnavailable( () -> fixture.initialAdmissionRepository.commit(request, testWorldProof(request), null)); - fixture.transactions.executeWithoutResult( - status -> fixture.initialAdmissionRepository.reserve(request)); - assertThat(attemptProjection(fixture, request)).isEqualTo(before); + assertNoAttemptAndNoPending(fixture, request); assertThat( fixture.initialAdmissionRepository.read( NAMESPACE, request.initialAdmissionRequestId())) - .contains(pending); + .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(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 terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { - Fixture fixture = fixture(); + 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( @@ -526,12 +425,15 @@ void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { "SELECT count(*) FROM flyway_schema_history WHERE version = '1011' AND success") .get(0, Long.class)) .isEqualTo(1L); - PreparedAdmission prepared = prepareAdmission(fixture); - var request = - initialAdmissionRequest( - prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); - fixture.transactions.executeWithoutResult( - status -> fixture.initialAdmissionRepository.reserve(request)); + assertThat( + 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<>( @@ -550,12 +452,55 @@ void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { terminalColumns.put("abort_proof_digest", "sha256:" + "f".repeat(64)); terminalColumns.put("terminal_at", terminalColumns.get("updated_at")); - // Isolate the declarative constraint in this disposable schema. All other triggers, - // source bindings and constraints stay enabled; each failed write rolls back separately. - fixture.dsl.execute( - "ALTER TABLE game_session_canonical_initial_admission_attempt DISABLE TRIGGER " - + "game_session_canonical_initial_admission_v44_terminal_evidence"); - try { + 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( @@ -565,7 +510,7 @@ void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { .insertInto( DSL.table( DSL.name("game_session_canonical_initial_admission_attempt"))) - .set(terminalColumns) + .set(partial) .execute())) .isInstanceOfSatisfying( DataAccessException.class, @@ -573,92 +518,37 @@ void terminalProtectionConstraintRejectsNewAndUpdatedUnprotectedTerminalRows() { assertThat(exception.sqlState()).isEqualTo("23514"); assertThat(exception) .hasStackTraceContaining( - "violates check constraint \"chk_gs_initial_admission_terminal_requires_protection\""); + "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' " + "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 = ?", - terminalColumns.get("abort_reason"), - terminalColumns.get("abort_proof_digest"), + 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 -> { - assertThat(exception.sqlState()).isEqualTo("23514"); - assertThat(exception) - .hasStackTraceContaining( - "violates check constraint \"chk_gs_initial_admission_terminal_requires_protection\""); - }); - 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( - "violates check constraint \"chk_gs_initial_admission_account_protection_evidence_complete\""); - }); - 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 -> { - assertThat(exception.sqlState()).isEqualTo("23514"); - assertThat(exception) - .hasStackTraceContaining( - "violates check constraint \"chk_gs_initial_admission_account_protection_evidence_complete\""); - }); - } - } finally { - fixture.dsl.execute( - "ALTER TABLE game_session_canonical_initial_admission_attempt ENABLE TRIGGER " - + "game_session_canonical_initial_admission_v44_terminal_evidence"); + 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( @@ -1497,6 +1387,26 @@ private static void assertHumanProtectionUnavailable(Runnable operation) { .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 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 index 656dd26b06..4ede003816 100644 --- 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 @@ -5,6 +5,9 @@ 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; @@ -279,6 +282,117 @@ void allocatesOneStartingLaunchWithExactPolicyAndIndependentOwnerReadback() thro 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, @@ -437,53 +551,51 @@ private static void insertHistoricalCatalog( var source = receipt.source(); UUID creationId = uuid(1105); String requestDigest = - historicalDigest( - java.util.List.of( - "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")); + 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", - historicalDigest( - java.util.List.of( - "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()))); + 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()); @@ -507,21 +619,6 @@ private static void insertHistoricalCatalog( }); } - private static String historicalDigest(java.util.List 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 void insertHumanLaunch( Fixture fixture, IntakeReceipt receipt, UUID realmId, String requestId) { var fresh = @@ -805,8 +902,26 @@ private static Fixture fixture() { } 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 = new DriverManagerDataSource(); + 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()); 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 4c08f03959..9f477cc5e0 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 @@ -789,7 +789,7 @@ private static CanonicalRealmCatalogSnapshot seedHistoricalCatalog( UUID realm = uuid(974); UUID namespace = uuid(973); String requestDigest = - historicalDigest( + CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( "game-session-canonical-realm-catalog-request/v1", "1", request.toString(), @@ -820,7 +820,7 @@ private static CanonicalRealmCatalogSnapshot seedHistoricalCatalog( "ABSENT", "ABSENT"); String receiptDigest = - historicalDigest( + CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( "game-session-canonical-realm-catalog-receipt/v1", "1", NAMESPACE, @@ -926,22 +926,6 @@ private static String historicalProjection( .get("retained", String.class); } - private static String historicalDigest(String... fields) { - try { - var 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 unavailable) { - throw new IllegalStateException(unavailable); - } - } - 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"); 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 b14b790ff5..f0e9be52a0 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 @@ -18,7 +18,7 @@ class CanonicalInitialAdmissionRepositoryTest { @Test - void incompleteHumanCommitAndAbortDenyBeforeAnyOwnerStorageInteraction() { + void incompleteHumanReserveCommitAndAbortDenyBeforeAnyOwnerStorageInteraction() { var dsl = mock(DSLContext.class); var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); var pointers = mock(GameSessionCanonicalAdmissionPointerRepository.class); @@ -81,6 +81,11 @@ void incompleteHumanCommitAndAbortDenyBeforeAnyOwnerStorageInteraction() { request.holdId(), request.holdFence(), request.holdBindingDigest()); + assertThatThrownBy(() -> repository.reserve(request)) + .isInstanceOf( + CanonicalInitialAdmissionRepository + .CanonicalHumanAdmissionProtectionUnavailableException.class) + .hasMessageContaining("Account terminal protection"); assertThatThrownBy(() -> repository.commit(request, world, null)) .isInstanceOf( CanonicalInitialAdmissionRepository From 6ee1cb3d505e15a6d4272959de532969d0bd6e2e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:34:44 +1300 Subject: [PATCH 19/26] Remove unreachable Human mutation paths and align fixture proof --- design/project-management/ai-observations.md | 5 + ...e-session-runtime-and-tick-coordination.md | 4 +- ...calInitialAdmissionOwnerConfiguration.java | 9 +- .../CanonicalInitialAdmissionRepository.java | 213 ++---------------- ...ialAdmissionRepositoryIntegrationTest.java | 28 +-- ...ratorAttemptRepositoryIntegrationTest.java | 170 ++++++-------- ...nonicalInitialAdmissionRepositoryTest.java | 174 +++++++++----- 7 files changed, 215 insertions(+), 388 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 279455d306..c95a28b014 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -301,3 +301,8 @@ Entry format: - 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. 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 f9cd4d6e62..f8b331a51a 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 @@ -16,9 +16,9 @@ The migration-preservation correction restores the exact original V1005/V1006 Gi ### 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 repaired candidate. The current local fixture consumes Game Design's atomic run/project-bound 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 retries and binds the launch to the registered source. Game Session obtains its typed fixture carrier only through the trusted data-package parser; the coordinator currently performs only `createVerifiedFixtureStartingLaunch` and `readVerifiedFixtureLaunch`, preparing the canonical fresh association, catalog, and `STARTING` launch with independent owner readback. 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. +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 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. Fresh packaged `PLAY`/`LOOK` remains unqualified for the current candidate, as described above. 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. 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 1680bee762..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,11 +1,9 @@ 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; @@ -28,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 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 f4ef1d9e12..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 @@ -7,10 +7,8 @@ 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.util.Collections; import java.util.HexFormat; import java.util.LinkedHashMap; @@ -21,21 +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.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"; @@ -50,7 +46,6 @@ public class CanonicalInitialAdmissionRepository { private final DSLContext dsl; private final GameSessionCanonicalRealmCatalogRepository catalogRepository; private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; - private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; /** One exact current pointer row plus its validated owner result and GS-owned snapshot digest. */ public record CurrentOpenSnapshot( @@ -76,18 +71,13 @@ 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"); - Objects.requireNonNull(eventRepository, "eventRepository"); } /** Denies fresh Human intent before owner effects while Account protection is unavailable. */ - @Transactional(isolation = Isolation.READ_COMMITTED) public void reserve(CanonicalInitialAdmissionRequest request) { Objects.requireNonNull(request, "request"); throw unavailableHumanAdmissionProtection(); @@ -97,11 +87,8 @@ public void reserve(CanonicalInitialAdmissionRequest request) { * 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); @@ -109,11 +96,7 @@ public void commit( } /** Denies Human abort before owner effects while Account terminal protection is unavailable. */ - @Transactional(isolation = Isolation.READ_COMMITTED) - public void abort( - CanonicalInitialAdmissionRequest request, - PreparedExpectedClosed preparedExpectedClosed, - String reason) { + public void abort(CanonicalInitialAdmissionRequest request, String reason) { Objects.requireNonNull(request, "request"); requireText(reason, "reason", 500); throw unavailableHumanAdmissionProtection(); @@ -124,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(); } @@ -432,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( @@ -467,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( @@ -483,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 @@ -492,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()) @@ -546,30 +524,6 @@ private CanonicalRealmCatalogSnapshot readExactCatalog(CanonicalInitialAdmission return catalog; } - 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()) @@ -586,120 +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 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); } @@ -863,37 +711,6 @@ private static String digest(List fields) { } } - 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/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 7f0055b5a1..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 @@ -207,14 +207,12 @@ void freshHumanReservationDeniesBeforeEffectsAndRetainedPendingCannotCommit() th () -> fixture.transactions.executeWithoutResult( status -> - fixture.initialAdmissionRepository.commit( - request, testWorldProof(request), null))); + fixture.initialAdmissionRepository.commit(request, testWorldProof(request)))); assertHumanProtectionUnavailable( () -> fixture.transactions.executeWithoutResult( status -> - fixture.initialAdmissionRepository.abort( - request, null, "Missing protection"))); + fixture.initialAdmissionRepository.abort(request, "Missing protection"))); assertThat(attemptProjection(fixture, request)).isEqualTo(before); assertThat( fixture.initialAdmissionRepository.read( @@ -337,17 +335,12 @@ void freshExpectedClosedHumanIntentDeniesBeforeEffects() { assertHumanProtectionUnavailable( () -> fixture.initialAdmissionRepository.reserve(firstOpenRequest)); assertNoAttemptAndNoPending(fixture, firstOpenRequest); - var preparedExpectedClosed = - fixture.pointerRepository.prepareExpectedClosedForRealm( - NAMESPACE, TENANT, catalog.realmId(), 1L, catalog.catalogRevision()); assertHumanProtectionUnavailable( () -> fixture.initialAdmissionRepository.commit( - firstOpenRequest, testWorldProof(firstOpenRequest), preparedExpectedClosed)); + firstOpenRequest, testWorldProof(firstOpenRequest))); assertHumanProtectionUnavailable( - () -> - fixture.initialAdmissionRepository.abort( - firstOpenRequest, preparedExpectedClosed, "Missing protection")); + () -> fixture.initialAdmissionRepository.abort(firstOpenRequest, "Missing protection")); assertThat(pointerAndAuditProjection(fixture)).isEqualTo(closedBefore); assertNoAttemptAndNoPending(fixture, firstOpenRequest); assertThat( @@ -391,9 +384,9 @@ void freshHumanReserveCommitAndAbortRetriesLeaveNoOwnerEffects() { for (int retry = 0; retry < 2; retry++) { assertHumanProtectionUnavailable(() -> fixture.initialAdmissionRepository.reserve(request)); assertHumanProtectionUnavailable( - () -> fixture.initialAdmissionRepository.abort(request, null, "World hold expired")); + () -> fixture.initialAdmissionRepository.abort(request, "World hold expired")); assertHumanProtectionUnavailable( - () -> fixture.initialAdmissionRepository.commit(request, testWorldProof(request), null)); + () -> fixture.initialAdmissionRepository.commit(request, testWorldProof(request))); assertNoAttemptAndNoPending(fixture, request); assertThat( fixture.initialAdmissionRepository.read( @@ -727,13 +720,11 @@ void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Ex .intoArray()) .containsOnlyNulls(); assertHumanProtectionUnavailable( - () -> - predecessor.initialAdmissionRepository.commit( - request, testWorldProof(request), null)); + () -> predecessor.initialAdmissionRepository.commit(request, testWorldProof(request))); assertHumanProtectionUnavailable( () -> predecessor.initialAdmissionRepository.abort( - request, null, "Current Human retry remains unprotected")); + request, "Current Human retry remains unprotected")); assertThatThrownBy( () -> predecessor.transactions.executeWithoutResult( @@ -1536,8 +1527,7 @@ private Fixture fixture(String targetVersion) { 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, 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 b592839853..8106cad084 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 @@ -108,56 +108,12 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr // 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. - var catalogEvidenceBefore = - 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()); - var launchEvidenceBefore = - 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()); - assertThat(launchEvidenceBefore).isNotNull(); - String originalLaunchColumnsBefore = - launchEvidenceBefore.get("original_columns", String.class); - String launchXminBefore = launchEvidenceBefore.get("xmin", String.class); - assertThat(catalogEvidenceBefore).isNotNull(); - String originalCatalogColumnsBefore = - catalogEvidenceBefore.get("original_columns", String.class); - String catalogXminBefore = catalogEvidenceBefore.get("xmin", String.class); + 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(); @@ -187,56 +143,12 @@ void v34_3BaselineUpgradePreservesLegitimateEvidenceAndCreatesContinuationConstr + " ORDER BY installed_rank") .getValues("version", String.class)) .containsExactly("35", "37", "38"); - var catalogEvidenceAfter = - 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()); - assertThat(catalogEvidenceAfter).isNotNull(); - assertThat(catalogEvidenceAfter.get("original_columns", String.class)) - .isEqualTo(originalCatalogColumnsBefore); - assertThat(catalogEvidenceAfter.get("xmin", String.class)).isEqualTo(catalogXminBefore); - var launchEvidenceAfter = - 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()); - assertThat(launchEvidenceAfter).isNotNull(); - assertThat(launchEvidenceAfter.get("original_columns", String.class)) - .isEqualTo(originalLaunchColumnsBefore); - assertThat(launchEvidenceAfter.get("xmin", String.class)).isEqualTo(launchXminBefore); + 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, @@ -294,6 +206,62 @@ 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("-", ""); @@ -655,6 +623,8 @@ private static void seedV34_3StartingRuntimeAndLaunch(DSLContext tx, PriorRuntim target.canonicalVersionId().toString()); } + private record PredecessorSnapshot(String originalColumns, String xmin) {} + private record PriorRuntime( String targetNamespace, UUID canonicalTenantId, 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 f0e9be52a0..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 @@ -5,16 +5,25 @@ 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 @@ -22,80 +31,57 @@ void incompleteHumanReserveCommitAndAbortDenyBeforeAnyOwnerStorageInteraction() var dsl = mock(DSLContext.class); var catalog = mock(GameSessionCanonicalRealmCatalogRepository.class); var pointers = mock(GameSessionCanonicalAdmissionPointerRepository.class); - var launches = mock(CanonicalGameInstanceLaunchAssociationRepository.class); - var events = mock(GameplayAdmissionPointerEventRepository.class); - var repository = - new CanonicalInitialAdmissionRepository(dsl, catalog, pointers, launches, events); - var prior = committedProof(); - String digest = - CanonicalInitialAdmissionRequest.computeRequestDigest( - prior.targetNamespace(), - prior.canonicalTenantId(), - prior.worldSlug(), - prior.realmId(), - prior.playableStateNamespaceId(), - prior.playableStateScope(), - prior.canonicalGameInstanceId(), - prior.canonicalVersionId(), - prior.activeLifecycleEpoch(), - prior.expectedCatalogRevision(), - prior.originKind(), - prior.expectedPriorPointerVersion(), - prior.initialAdmissionRequestId()); - var request = - new CanonicalInitialAdmissionRequest( - prior.targetNamespace(), - prior.canonicalTenantId(), - prior.worldSlug(), - prior.realmId(), - prior.playableStateNamespaceId(), - prior.playableStateScope(), - prior.canonicalGameInstanceId(), - prior.canonicalVersionId(), - prior.activeLifecycleEpoch(), - prior.expectedCatalogRevision(), - prior.originKind(), - prior.expectedPriorPointerVersion(), - prior.initialAdmissionRequestId(), - digest, - prior.holdId(), - prior.holdFence(), - prior.holdBindingDigest()); - var world = - new CanonicalInitialAdmissionWorldProof( - request.initialAdmissionRequestId(), - digest, - 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()); + 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, null)) + assertThatThrownBy(() -> repository.commit(request, world)) .isInstanceOf( CanonicalInitialAdmissionRepository .CanonicalHumanAdmissionProtectionUnavailableException.class) .hasMessageContaining("Account terminal protection"); - assertThatThrownBy(() -> repository.abort(request, null, "Missing protection")) + assertThatThrownBy(() -> repository.abort(request, "Missing protection")) .isInstanceOf( CanonicalInitialAdmissionRepository .CanonicalHumanAdmissionProtectionUnavailableException.class); - verifyNoInteractions(dsl, catalog, pointers, launches, events); + 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 @@ -201,6 +187,70 @@ 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", From 65ffa8db386f70f26e4a3bc1929e346c24ab5c77 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:10:07 +1300 Subject: [PATCH 20/26] Skip occupied private tenant reservations during fresh allocation --- ...ssionFreshTenantAssociationRepository.java | 37 +++--- ...tAssociationRepositoryIntegrationTest.java | 116 ++++++++++++++++++ 2 files changed, 139 insertions(+), 14 deletions(-) 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 61a27aa895..079d31b3cc 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 @@ -40,6 +40,7 @@ */ public class GameSessionFreshTenantAssociationRepository { private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int MAX_TENANT_ID_ALLOCATION_ATTEMPTS = 64; private final DSLContext dsl; @@ -615,21 +616,29 @@ private void rejectClaimWithoutAssociation( } private long allocateFreshTenantId() { - Record reservation = - dsl.fetchOne( - "INSERT INTO game_session_tenant_scope_reservation (reservation_kind)" - + " VALUES ('FRESH_SOURCE_BOUND') RETURNING game_session_tenant_id, reservation_kind"); - if (reservation == null - || !"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"); + 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; } - return tenantId; + throw new InvalidFreshTenantAssociationException( + "Game Session numeric tenant reservation exhausted its bounded allocation attempts"); } private void lockSourceIdentity(FreshTenantCreationEvidence evidence) { 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 ba55c7adfa..3cbc7a7891 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 @@ -103,6 +103,122 @@ 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 { From 8b399b00179d06eaa59a25eb940490f2814a9b76 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:56:02 +1300 Subject: [PATCH 21/26] Separate canonical fixture source preparation from retained bootstrap --- .../game-session-service/api-contracts.md | 4 +- .../world-management-service/api-contracts.md | 2 +- .../system-architecture-testing.md | 4 +- ...e-session-runtime-and-tick-coordination.md | 12 +- .../world-runtime-and-movement.md | 8 +- ...nOwnedCanonicalLaunchPreparationOwner.java | 361 +++++ ...nedInitialAdmissionFixtureCoordinator.java | 652 +++++--- ...unOwnedInitialAdmissionLaunchEvidence.java | 4 +- ...tectedGameSessionLoginGrpcInterceptor.java | 2 +- .../service/impl/GameInstanceServiceImpl.java | 769 +++++++++- .../GameSessionControlPlaneGrpcService.java | 14 +- ...edCanonicalLaunchPreparationOwnerTest.java | 653 ++++++++ ...nitialAdmissionFixtureCoordinatorTest.java | 1354 +++++++++++------ ...edGameSessionLoginGrpcInterceptorTest.java | 64 + .../impl/GameInstanceServiceImplTest.java | 622 +++++++- ...eLaunchAssociationReadGrpcServiceTest.java | 8 +- .../data/RunOwnedWorldLaunchEvidence.java | 77 +- .../RunOwnedWorldLaunchEvidenceProvider.java | 135 +- .../worldmanagement/data/TestDataSeeder.java | 11 - .../WorldLifecycleCommandServiceImpl.java | 123 +- ...orldLaunchEvidenceMtlsIntegrationTest.java | 1085 +++++++++---- ...LaunchEvidencePostgresIntegrationTest.java | 317 ++-- ...nOwnedWorldLaunchEvidenceProviderTest.java | 799 +--------- .../data/TestDataSeederTest.java | 10 - .../WorldLifecycleCommandServiceImplTest.java | 253 ++- 25 files changed, 5060 insertions(+), 2283 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwner.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptorTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 67cfdc72fa..9173fcfd48 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,11 +8,11 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -The bounded run-owned owner stage consumes the closed Game Design creation/source receipt, four immutable launch snapshots and policy seal through the trusted fixed capability parser. Under the existing default-off fixture configuration, the coordinator prepares the actual canonical Game Session fresh association, catalog and `STARTING` launch, then compares an independent committed owner readback. Game Design source keys and Game Session's allocated private tenant/runtime keys are separate. The earlier numeric fixture allocator is removed. The fixture lifecycle method refuses the unavailable World continuation before owner effects; it returns no active or admission result. +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. No World materialization/activation, canonical first-`OPEN`, or admission result is established. `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, holds and the later first-`OPEN` phase remain unavailable in this stage. The coordinator's completed launch-preparation phase is not a completed admission. Generic `StartSession` cannot construct the verified fixture carrier, and this stage grants no Human activation or production Game Design release-read permission. +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, and the retained published bootstrap does not establish completion of that phase or a completed admission. 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). diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 0bdf8fbf32..2599359007 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -2,7 +2,7 @@ ## Implementation Status -The bounded canonical fixture launch successor reads the exact authenticated Game Session `STARTING` allocation as source evidence. World fixture bootstrap and prepare/activate refuse before repository effects while source/Version materialization, canonical World association and holds are unavailable. Ordinary demo topology remains under its existing separate configuration. This read neither adopts numeric source keys nor supplies an `ACTIVE` state, first admission bind, Entity placement or operational-region authority. The guarded graph owner's stored and capture states remain unverified; [the World tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#current-status) records physical proof and remaining phases. +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. diff --git a/design/architecture/system-architecture-testing.md b/design/architecture/system-architecture-testing.md index b87175b223..750a85e4f5 100644 --- a/design/architecture/system-architecture-testing.md +++ b/design/architecture/system-architecture-testing.md @@ -179,7 +179,7 @@ Unknown, partial, stale, contradictory, or unavailable reset, mutation, or clean #### Run-owned v1 launch read evidence -Current bounded implementation stops after the closed Game Design producer and independently read canonical Game Session `STARTING` allocation. The existing fixture configuration selects those owners without a second launch flag. Authenticated allocation readback is source evidence only; World bootstrap and fixture prepare/activate refuse before effects while materialization and holds are unavailable. 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. +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. 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. @@ -189,7 +189,7 @@ The immutable source receipt has exactly fourteen envelope fields, including `cr 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 trusted data-package coordinator validates this complete fixed capability and receipt before creating the typed fixture carrier. 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. +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. 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 f8b331a51a..770fa6cd7e 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 @@ -8,17 +8,19 @@ This is a non-normative implementation tracker for Game Session runtime and tick ### Canonical fixture launch owner stage -The successor to the guarded World owner stage prepares the closed Game Design fixture-policy receipt and actual Game Session fresh association, catalog and canonical `STARTING` launch. The scheduler completes only that independently read owner phase. Its authenticated fixed World read echoes the original policy request/seal and owner-allocated private identities; it neither writes an admission pointer nor reports an active World. +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 obsolete numeric fixture allocator and its lifecycle dispatch are removed. The unavailable World continuation refuses before effects under the existing default-off fixture configuration; World materialization, holds, first `OPEN` and all four genuine handoffs remain open. 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 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. This proves the retained bootstrap composition; 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 current local fixture consumes Game Design's atomic run/project-bound 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 retries and binds the launch to the registered source. Game Session obtains its typed fixture carrier only through the trusted data-package parser; the coordinator currently performs only `createVerifiedFixtureStartingLaunch` and `readVerifiedFixtureLaunch`, preparing the canonical fresh association, catalog, and `STARTING` launch with independent owner readback. 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. +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 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. Fresh packaged `PLAY`/`LOOK` remains unqualified for the current candidate, as described above. 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 `GameSessionFixtureLaunchAssociationReadGrpcServiceTest` sources have not been run. 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. Fresh packaged `PLAY`/`LOOK` remains unqualified for the current candidate, as described above. 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. @@ -69,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, 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 opt-in fixture coordinator prepares only canonical STARTING allocation/readback; fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, and fixture World materialization, holds and first OPEN remain unavailable. 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 opt-in run-owned fixture preparation and canonical launch persistence are covered by [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java) and [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); [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 new tests are unrun and 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); they are unrun for this candidate and do not establish scheduled canonical preparation. 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. | 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 54d2156be6..b731371e67 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for world runtime and movement. C ### Canonical fixture launch receiving boundary -The canonical launch-owner successor adds authenticated fixed Game Session `STARTING` allocation readback. World bootstrap and fixture prepare/activate refuse before owner effects until actual World materialization and holds are composed. That source read grants no World lifecycle, first admission, Entity or operational-region authority. After the ordinary carry of [PR #3203](https://github.com/benhook1013/FireMUD/pull/3203) at `3ae5fffd4aec52101739c78d89cd6bd0ce5f9935`, the selected successor at `4cee3da213ad2b4d1ba27a4bbb7e418efee88a8a` passed its World whole-service check, formatting, static analysis and documentation checks in 2m43s: 292 fresh unit cases and 65 fresh service integration cases, with zero failures, errors or skips. The integration cases comprise 63 PostgreSQL-backed cases and two controlled mTLS socket tests. The socket cases qualify authentication and exact echo against controlled remote handlers; the database cases qualify before-effects refusal and independent passive storage, original rows/bytes/`xmin`, constraints and CAS. They establish neither a live remote Game Session producer, complete-commit producer, World activation nor packaged runtime. All four genuine handoffs remain open. +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`; original-capability teardown removed the claimed project containers, network and volumes. These packaged results qualify the retained bootstrap, while 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 @@ -36,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 retained initial-admission code includes the typed Game Session workload-only acquire RPC, durable World holds, lifecycle-row termination serialization and fail-closed reconciliation. Earlier coordinator-driven holds and World fixture PREPARING/ACTIVE binding belong to predecessor revisions. The current run-owned coordinator completes canonical Game Session STARTING allocation and independent readback only; World fixture bootstrap skips seeding, and prepare/activate refuse before owner effects. The World provider’s authenticated Game Session read verifies immutable fixture provenance and private allocation identity, but has no production lifecycle caller in this phase; it grants no 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 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. @@ -56,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 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 run-owned coordinator completes Game Session STARTING allocation and readback only. Earlier Compose-driven holds, preparing-epoch binding and ACTIVE replay belong to predecessor evidence. The World provider implements a bounded authenticated Game Session read, but the current lifecycle has no caller because prepare/activate refuse before effects; controlled provider proof is not production execution. Fixture bootstrap skips seeding without granting 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 current run-owned fixture path verifies the sealed Game Design receipt and authenticated Game Session STARTING allocation; fixture bootstrap skips all seeding with a diagnostic, and prepare/activate refuse before materialization, lifecycle, hold or first-OPEN effects. Earlier binding/ACTIVE replay and coordinator-driven hold execution are predecessor proof, not current fixture capability. | [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) | Current fixture materialization, activation, continuous Account protection, hold acquisition and first OPEN remain unavailable. 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.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. 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; the retained bootstrap has separate qualified runtime proof. 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. | 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/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java index 2387428f7d..2c59a056a7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -1,37 +1,48 @@ package net.firedevops.firemud.gamesession.data; +import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; 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 net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.WorldManagementClient; +import net.firedevops.firemud.gamesession.dto.GameInstanceDto; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; +import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; +import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -/** - * Bounded, internal-only launch preparation for an explicitly claimed run-owned Compose fixture. - */ +/** Bounded, internal-only bootstrap for an explicitly claimed run-owned Compose fixture. */ @Component public final class RunOwnedInitialAdmissionFixtureCoordinator { private static final Logger logger = LoggerFactory.getLogger(RunOwnedInitialAdmissionFixtureCoordinator.class); private static final int MAX_ATTEMPTS = 12; private static final long RETRY_INTERVAL_MS = 5_000L; + private static final String RUNNING = "RUNNING"; + private static final String DIGEST_DOMAIN = "firemud.run-owned-initial-admission-bind.v1"; private final boolean enabled; private final String capabilityPath; @@ -39,9 +50,9 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { 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 GameInstanceService gameInstanceService; + private final InitialAdmissionBindOwnerService ownerService; + private final WorldManagementClient worldManagementClient; private final AtomicInteger attempts = new AtomicInteger(); private final AtomicBoolean inProgress = new AtomicBoolean(); private final AtomicBoolean finished = new AtomicBoolean(); @@ -50,7 +61,6 @@ public final class RunOwnedInitialAdmissionFixtureCoordinator { private final AtomicReference acceptedSourceReceipt = new AtomicReference<>(); - @Autowired public RunOwnedInitialAdmissionFixtureCoordinator( @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, @@ -58,60 +68,19 @@ public RunOwnedInitialAdmissionFixtureCoordinator( @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); - } - - RunOwnedInitialAdmissionFixtureCoordinator( - 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 RunOwnedInitialAdmissionFixtureCoordinator( - boolean enabled, - String capabilityPath, - String sourceReceiptPath, - String runId, - String composeProjectName, - CommonGrpcClientProperties grpcProperties, - ObjectProvider configuredLaunchOwners, - String workloadNamespace, - GameSessionCanonicalInstanceLaunchRepository fixedLaunchOwner) { + GameInstanceService gameInstanceService, + InitialAdmissionBindOwnerService ownerService, + WorldManagementClient worldManagementClient) { 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; + this.gameInstanceService = Objects.requireNonNull(gameInstanceService, "gameInstanceService"); + this.ownerService = Objects.requireNonNull(ownerService, "ownerService"); + this.worldManagementClient = + Objects.requireNonNull(worldManagementClient, "worldManagementClient"); } @Scheduled(initialDelay = RETRY_INTERVAL_MS, fixedDelay = RETRY_INTERVAL_MS) @@ -128,40 +97,50 @@ void retryRunOwnedFixtureBootstrap() { try { RunOwnedInitialAdmissionFixtureCapability capability = - acceptCapability( - RunOwnedInitialAdmissionFixtureCapability.load( - declaredCapabilityPath(), runId, composeProjectName, grpcProperties)); + RunOwnedInitialAdmissionFixtureCapability.load( + declaredCapabilityPath(), runId, composeProjectName, grpcProperties); + RunOwnedInitialAdmissionFixtureCapability firstCapability = + acceptedCapability.updateAndGet(existing -> existing == null ? capability : existing); + if (!firstCapability.equals(capability)) { + throw unresolved(); + } RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = - acceptSourceReceipt( - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - declaredSourceReceiptPath(), - runId, - composeProjectName, - capability, - grpcProperties)); - CommittedFixtureLaunchOwnerEvidence result = coordinate(capability, sourceReceipt); - finished.set(true); - logger.info( - "Run-owned fixture launch preparation reached independent Game Session STARTING owner" - + " readback; firstOPEN and World materialization remain unavailable." - + " ownerStatus={}", - result.launch().status()); + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + declaredSourceReceiptPath(), runId, composeProjectName, capability, grpcProperties); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt firstSourceReceipt = + acceptedSourceReceipt.updateAndGet( + existing -> existing == null ? sourceReceipt : existing); + if (!firstSourceReceipt.equals(sourceReceipt)) { + throw unresolved(); + } + BootstrapResult result = coordinate(capability, sourceReceipt); + if (result == BootstrapResult.COMMITTED) { + finished.set(true); + logger.info( + "Run-owned initial-admission fixture committed; World hold reconciliation remains" + + " asynchronous."); + } else if (result == BootstrapResult.ABORTED) { + finished.set(true); + logger.warn( + "Run-owned initial-admission fixture has a durable abort; World retains ownership of" + + " hold reconciliation."); + } } catch (RuntimeException exception) { SafeDiagnostic diagnostic = safeDiagnostic(exception); if (attempt >= MAX_ATTEMPTS) { finished.set(true); logger.error( - "Run-owned fixture launch preparation did not reach independent STARTING owner" - + " readback after the bounded retry budget; firstOPEN and World materialization" - + " remain unavailable. exceptionType={} errorCode={} message={}", + "Run-owned initial-admission fixture did not reach a verified terminal result after" + + " the bounded retry budget; World hold state remains owner-controlled." + + " exceptionType={} errorCode={} message={}", diagnostic.exceptionType(), diagnostic.errorCode(), diagnostic.message()); } else { logger.warn( - "Run-owned fixture launch preparation attempt {}/{} remains unresolved; the same" - + " fixed operation identity will be retried. firstOPEN and World materialization" - + " remain unavailable. exceptionType={} errorCode={} message={}", + "Run-owned initial-admission fixture attempt {}/{} remains unresolved; the same" + + " stable operation identity will be retried. exceptionType={} errorCode={}" + + " message={}", attempt, MAX_ATTEMPTS, diagnostic.exceptionType(), @@ -173,115 +152,88 @@ void retryRunOwnedFixtureBootstrap() { } } - CommittedFixtureLaunchOwnerEvidence coordinate( + BootstrapResult coordinate( RunOwnedInitialAdmissionFixtureCapability capability, RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { 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); - } + RunOwnedInitialLaunchResult launch = + gameInstanceService.startRunOwnedInitialLaunch( + new StartSessionRequest( + capability.tenantId(), + capability.gameTemplateId(), + capability.operationId(), + capability.ownerAccountId()), + launchEvidence); + GameInstanceDto target = requireExactRunningTarget(launch, capability); - /** Loads only the fixed, independently verified fixture source; it performs no owner writes. */ - public RunOwnedInitialAdmissionLaunchEvidence loadFixedVerifiedEvidence() { - if (!enabled) { - throw unresolved(); - } - RunOwnedInitialAdmissionFixtureCapability capability = - acceptCapability( - RunOwnedInitialAdmissionFixtureCapability.load( - declaredCapabilityPath(), runId, composeProjectName, grpcProperties)); - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = - acceptSourceReceipt( - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - declaredSourceReceiptPath(), - runId, - composeProjectName, - capability, - grpcProperties)); - return RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt( - capability, sourceReceipt); - } + InitialAdmissionBindCatalogDescriptor descriptor = + new InitialAdmissionBindCatalogDescriptor( + capability.tenantId(), + capability.gameTemplateId(), + capability.worldSlug(), + capability.worldDisplayName(), + capability.realmSlug(), + capability.realmDisplayName(), + capability.requiresCharacterSelection()); + InitialAdmissionBindCatalog catalog = + ownerService.registerPublicSharedFixtureCatalog(descriptor); + requireExactCatalog(catalog, descriptor); - /** 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; - } + long gameInstanceId = target.id(); + long versionId = target.versionId(); + long activeLifecycleEpoch = launch.activeLifecycleEpoch(); + String requestDigest = + requestDigest(capability, catalog, gameInstanceId, versionId, activeLifecycleEpoch); + InitialAdmissionBindRequest request = + new InitialAdmissionBindRequest( + capability.tenantId(), + capability.worldSlug(), + capability.realmSlug(), + capability.operationId(), + requestDigest, + gameInstanceId, + versionId, + activeLifecycleEpoch); + InitialAdmissionBindAttempt attempt = ownerService.beginIntent(request); + requireExactAttempt(attempt, request, catalog, null, null); - /** Reads the actual coordinator-owned launch allocation through its canonical owner. */ - public FixtureCanonicalInstanceLaunch readFixedFixtureLaunch( - RunOwnedInitialAdmissionLaunchEvidence evidence) { - Objects.requireNonNull(evidence, "evidence").requireVerifiedFixture(); - if (!Objects.equals(workloadNamespace, evidence.sourceEvidence().targetNamespace())) { + AcquireInitialAdmissionBindHoldResponse response = + worldManagementClient.acquireInitialAdmissionBindHold( + capability.tenantId(), + gameInstanceId, + versionId, + activeLifecycleEpoch, + capability.operationId(), + requestDigest, + catalog.realmId(), + catalog.playableStateNamespaceId(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + catalog.catalogRevision()); + if (response == null || response.hasError() || !response.hasHold()) { throw unresolved(); } - return launchOwner().readVerifiedFixtureLaunch(evidence); - } + InitialAdmissionBindHold hold = response.getHold(); + InitialAdmissionBindHoldBinding binding = + requireExactHold(hold, request, catalog, gameInstanceId, versionId, activeLifecycleEpoch); - private RunOwnedInitialAdmissionFixtureCapability acceptCapability( - RunOwnedInitialAdmissionFixtureCapability capability) { - RunOwnedInitialAdmissionFixtureCapability first = - acceptedCapability.updateAndGet(existing -> existing == null ? capability : existing); - if (!Objects.equals(first, capability)) { - throw unresolved(); + if (isTerminalHoldStatus(hold.getStatus())) { + return resultFromProof( + ownerService.read(binding), binding, attempt, request.initialAdmissionRequestId()); } - return first; - } - - private RunOwnedInitialAdmissionFixtureCapability.SourceReceipt acceptSourceReceipt( - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt first = - acceptedSourceReceipt.updateAndGet(existing -> existing == null ? sourceReceipt : existing); - if (!Objects.equals(first, sourceReceipt)) { + if (!isRetryableHoldStatus(hold.getStatus())) { 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; + InitialAdmissionBindAttempt attached = ownerService.attachHold(binding); + requireExactAttempt(attached, request, catalog, binding.holdId(), binding.holdFence()); + InitialAdmissionBindOwnerProof proof = + attached.status() == InitialAdmissionBindAttempt.Status.PENDING + ? ownerService.commit(binding) + : ownerService.read(binding); + return resultFromProof(proof, binding, attached, request.initialAdmissionRequestId()); } private Path declaredCapabilityPath() { @@ -306,45 +258,6 @@ private Path declaredSourceReceiptPath() { } } - 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) { @@ -360,29 +273,9 @@ static void requireExactSourceReceipt( || !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( @@ -399,8 +292,273 @@ static void requireExactSourceReceipt( } } + private static GameInstanceDto requireExactRunningTarget( + RunOwnedInitialLaunchResult launch, RunOwnedInitialAdmissionFixtureCapability capability) { + if (launch == null || launch.gameInstance() == null || launch.activeLifecycleEpoch() <= 0L) { + throw unresolved(); + } + GameInstanceDto target = launch.gameInstance(); + if (target.id() == null + || target.id() <= 0L + || target.tenantId() == null + || target.tenantId() != capability.tenantId() + || target.gameTemplateId() == null + || target.gameTemplateId() != capability.gameTemplateId() + || target.ownerAccountId() == null + || target.ownerAccountId() != capability.ownerAccountId() + || target.versionId() == null + || target.versionId() <= 0L + || target.launchDescriptorId() == null + || target.launchDescriptorId().isBlank() + || !RUNNING.equals(target.status())) { + throw unresolved(); + } + return target; + } + + private static void requireExactCatalog( + InitialAdmissionBindCatalog catalog, InitialAdmissionBindCatalogDescriptor descriptor) { + if (catalog == null + || catalog.realmId() == null + || catalog.playableStateNamespaceId() == null + || catalog.tenantId() != descriptor.tenantId() + || catalog.gameTemplateId() != descriptor.gameTemplateId() + || !descriptor.worldSlug().equals(catalog.worldSlug()) + || !descriptor.worldDisplayName().equals(catalog.worldDisplayName()) + || !descriptor.realmSlug().equals(catalog.realmSlug()) + || !descriptor.realmDisplayName().equals(catalog.realmDisplayName()) + || catalog.catalogRevision() <= 0L + || !catalog.visible() + || !catalog.publicProductionRealm() + || catalog.requiresCharacterSelection() != descriptor.requiresCharacterSelection() + || !RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE.equals(catalog.stateScope()) + || !RunOwnedInitialAdmissionFixtureCapability.CHARACTER_CREATION_POLICY.equals( + catalog.characterCreationPolicy())) { + throw unresolved(); + } + } + + private static void requireExactAttempt( + InitialAdmissionBindAttempt attempt, + InitialAdmissionBindRequest request, + InitialAdmissionBindCatalog catalog, + String holdId, + String holdFence) { + if (attempt == null + || attempt.attemptId() == null + || attempt.tenantId() != request.tenantId() + || !request.initialAdmissionRequestId().equals(attempt.initialAdmissionRequestId()) + || !request.requestDigest().equals(attempt.requestDigest()) + || !catalog.realmId().equals(attempt.realmId()) + || !catalog.playableStateNamespaceId().equals(attempt.playableStateNamespaceId()) + || !RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE.equals( + attempt.playableStateScope()) + || !attempt.expectedNoPriorPointer() + || attempt.catalogRevision() != catalog.catalogRevision() + || attempt.gameInstanceId() != request.gameInstanceId() + || attempt.versionId() != request.versionId() + || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() + || (holdId != null && !holdId.equals(asCanonicalUuid(attempt.holdId()))) + || (holdFence != null && !holdFence.equals(asCanonicalUuid(attempt.holdFence())))) { + throw unresolved(); + } + } + + private static InitialAdmissionBindHoldBinding requireExactHold( + InitialAdmissionBindHold hold, + InitialAdmissionBindRequest request, + InitialAdmissionBindCatalog catalog, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch) { + if (hold == null + || !isCanonicalUuid(hold.getHoldId()) + || !isCanonicalUuid(hold.getHoldFence()) + || !Long.toString(request.tenantId()).equals(hold.getTenantId()) + || !catalog.realmId().toString().equals(hold.getRealmUuid()) + || !catalog + .playableStateNamespaceId() + .toString() + .equals(hold.getPlayableStateNamespaceUuid()) + || hold.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || !Long.toString(gameInstanceId).equals(hold.getGameInstanceId()) + || !Long.toString(versionId).equals(hold.getVersionId()) + || hold.getActiveLifecycleEpoch() != activeLifecycleEpoch + || !request.initialAdmissionRequestId().equals(hold.getInitialAdmissionRequestId()) + || !request.requestDigest().equals(hold.getRequestDigest()) + || !hold.getExpectedNoPriorPointer() + || hold.getExpectedCatalogRevision() != catalog.catalogRevision() + || hold.getStatus() + == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED) { + throw unresolved(); + } + return new InitialAdmissionBindHoldBinding( + hold.getHoldId(), + hold.getHoldFence(), + request.tenantId(), + hold.getRealmUuid(), + hold.getPlayableStateNamespaceUuid(), + RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE, + gameInstanceId, + versionId, + activeLifecycleEpoch, + request.initialAdmissionRequestId(), + request.requestDigest(), + true, + catalog.catalogRevision()); + } + + private static BootstrapResult resultFromProof( + InitialAdmissionBindOwnerProof proof, + InitialAdmissionBindHoldBinding binding, + InitialAdmissionBindAttempt attempt, + String expectedRequestId) { + if (!matchesExactProof(proof, binding, attempt, expectedRequestId)) { + throw unresolved(); + } + if (proof.outcome() == Outcome.COMMITTED) { + return BootstrapResult.COMMITTED; + } + if (proof.outcome() == Outcome.ABORTED && proof.futureCommitPrevented()) { + return BootstrapResult.ABORTED; + } + throw unresolved(); + } + + private static boolean matchesExactProof( + InitialAdmissionBindOwnerProof proof, + InitialAdmissionBindHoldBinding binding, + InitialAdmissionBindAttempt attempt, + String expectedRequestId) { + if (proof == null + || proof.holdId() == null + || !binding.holdId().equals(proof.holdId()) + || !binding.holdFence().equals(proof.holdFence()) + || proof.tenantId() != binding.tenantId() + || !binding.realmUuid().equals(proof.realmUuid()) + || !binding.playableStateNamespaceUuid().equals(proof.playableStateNamespaceUuid()) + || !binding.playableStateScope().equals(proof.playableStateScope()) + || proof.gameInstanceId() != binding.gameInstanceId() + || proof.versionId() != binding.versionId() + || proof.activeLifecycleEpoch() != binding.activeLifecycleEpoch() + || !expectedRequestId.equals(proof.initialAdmissionRequestId()) + || !binding.requestDigest().equals(proof.requestDigest()) + || proof.expectedNoPriorPointer() != binding.expectedNoPriorPointer() + || proof.expectedCatalogRevision() != binding.expectedCatalogRevision() + || attempt == null + || !attempt.attemptId().toString().equals(proof.ownerProofId())) { + return false; + } + + if (proof.outcome() == Outcome.COMMITTED) { + return proof.pointerAuditId() != null + && isCanonicalPositiveLong(proof.pointerAuditId()) + && proof.pointerVersion() == 1L + && binding.requestDigest().equals(proof.pointerAuditRequestDigest()) + && !proof.futureCommitPrevented(); + } + if (proof.outcome() == Outcome.ABORTED) { + return proof.pointerAuditId() == null + && proof.pointerVersion() == 0L + && proof.pointerAuditRequestDigest() == null + && proof.futureCommitPrevented(); + } + return false; + } + + private static boolean isTerminalHoldStatus(InitialAdmissionBindHoldStatus status) { + return status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED + || status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED; + } + + private static boolean isRetryableHoldStatus(InitialAdmissionBindHoldStatus status) { + return status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING + || status + == InitialAdmissionBindHoldStatus + .INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED; + } + + private static String requestDigest( + RunOwnedInitialAdmissionFixtureCapability capability, + InitialAdmissionBindCatalog catalog, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch) { + StringBuilder canonical = new StringBuilder(); + appendDigestField(canonical, "domain", DIGEST_DOMAIN); + appendDigestField(canonical, "operationId", capability.operationId()); + appendDigestField(canonical, "tenantId", Long.toString(capability.tenantId())); + appendDigestField(canonical, "gameTemplateId", Long.toString(capability.gameTemplateId())); + appendDigestField(canonical, "ownerAccountId", Long.toString(capability.ownerAccountId())); + appendDigestField(canonical, "worldSlug", capability.worldSlug()); + appendDigestField(canonical, "worldDisplayName", capability.worldDisplayName()); + appendDigestField(canonical, "realmSlug", capability.realmSlug()); + appendDigestField(canonical, "realmDisplayName", capability.realmDisplayName()); + appendDigestField( + canonical, + "requiresCharacterSelection", + Boolean.toString(capability.requiresCharacterSelection())); + appendDigestField(canonical, "realmId", catalog.realmId().toString()); + appendDigestField( + canonical, "playableStateNamespaceId", catalog.playableStateNamespaceId().toString()); + appendDigestField( + canonical, "playableStateScope", RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE); + appendDigestField(canonical, "expectedNoPriorPointer", "true"); + appendDigestField(canonical, "gameInstanceId", Long.toString(gameInstanceId)); + appendDigestField(canonical, "versionId", Long.toString(versionId)); + appendDigestField(canonical, "activeLifecycleEpoch", Long.toString(activeLifecycleEpoch)); + appendDigestField(canonical, "catalogRevision", Long.toString(catalog.catalogRevision())); + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(canonical.toString().getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void appendDigestField(StringBuilder canonical, String name, String value) { + int nameBytes = name.getBytes(StandardCharsets.UTF_8).length; + int valueBytes = value.getBytes(StandardCharsets.UTF_8).length; + canonical + .append(nameBytes) + .append(':') + .append(name) + .append(valueBytes) + .append(':') + .append(value); + } + + private static String asCanonicalUuid(UUID value) { + return value == null ? null : value.toString(); + } + + private static boolean isCanonicalUuid(String value) { + if (value == null) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static boolean isCanonicalPositiveLong(String value) { + if (value == null) { + return false; + } + try { + long parsed = Long.parseLong(value); + return parsed > 0L && Long.toString(parsed).equals(value); + } catch (NumberFormatException exception) { + return false; + } + } + private static RuntimeException unresolved() { - return new IllegalStateException("Run-owned fixture launch preparation remains unresolved"); + return new IllegalStateException("Run-owned initial-admission fixture remains unresolved"); } private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { @@ -414,7 +572,7 @@ private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { return new SafeDiagnostic( exception.getClass().getSimpleName(), "FIXTURE_STATE_UNRESOLVED", - "Fixture launch state remains unresolved."); + "Fixture state remains unresolved."); } return new SafeDiagnostic( exception.getClass().getSimpleName(), @@ -424,12 +582,8 @@ private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { private record SafeDiagnostic(String exceptionType, String errorCode, String message) {} - record CommittedFixtureLaunchOwnerEvidence( - RunOwnedInitialAdmissionLaunchEvidence launchEvidence, - FixtureCanonicalInstanceLaunch launch) { - CommittedFixtureLaunchOwnerEvidence { - Objects.requireNonNull(launchEvidence, "launchEvidence"); - Objects.requireNonNull(launch, "launch"); - } + enum BootstrapResult { + COMMITTED, + ABORTED } } 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 d6aac679f5..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 @@ -69,7 +69,7 @@ private 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( @@ -128,7 +128,7 @@ private VerifiedFixture verified() { if (!(verification instanceof VerifiedFixture fixture)) { throw new IllegalArgumentException("Verified run-owned fixture provenance is required"); } - RunOwnedInitialAdmissionFixtureCoordinator.requireExactSourceReceipt( + RunOwnedCanonicalLaunchPreparationOwner.requireExactSourceReceipt( fixture.capability(), fixture.receipt()); String requestDigest = RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( 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 d9a2d29dd6..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 @@ -20,7 +20,7 @@ public final class ProtectedGameSessionLoginGrpcInterceptor implements ServerInt "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/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index 246784ac10..62844772ac 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -2,10 +2,17 @@ import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.HashSet; +import java.util.HexFormat; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; import net.firedevops.firemud.common.saga.SagaBuilder; import net.firedevops.firemud.common.saga.SagaException; import net.firedevops.firemud.common.saga.SagaRunner; @@ -52,6 +59,8 @@ public class GameInstanceServiceImpl implements GameInstanceService { private static final String STATUS_RUNNING = "RUNNING"; private static final String STATUS_STOPPING = "STOPPING"; private static final String STATUS_STOPPED = "STOPPED"; + private static final String RUN_OWNED_LAUNCH_DIGEST_SCHEMA = + "firemud.run-owned-initial-launch/v2"; private static final String SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION = "v1"; private static final String WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE = "world activation authority unavailable"; @@ -233,20 +242,123 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace } /** - * Validates verified fixture launch evidence, then refuses before World materialization or first - * OPEN admission. Canonical STARTING allocation is owned by the fixture coordinator. + * Starts or resumes a local fixture launch under a durable, tenant/request-bound owner identity. + * This method has no transport binding; the run-owned fixture coordinator is its only caller. */ @Override @Timed(value = "gamesession.run_owned_initial_launch") public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch( StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { validateRunOwnedLaunchRequest(request); - Objects.requireNonNull(launchEvidence, "launchEvidence").requireVerifiedFixture(); requireRunOwnedSourceMatchesRequest(request, launchEvidence); - throw new IllegalStateException( - "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: canonical STARTING launch preparation" - + " is owned by the fixture coordinator; World materialization and first OPEN" - + " admission remain unavailable"); + ResolvedLaunchDescriptor resolvedLaunchDescriptor = + preflightRunOwnedLaunch(request, launchEvidence); + requireDescriptorMatchesRequest(request, resolvedLaunchDescriptor); + String requestDigest = runOwnedLaunchRequestDigest(request, launchEvidence); + GameInstance reserved = + inTransaction( + () -> reserveRunOwnedInitialLaunch(request, resolvedLaunchDescriptor, requestDigest), + "reserve run-owned initial launch"); + long gameInstanceId = reserved.getId(); + requireRunOwnedTargetCanResume(reserved); + + if (STATUS_RUNNING.equals(reserved.getStatus())) { + long activeEpoch = requireRunOwnedRecordedActiveEpoch(reserved); + WorldInstanceLifecycleSnapshot current = + readRunOwnedWorldLifecycle(reserved, request, resolvedLaunchDescriptor); + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World"); + } + if (current.getStatus() + != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + throw runOwnedWorldStatusFailure(current.getStatus()); + } + requireRunOwnedActiveEpoch(current, activeEpoch); + sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_RUNNING)); + GameInstance completed = + inTransaction( + () -> + completeRunOwnedInitialLaunch( + request, + requestDigest, + resolvedLaunchDescriptor, + gameInstanceId, + activeEpoch), + "complete run-owned initial launch retry"); + return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); + } + + validateStartDependencies(); + + WorldInstanceLifecycleSnapshot prepared = + prepareRunOwnedWorldInstance(reserved, resolvedLaunchDescriptor, request); + if (prepared.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + reserved = + inTransaction( + () -> + recordRunOwnedPreparingEpoch( + request, + requestDigest, + resolvedLaunchDescriptor, + gameInstanceId, + prepared.getLifecycleEpoch()), + "record run-owned preparing epoch"); + } else { + reserved = + reloadRunOwnedInitialLaunch( + request, requestDigest, resolvedLaunchDescriptor, gameInstanceId); + } + + WorldInstanceLifecycleSnapshot current = + readRunOwnedWorldLifecycle(reserved, request, resolvedLaunchDescriptor); + long activeEpoch; + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + if (STATUS_RUNNING.equals(reserved.getStatus())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World"); + } + if (reserved.getRunOwnedStartActiveEpoch() != null) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: starting owner row already has an active epoch"); + } + long preparingEpoch = requireRunOwnedPreparingEpoch(reserved); + activeEpoch = Math.addExact(preparingEpoch, 1L); + if (current.getLifecycleEpoch() != preparingEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch differs from the durable launch fence"); + } + if (STATUS_STARTING.equals(reserved.getStatus())) { + sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_STARTING)); + } + activateAndReadBackRunOwnedWorld( + reserved, request, resolvedLaunchDescriptor, preparingEpoch, activeEpoch); + } else if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + long preparingEpoch = requireRunOwnedPreparingEpoch(reserved); + activeEpoch = Math.addExact(preparingEpoch, 1L); + if (reserved.getRunOwnedStartActiveEpoch() != null + && reserved.getRunOwnedStartActiveEpoch() != activeEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation result"); + } + requireRunOwnedActiveEpoch(current, activeEpoch); + } else { + throw runOwnedWorldStatusFailure(current.getStatus()); + } + + GameInstanceDto runningState = withStatus(snapshot(reserved), STATUS_RUNNING); + sessionStateService.saveState(runningState); + GameInstance completed = + inTransaction( + () -> + completeRunOwnedInitialLaunch( + request, requestDigest, resolvedLaunchDescriptor, gameInstanceId, activeEpoch), + "complete run-owned initial launch"); + return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); } @Override @@ -626,6 +738,508 @@ private void validateRunOwnedLaunchRequest(StartSessionRequest request) { } } + private static String runOwnedLaunchRequestDigest( + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { + AuthoredWorldSourceEvidence sourceEvidence = launchEvidence.sourceEvidence(); + StringBuilder preimage = new StringBuilder(); + appendDigestField(preimage, "schema", RUN_OWNED_LAUNCH_DIGEST_SCHEMA); + appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); + appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); + appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); + appendDigestField(preimage, "ownerAccountId", Long.toString(request.ownerAccountId())); + appendDigestField(preimage, "replaceExistingFirst", "false"); + appendDigestField( + preimage, "sourceSchemaVersion", Integer.toString(sourceEvidence.schemaVersion())); + appendDigestField(preimage, "sourceTargetNamespace", sourceEvidence.targetNamespace()); + appendDigestField( + preimage, "sourceRegistrationRequestId", sourceEvidence.registrationRequestId().toString()); + appendDigestField(preimage, "sourceOperationId", sourceEvidence.operationId().toString()); + appendDigestField(preimage, "sourceRequestDigest", sourceEvidence.requestDigest()); + appendDigestField( + preimage, "sourceCanonicalTenantId", sourceEvidence.canonicalTenantId().toString()); + appendDigestField(preimage, "sourceTenantSlug", sourceEvidence.tenantSlug()); + appendDigestField(preimage, "sourceWorldSlug", sourceEvidence.worldSlug()); + appendDigestField(preimage, "sourceWorldDisplayName", sourceEvidence.worldDisplayName()); + appendDigestField(preimage, "sourceGameRowId", Long.toString(sourceEvidence.sourceGameRowId())); + appendDigestField(preimage, "sourceGameTenantKey", sourceEvidence.sourceGameTenantKey()); + appendDigestField(preimage, "sourceProvenanceKind", sourceEvidence.provenanceKind()); + appendDigestField(preimage, "sourceEvidenceDigest", sourceEvidence.evidenceDigest()); + appendDigestField(preimage, "launchReadEvidenceSchema", launchEvidence.schema()); + appendDigestField( + preimage, + "launchReadEvidenceGameTemplateId", + Long.toString(launchEvidence.gameTemplateId())); + appendDigestField( + preimage, + "publishedReleaseBundleSnapshotSha256", + sha256Hex(launchEvidence.publishedReleaseBundle().toByteArray())); + appendDigestField( + preimage, + "versionAssetArtifactStateSnapshotSha256", + sha256Hex(launchEvidence.versionAssetArtifactState().toByteArray())); + appendDigestField( + preimage, + "versionStateSnapshotSha256", + sha256Hex(launchEvidence.versionState().toByteArray())); + return sha256Hex(preimage.toString().getBytes(StandardCharsets.UTF_8)); + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } + + private static void appendDigestField(StringBuilder preimage, String name, String value) { + int nameByteLength = name.getBytes(StandardCharsets.UTF_8).length; + int valueByteLength = value.getBytes(StandardCharsets.UTF_8).length; + preimage + .append(nameByteLength) + .append(':') + .append(name) + .append(valueByteLength) + .append(':') + .append(value); + } + + private void requireDescriptorMatchesRequest( + StartSessionRequest request, ResolvedLaunchDescriptor descriptor) { + if (descriptor.tenantId() != request.tenantId() + || descriptor.gameTemplateId() != request.gameTemplateId() + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_REQUEST_MISMATCH: resolved descriptor is not bound to this request"); + } + if (descriptor.launchDescriptorId() == null + || descriptor.launchDescriptorId().isBlank() + || descriptor.versionId() <= 0L + || descriptor.releaseBundleId() <= 0L + || descriptor.versionStateEpoch() <= 0L + || descriptor.generationConfigRevision() == null + || descriptor.generationConfigRevision().isBlank() + || descriptor.publishedReleaseBundleRef() == null + || descriptor.publishedReleaseBundleRef().isBlank()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_INCOMPLETE: resolved descriptor is missing exact published inputs"); + } + } + + private GameInstance reserveRunOwnedInitialLaunch( + StartSessionRequest request, ResolvedLaunchDescriptor descriptor, String requestDigest) { + repository.lockRunOwnedStartIdentity(request.tenantId(), request.controlPlaneRequestId()); + Optional existing = + repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( + request.tenantId(), request.controlPlaneRequestId()); + if (existing.isPresent()) { + requireSameRunOwnedInitialLaunch(existing.get(), request, descriptor, requestDigest); + return existing.get(); + } + + GameInstance instance = new GameInstance(); + instance.setTenantId(request.tenantId()); + instance.setRuntimeVersion(Long.toString(descriptor.versionId())); + instance.setGameTemplateId(request.gameTemplateId()); + instance.setLaunchDescriptorId(descriptor.launchDescriptorId()); + instance.setVersionId(descriptor.versionId()); + instance.setReleaseBundleId(descriptor.releaseBundleId()); + instance.setVersionStateEpoch(descriptor.versionStateEpoch()); + instance.setGenerationConfigRevision(descriptor.generationConfigRevision()); + instance.setRemapSetId(descriptor.remapSetId()); + instance.setOwnerAccountId(request.ownerAccountId()); + instance.setStatus(STATUS_STARTING); + instance.setRunOwnedStartRequestId(request.controlPlaneRequestId()); + instance.setRunOwnedStartRequestDigest(requestDigest); + instance.setRunOwnedStartPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()); + return repository.save(instance); + } + + private void requireSameRunOwnedInitialLaunch( + GameInstance instance, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + String requestDigest) { + if (!request.controlPlaneRequestId().equals(instance.getRunOwnedStartRequestId()) + || !requestDigest.equals(instance.getRunOwnedStartRequestDigest()) + || !Objects.equals(instance.getTenantId(), request.tenantId()) + || !Objects.equals(instance.getOwnerAccountId(), request.ownerAccountId()) + || !Objects.equals(instance.getGameTemplateId(), request.gameTemplateId()) + || !Objects.equals(instance.getRuntimeVersion(), Long.toString(descriptor.versionId())) + || !Objects.equals(instance.getLaunchDescriptorId(), descriptor.launchDescriptorId()) + || !Objects.equals(instance.getVersionId(), descriptor.versionId()) + || !Objects.equals(instance.getReleaseBundleId(), descriptor.releaseBundleId()) + || !Objects.equals(instance.getVersionStateEpoch(), descriptor.versionStateEpoch()) + || !Objects.equals( + instance.getGenerationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals(instance.getRemapSetId(), descriptor.remapSetId()) + || !Objects.equals( + instance.getRunOwnedStartPublishedReleaseBundleRef(), + descriptor.publishedReleaseBundleRef())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_CONFLICT: request or resolved descriptor changed"); + } + } + + private void requireRunOwnedTargetCanResume(GameInstance instance) { + if (instance.getId() == null + || instance.getRunOwnedStartRequestId() == null + || instance.getRunOwnedStartRequestDigest() == null) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: durable request identity is incomplete"); + } + if (!STATUS_STARTING.equals(instance.getStatus()) + && !STATUS_RUNNING.equals(instance.getStatus())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_TARGET_NOT_RESUMABLE: existing instance is not starting or running"); + } + if (STATUS_RUNNING.equals(instance.getStatus())) { + requireRunOwnedRecordedActiveEpoch(instance); + } + } + + private long requireRunOwnedRecordedActiveEpoch(GameInstance instance) { + long preparingEpoch = requireRunOwnedPreparingEpoch(instance); + Long activeEpoch = instance.getRunOwnedStartActiveEpoch(); + if (activeEpoch == null || activeEpoch <= 0L) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_EPOCH_UNAVAILABLE: running instance has no active epoch proof"); + } + if (activeEpoch != Math.addExact(preparingEpoch, 1L)) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: durable ACTIVE epoch differs from the prepare fence"); + } + return activeEpoch; + } + + private GameInstance recordRunOwnedPreparingEpoch( + StartSessionRequest request, + String requestDigest, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId, + long preparingEpoch) { + if (preparingEpoch <= 0L) { + throw new IllegalStateException( + "WORLD_AUTHORITY_MALFORMED: lifecycle epoch must be positive"); + } + GameInstance instance = + repository + .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); + Long recordedEpoch = instance.getRunOwnedStartPreparingEpoch(); + if (recordedEpoch != null) { + if (recordedEpoch != preparingEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch changed across retries"); + } + return instance; + } + if (instance.getRunOwnedStartActiveEpoch() != null) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_EPOCH_MISMATCH: active epoch exists without its prepare fence"); + } + instance.setRunOwnedStartPreparingEpoch(preparingEpoch); + return repository.save(instance); + } + + private GameInstance reloadRunOwnedInitialLaunch( + StartSessionRequest request, + String requestDigest, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId) { + return inTransaction( + () -> { + GameInstance instance = + repository + .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); + return instance; + }, + "reload run-owned initial launch"); + } + + private GameInstance completeRunOwnedInitialLaunch( + StartSessionRequest request, + String requestDigest, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId, + long activeEpoch) { + GameInstance instance = + repository + .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); + long expectedActiveEpoch = Math.addExact(requireRunOwnedPreparingEpoch(instance), 1L); + if (activeEpoch != expectedActiveEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation fence"); + } + if (instance.getRunOwnedStartActiveEpoch() != null + && instance.getRunOwnedStartActiveEpoch() != activeEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch changed across retries"); + } + if (!STATUS_STARTING.equals(instance.getStatus()) + && !STATUS_RUNNING.equals(instance.getStatus())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_TARGET_NOT_RESUMABLE: existing instance is not starting or running"); + } + instance.setRunOwnedStartActiveEpoch(activeEpoch); + instance.setStatus(STATUS_RUNNING); + return repository.save(instance); + } + + private long requireRunOwnedPreparingEpoch(GameInstance instance) { + Long epoch = instance.getRunOwnedStartPreparingEpoch(); + if (epoch == null || epoch <= 0L) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_EPOCH_UNAVAILABLE: exact PREPARING epoch is not durable"); + } + return epoch; + } + + private WorldInstanceLifecycleSnapshot prepareRunOwnedWorldInstance( + GameInstance instance, ResolvedLaunchDescriptor descriptor, StartSessionRequest request) { + if (worldManagementClient == null) { + throw new IllegalStateException(WORLD_PREPARATION_AUTHORITY_UNAVAILABLE); + } + final PrepareWorldInstanceResponse response; + try { + response = + worldManagementClient.prepareWorldInstance( + request.tenantId(), + instance.getId(), + request.gameTemplateId(), + request.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + instance.getScriptPatchVersion(), + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + descriptor.remapSetId()); + } catch (RuntimeException exception) { + throw new IllegalStateException(WORLD_PREPARATION_AUTHORITY_UNAVAILABLE, exception); + } + if (response == null) { + throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); + } + if (response.hasError()) { + throw new IllegalStateException( + response.getError().getCode() + ": " + response.getError().getMessage()); + } + WorldInstanceLifecycleSnapshot snapshot = + requireWorldSnapshot( + response.hasWorldInstance(), + response.getWorldInstance(), + request.tenantId(), + instance.getId(), + null); + requireRunOwnedWorldDescriptor(snapshot, request, descriptor, instance.getId()); + requireKnownRunOwnedWorldStatus(snapshot.getStatus()); + return snapshot; + } + + private WorldInstanceLifecycleSnapshot readRunOwnedWorldLifecycle( + GameInstance instance, StartSessionRequest request, ResolvedLaunchDescriptor descriptor) { + if (worldManagementClient == null) { + throw new IllegalStateException(WORLD_LIFECYCLE_AUTHORITY_UNAVAILABLE); + } + final GetWorldInstanceLifecycleResponse response; + try { + response = + worldManagementClient.getWorldInstanceLifecycle(request.tenantId(), instance.getId()); + } catch (RuntimeException exception) { + throw new IllegalStateException(WORLD_LIFECYCLE_AUTHORITY_UNAVAILABLE, exception); + } + if (response == null) { + throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); + } + if (response.hasError()) { + throw new IllegalStateException( + response.getError().getCode() + ": " + response.getError().getMessage()); + } + WorldInstanceLifecycleSnapshot snapshot = + requireWorldSnapshot( + response.hasWorldInstance(), + response.getWorldInstance(), + request.tenantId(), + instance.getId(), + null); + requireRunOwnedWorldDescriptor(snapshot, request, descriptor, instance.getId()); + requireKnownRunOwnedWorldStatus(snapshot.getStatus()); + return snapshot; + } + + private WorldInstanceLifecycleSnapshot activateAndReadBackRunOwnedWorld( + GameInstance instance, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + long preparingEpoch, + long activeEpoch) { + if (worldManagementClient == null) { + throw new IllegalStateException(WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE); + } + final ActivatePreparedWorldInstanceResponse response; + try { + response = + worldManagementClient.activatePreparedWorldInstance( + request.tenantId(), instance.getId(), preparingEpoch); + } catch (RuntimeException activationFailure) { + return reconcileRunOwnedActivationFailure( + instance, request, descriptor, preparingEpoch, activeEpoch, activationFailure); + } + if (response == null) { + throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); + } + if (response.hasError()) { + return reconcileRunOwnedActivationFailure( + instance, + request, + descriptor, + preparingEpoch, + activeEpoch, + new IllegalStateException( + response.getError().getCode() + ": " + response.getError().getMessage())); + } + WorldInstanceLifecycleSnapshot activated = + requireWorldSnapshot( + response.hasWorldInstance(), + response.getWorldInstance(), + request.tenantId(), + instance.getId(), + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); + requireRunOwnedWorldDescriptor(activated, request, descriptor, instance.getId()); + requireRunOwnedActiveEpoch(activated, activeEpoch); + + WorldInstanceLifecycleSnapshot readback = + readRunOwnedWorldLifecycle(instance, request, descriptor); + if (readback.getStatus() + != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + throw runOwnedWorldStatusFailure(readback.getStatus()); + } + requireRunOwnedActiveEpoch(readback, activeEpoch); + return readback; + } + + private WorldInstanceLifecycleSnapshot reconcileRunOwnedActivationFailure( + GameInstance instance, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + long preparingEpoch, + long activeEpoch, + RuntimeException activationFailure) { + WorldInstanceLifecycleSnapshot current = + readRunOwnedWorldLifecycle(instance, request, descriptor); + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + requireRunOwnedActiveEpoch(current, activeEpoch); + return current; + } + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + if (current.getLifecycleEpoch() != preparingEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch differs from the durable launch fence", + activationFailure); + } + throw new IllegalStateException(WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE, activationFailure); + } + throw runOwnedWorldStatusFailure(current.getStatus()); + } + + private void requireRunOwnedWorldDescriptor( + WorldInstanceLifecycleSnapshot snapshot, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId) { + final long tenantId; + final long instanceId; + final long templateId; + final long versionId; + final long releaseBundleId; + try { + tenantId = RequestIdValidation.requirePositiveLong(snapshot.getTenantId(), "tenantId"); + instanceId = + RequestIdValidation.requirePositiveLong(snapshot.getGameInstanceId(), "gameInstanceId"); + templateId = + RequestIdValidation.requirePositiveLong(snapshot.getGameTemplateId(), "gameTemplateId"); + versionId = RequestIdValidation.requirePositiveLong(snapshot.getVersionId(), "versionId"); + releaseBundleId = + RequestIdValidation.requirePositiveLong(snapshot.getReleaseBundleId(), "releaseBundleId"); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "WORLD_AUTHORITY_MALFORMED: " + exception.getMessage(), exception); + } + if (tenantId != request.tenantId() + || instanceId != gameInstanceId + || templateId != request.gameTemplateId() + || !request.controlPlaneRequestId().equals(snapshot.getControlPlaneRequestId()) + || !descriptor.launchDescriptorId().equals(snapshot.getLaunchDescriptorId()) + || versionId != descriptor.versionId() + || releaseBundleId != descriptor.releaseBundleId() + || !descriptor.generationConfigRevision().equals(snapshot.getGenerationConfigRevision()) + || !descriptor.publishedReleaseBundleRef().equals(snapshot.getPublishedReleaseBundleRef()) + || snapshot.getVersionStateEpoch() != descriptor.versionStateEpoch() + || !Objects.equals( + normalizeBlank(descriptor.remapSetId()), normalizeBlank(snapshot.getRemapSetId()))) { + throw new IllegalStateException( + "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor"); + } + } + + private void requireKnownRunOwnedWorldStatus(WorldInstanceLifecycleStatus status) { + if (status == null + || status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED + || status == WorldInstanceLifecycleStatus.UNRECOGNIZED) { + throw new IllegalStateException("WORLD_AUTHORITY_MALFORMED: lifecycle status is unavailable"); + } + } + + private void requireRunOwnedActiveEpoch( + WorldInstanceLifecycleSnapshot snapshot, long expectedActiveEpoch) { + if (snapshot.getLifecycleEpoch() != expectedActiveEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation result"); + } + } + + private RuntimeException runOwnedWorldStatusFailure(WorldInstanceLifecycleStatus status) { + if (status + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) { + return new LifecycleOutcomeException( + "WORLD_INSTANCE_LIFECYCLE_FAILED_PRE_ACTIVATION", + "run-owned instance failed before activation and remains terminal for this request"); + } + if (status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATING) { + return new LifecycleOutcomeException( + "WORLD_TERMINATION_IN_PROGRESS", "run-owned instance termination is in progress"); + } + if (status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) { + return new LifecycleOutcomeException( + "WORLD_INSTANCE_TERMINATED", "run-owned instance is already terminated"); + } + return new IllegalStateException( + "WORLD_AUTHORITY_MALFORMED: lifecycle status cannot resume initial launch"); + } + + private String normalizeBlank(String value) { + return value == null || value.isBlank() ? null : value; + } + private GameInstanceDto withStatus(GameInstanceDto snapshot, String status) { return new GameInstanceDto( snapshot.id(), @@ -672,6 +1286,83 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { return preflightLaunchResponse(request, descriptorResponse, descriptorTenantId); } + private ResolvedLaunchDescriptor preflightRunOwnedLaunch( + StartSessionRequest request, RunOwnedInitialAdmissionLaunchEvidence launchEvidence) { + if (gameDesignClient == null) { + throw new IllegalStateException("launch descriptor authority unavailable"); + } + AuthoredWorldSourceEvidence sourceEvidence = launchEvidence.sourceEvidence(); + ResolveLaunchDescriptorResponse descriptorResponse = + gameDesignClient.resolveLaunchDescriptor( + request.tenantId(), + request.gameTemplateId(), + request.controlPlaneRequestId(), + sourceEvidence); + AuthoredWorldLaunchDescriptorEvidence actualDescriptorEvidence = + requireExactAuthoredWorldDescriptorRequest(request, sourceEvidence, descriptorResponse); + if (descriptorResponse.hasError()) { + throw new IllegalArgumentException( + descriptorResponse.getError().getCode() + + ": " + + descriptorResponse.getError().getMessage()); + } + requireRunOwnedLaunchDescriptorMatchesReceipt( + actualDescriptorEvidence, launchEvidence.launchDescriptor()); + if (!descriptorResponse.hasLaunchDescriptor()) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); + } + var descriptor = descriptorResponse.getLaunchDescriptor(); + var bundle = launchEvidence.publishedReleaseBundle(); + var artifactState = launchEvidence.versionAssetArtifactState(); + var versionState = launchEvidence.versionState(); + String tenantId = Long.toString(request.tenantId()); + if (!RunOwnedInitialAdmissionLaunchEvidence.SCHEMA.equals(launchEvidence.schema()) + || launchEvidence.gameTemplateId() != request.gameTemplateId() + || descriptor.getGameTemplateId() != request.gameTemplateId() + || descriptor.getVersionId() != bundle.getVersionId() + || descriptor.getReleaseBundleId() != bundle.getId() + || descriptor.getVersionStateEpoch() != versionState.getVersionStateEpoch() + || !descriptor.getPublishedReleaseBundleRef().equals(bundle.getPublishedReleaseBundleRef()) + || !descriptor.getGenerationConfigRevision().equals(bundle.getGenerationConfigRevision()) + || !sourceEvidence.canonicalTenantId().toString().equals(bundle.getCanonicalTenantId()) + || !tenantId.equals(artifactState.getTenantId()) + || artifactState.getVersionId() != descriptor.getVersionId() + || artifactState.getStateEpoch() <= 0L + || artifactState.getArtifactState() + != net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED + || !artifactState.getManifestHash().equals(bundle.getManifestHash()) + || artifactState.getExportedVersionNumber() != bundle.getVersionNumber() + || !artifactState + .getExportedManifestAssetKeysList() + .containsAll(bundle.getRequiredManifestAssetKeysList()) + || !tenantId.equals(versionState.getTenantId()) + || versionState.getVersionId() != descriptor.getVersionId() + || versionState.getVersionStateEpoch() != descriptor.getVersionStateEpoch() + || (versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED + && versionState.getVersionState() + != VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE)) { + throw new IllegalArgumentException( + "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch" + + " descriptor"); + } + requireSupportedReleaseAttestationSchema(bundle.getAttestationSchemaVersion()); + return new ResolvedLaunchDescriptor( + descriptor.getLaunchDescriptorId(), + request.tenantId(), + descriptor.getGameTemplateId(), + descriptor.getControlPlaneRequestId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion().isBlank() ? null : descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId().isBlank() ? null : descriptor.getRemapSetId()); + } + private ResolvedLaunchDescriptor preflightLaunchResponse( StartSessionRequest request, ResolveLaunchDescriptorResponse descriptorResponse, @@ -764,6 +1455,70 @@ private void requireRunOwnedSourceMatchesRequest( } } + private AuthoredWorldLaunchDescriptorEvidence requireExactAuthoredWorldDescriptorRequest( + StartSessionRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + ResolveLaunchDescriptorResponse response) { + if (response == null) { + throw new IllegalStateException("launch descriptor authority returned no response"); + } + if (response.hasError()) { + return null; + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design returned no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + sourceEvidence.targetNamespace(), + request.controlPlaneRequestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.worldSlug(), + sourceEvidence.operationId(), + sourceEvidence.evidenceDigest(), + request.gameTemplateId(), + false, + null, + false, + null, + false, + null, + false, + null); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + expectedRequest, response.getLaunchDescriptor()); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_LAUNCH_DESCRIPTOR_MISMATCH: Game Design response is not bound to the" + + " exact source request", + exception); + } + } + + private void requireRunOwnedLaunchDescriptorMatchesReceipt( + AuthoredWorldLaunchDescriptorEvidence actualDescriptorEvidence, + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor receiptDescriptor) { + AuthoredWorldLaunchDescriptorEvidence receiptDescriptorEvidence; + try { + receiptDescriptorEvidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromLaunchDescriptorMessage( + actualDescriptorEvidence.request(), receiptDescriptor); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException( + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: owner receipt descriptor is invalid", exception); + } + if (!AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(actualDescriptorEvidence) + .equals( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + receiptDescriptorEvidence))) { + throw new IllegalArgumentException( + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor"); + } + } + private void validatePublishedAssetProof( long tenantId, long versionId, 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 f6aac311a5..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 @@ -21,7 +21,7 @@ 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.RunOwnedInitialAdmissionFixtureCoordinator; +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; @@ -121,7 +121,7 @@ public final class GameSessionControlPlaneGrpcService private final MeterRegistry meterRegistry; private InitialAdmissionBindOwnerProofReader initialAdmissionBindOwnerProofReader; private InitialAdmissionBindOwnerReadWorkloadGuard initialAdmissionBindOwnerReadWorkloadGuard; - private RunOwnedInitialAdmissionFixtureCoordinator runOwnedFixtureCoordinator; + private RunOwnedCanonicalLaunchPreparationOwner runOwnedLaunchPreparationOwner; private String fixtureReadWorkloadNamespace; private boolean fixtureLaunchReadEnabled; @@ -159,10 +159,10 @@ public void configureInitialAdmissionBindOwnerReadBoundary( @Autowired(required = false) public void configureRunOwnedFixtureLaunchAssociationReadBoundary( - RunOwnedInitialAdmissionFixtureCoordinator fixtureCoordinator, + RunOwnedCanonicalLaunchPreparationOwner fixtureOwner, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean fixtureEnabled, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { - this.runOwnedFixtureCoordinator = fixtureCoordinator; + this.runOwnedLaunchPreparationOwner = fixtureOwner; this.fixtureLaunchReadEnabled = fixtureEnabled; this.fixtureReadWorkloadNamespace = workloadNamespace; } @@ -318,7 +318,7 @@ public void getRunOwnedFixtureLaunchAssociation( Objects.requireNonNull(responseObserver, "responseObserver"); try { requireWorldFixtureLaunchAssociationReadCaller(); - if (!fixtureLaunchReadEnabled || runOwnedFixtureCoordinator == null) { + if (!fixtureLaunchReadEnabled || runOwnedLaunchPreparationOwner == null) { throw new IllegalStateException("Fixed fixture owner read is disabled"); } if (TransactionSynchronizationManager.isActualTransactionActive() @@ -336,7 +336,7 @@ public void getRunOwnedFixtureLaunchAssociation( // Authentication and the fixed default-off boundary precede strict wire decoding. RunOwnedInitialAdmissionLaunchEvidence evidence = - runOwnedFixtureCoordinator.loadFixedVerifiedEvidenceForWorldPeer(); + runOwnedLaunchPreparationOwner.loadFixedVerifiedEvidenceForWorldPeer(); CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest selector; try { selector = CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request); @@ -364,7 +364,7 @@ public void getRunOwnedFixtureLaunchAssociation( return; } - var launch = runOwnedFixtureCoordinator.readFixedFixtureLaunch(evidence); + var launch = runOwnedLaunchPreparationOwner.readFixedFixtureLaunch(evidence); var catalog = launch.catalog().snapshot(); var result = new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( 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..747018299e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java @@ -0,0 +1,653 @@ +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); + + 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/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index fdda9e7306..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 @@ -3,486 +3,894 @@ 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.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; 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.same; 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.time.Instant; import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; 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 net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.WorldManagementClient; +import net.firedevops.firemud.gamesession.dto.GameInstanceDto; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; +import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; +import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.MockedStatic; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +@ExtendWith(OutputCaptureExtension.class) class RunOwnedInitialAdmissionFixtureCoordinatorTest { - 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 RUN_ID = "compose-smoke-2939"; + 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 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, "a".repeat(64), "b".repeat(64)) + CLAIM_DIGEST, RUN_ID, PROJECT_NAME, GAME_SESSION_LEAF_SHA256, CA_CERTIFICATE_SHA256) .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 SOURCE_OPERATION_ID = + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); 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"); + private static final UUID HOLD_ID = UUID.fromString("5fdd38a3-09e3-46bb-b11a-e2ff2a096211"); + private static final UUID HOLD_FENCE = UUID.fromString("e385de73-4324-44a8-a815-d0c806b9a0f7"); + private static final UUID ATTEMPT_ID = UUID.fromString("6f39929c-44ee-45c7-9e96-8c6548b84e65"); @Test - void commitsExactStartingOwnerAllocationThenPerformsSeparateIndependentReadback() { - Fixture fixture = fixture(true); + void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsync() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - var result = fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); + RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult result = + fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); - assertThat(result.launchEvidence().sourceEvidence()) + assertThat(fixture.sourceReceipt.sourceEvidence().registrationRequestId()) + .isEqualTo(UUID.fromString(OPERATION_ID)); + assertThat(fixture.sourceReceipt.sourceEvidence().operationId()) + .isNotEqualTo(fixture.sourceReceipt.sourceEvidence().registrationRequestId()); + assertThat(result) + .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.COMMITTED); + InOrder order = inOrder(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); + ArgumentCaptor launchEvidence = + ArgumentCaptor.forClass(RunOwnedInitialAdmissionLaunchEvidence.class); + order + .verify(fixture.gameInstanceService) + .startRunOwnedInitialLaunch(any(), launchEvidence.capture()); + assertThat(launchEvidence.getValue().sourceEvidence()) .isEqualTo(fixture.sourceReceipt.sourceEvidence()); - assertThat(result.launchEvidence().creationEvidence()) + assertThat(launchEvidence.getValue().creationEvidence()) .isEqualTo(fixture.sourceReceipt.creationEvidence()); - assertThat(result.launchEvidence().fixturePolicySeal()) + assertThat(launchEvidence.getValue().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)); + assertThat(launchEvidence.getValue().publishedReleaseBundle()) + .isEqualTo(fixture.sourceReceipt.launchReadEvidence().publishedReleaseBundle()); + assertThat(launchEvidence.getValue().launchDescriptor()) + .isEqualTo(fixture.sourceReceipt.launchReadEvidence().launchDescriptor()); + order.verify(fixture.ownerService).registerPublicSharedFixtureCatalog(any()); + order.verify(fixture.ownerService).beginIntent(any()); + order + .verify(fixture.worldClient) + .acquireInitialAdmissionBindHold( + eq(7L), + eq(42L), + eq(11L), + eq(4L), + eq(OPERATION_ID), + anyString(), + eq(REALM_ID), + eq(NAMESPACE_ID), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + eq(3L)); + order.verify(fixture.ownerService).attachHold(any()); + order.verify(fixture.ownerService).commit(any()); + verify(fixture.ownerService, never()).abort(any()); + verify(fixture.ownerService, never()).read(any()); } @Test - void exactReplayUsesTheSameOperationAndReturnsTheSameStartingAllocation() { - Fixture fixture = fixture(true); - - var first = fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); - var replay = fixture.coordinator.coordinate(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()); + void unresolvedOwnerProofDoesNotReleaseHoldOrCompensate() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doAnswer( + invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return proof(binding, Outcome.PENDING, ATTEMPT_ID, null, 0L, null, false); + }) + .when(fixture.ownerService) + .commit(any()); + + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) + .isInstanceOf(IllegalStateException.class); + + verify(fixture.ownerService, never()).abort(any()); + verify(fixture.ownerService).attachHold(any()); + verify(fixture.ownerService).commit(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); + void rejectsMismatchedWorldHoldBeforeAttachingOrCommitting() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doAnswer( + invocation -> + AcquireInitialAdmissionBindHoldResponse.newBuilder() + .setHold( + hold( + InitialAdmissionBindHoldStatus + .INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, + UUID.fromString("49de9f26-f314-40e1-96a7-5655c5e5b16e"), + fixture.request.get().requestDigest())) + .build()) + .when(fixture.worldClient) + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong()); assertThatThrownBy( - () -> - changedIdentity.coordinator.coordinate( - changedIdentity.capability, changedIdentity.sourceReceipt)) + () -> fixture.coordinator.coordinate(fixture.capability, fixture.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); + verify(fixture.ownerService, never()).attachHold(any()); + verify(fixture.ownerService, never()).commit(any()); + verify(fixture.ownerService, never()).abort(any()); + } + + @Test + void rejectsMalformedWorldHoldIdentityBeforeAttachingOrCommitting() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doAnswer( + invocation -> { + UUID namespaceId = invocation.getArgument(7); + String requestDigest = invocation.getArgument(5); + return AcquireInitialAdmissionBindHoldResponse.newBuilder() + .setHold( + hold( + InitialAdmissionBindHoldStatus + .INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, + namespaceId, + requestDigest) + .toBuilder() + .setHoldFence("not-a-uuid") + .build()) + .build(); + }) + .when(fixture.worldClient) + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong()); assertThatThrownBy( - () -> - changedStatus.coordinator.coordinate( - changedStatus.capability, changedStatus.sourceReceipt)) + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isInstanceOf(IllegalStateException.class); + + verify(fixture.ownerService, never()).attachHold(any()); + verify(fixture.ownerService, never()).commit(any()); + verify(fixture.ownerService, never()).abort(any()); } @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.coordinate(fixture.capability, changedReceipt)) - .isInstanceOf(IllegalArgumentException.class); - verifyNoInteractions(fixture.launchOwner); + void rejectsMissingOrNoncanonicalCommittedAuditId() { + for (String auditId : new String[] {null, "031"}) { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doAnswer( + invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return proof( + binding, + Outcome.COMMITTED, + ATTEMPT_ID, + auditId, + 1L, + binding.requestDigest(), + false); + }) + .when(fixture.ownerService) + .commit(any()); + + assertThatThrownBy( + () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) + .isInstanceOf(IllegalStateException.class); + } + } + + @Test + void terminalWorldAbortUsesExactReadbackWithoutTryingToCommit() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED); + when(fixture.ownerService.read(any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return proof(binding, Outcome.ABORTED, ATTEMPT_ID, null, 0L, null, true); + }); + + assertThat(fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) + .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.ABORTED); + + verify(fixture.ownerService).read(any()); + verify(fixture.ownerService, never()).attachHold(any()); + verify(fixture.ownerService, never()).commit(any()); + verify(fixture.ownerService, never()).abort(any()); } @Test - void disabledCoordinatorDoesNotReadFixturePathsOrWriteLaunchOwner() { - Fixture fixture = fixture(false); + void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { + GameInstanceService gameInstanceService = org.mockito.Mockito.mock(GameInstanceService.class); + InitialAdmissionBindOwnerService ownerService = + org.mockito.Mockito.mock(InitialAdmissionBindOwnerService.class); + WorldManagementClient worldClient = org.mockito.Mockito.mock(WorldManagementClient.class); + RunOwnedInitialAdmissionFixtureCoordinator coordinator = + new RunOwnedInitialAdmissionFixtureCoordinator( + false, + "", + "", + "", + "", + new CommonGrpcClientProperties(), + gameInstanceService, + ownerService, + worldClient); + + coordinator.retryRunOwnedFixtureBootstrap(); + + verifyNoInteractions(gameInstanceService, ownerService, worldClient); + } - try (MockedStatic loader = + @Test + void missingSourceReceiptRejectsBeforeLaunchOrOwnerMutation() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenThrow(RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + } - loader.verify( - () -> RunOwnedInitialAdmissionFixtureCapability.load(any(), any(), any(), any()), - never()); - loader.verify( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(), any(), any(), any(), any()), - never()); + verifyNoInteractions(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); + } + + @Test + void changedSourceReceiptAcrossRetriesIsRejectedBeforeSecondLaunch() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doThrow(new IllegalStateException("stop after initial launch")) + .when(fixture.ownerService) + .registerPublicSharedFixtureCatalog(any()); + var changedReceipt = + sourceReceipt( + fixture.capability, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")); + try (MockedStatic capabilityLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt, changedReceipt); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); } - verifyNoInteractions(fixture.launchOwner); + verify(fixture.gameInstanceService, times(1)) + .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); + verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); + verify(fixture.ownerService, never()).beginIntent(any()); + verifyNoInteractions(fixture.worldClient); } @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 = + void changedOwnerReadEvidenceAcrossRetriesIsRejectedBeforeSecondLaunch() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + doThrow(new IllegalStateException("stop after initial launch")) + .when(fixture.ownerService) + .registerPublicSharedFixtureCatalog(any()); + var changedReceipt = + withPublishedReleaseBundleRef( + fixture.capability, fixture.sourceReceipt, "owner-release-ref-changed"); + try (MockedStatic capabilityLoader = 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); - - 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(); - } + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt, changedReceipt); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); } + + verify(fixture.gameInstanceService, times(1)) + .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); + verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); + verify(fixture.ownerService, never()).beginIntent(any()); + verifyNoInteractions(fixture.worldClient); } @Test - void retryPinsReceiptRejectsChangedSourceAndExhaustsAtTheBoundedBudget() { - Fixture conflict = fixture(true); - var changedReceipt = sourceReceipt(conflict.capability, 30L); - doAnswer( - invocation -> { - throw new IllegalStateException("owner unavailable"); - }) - .when(conflict.launchOwner) - .createVerifiedFixtureStartingLaunch(any()); - try (MockedStatic loader = + void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( + CapturedOutput output) { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + String hostileMessage = + "capability-bytes=secret grpc-status-detail=tenant-token raw-pointer=private"; + doThrow(new IllegalStateException(hostileMessage)) + .when(fixture.gameInstanceService) + .startRunOwnedInitialLaunch(any(), any()); + + try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - stubFixtureLoaders(loader, conflict, conflict.sourceReceipt, changedReceipt); - conflict.coordinator.retryRunOwnedFixtureBootstrap(); - conflict.coordinator.retryRunOwnedFixtureBootstrap(); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); } - verify(conflict.launchOwner, times(1)).createVerifiedFixtureStartingLaunch(any()); - verify(conflict.launchOwner, never()).readVerifiedFixtureLaunch(any()); - Fixture exhausted = fixture(true); - doAnswer( - invocation -> { - throw new IllegalStateException("owner unavailable"); - }) - .when(exhausted.launchOwner) - .createVerifiedFixtureStartingLaunch(any()); - try (MockedStatic loader = + assertThat(output) + .contains("exceptionType=IllegalStateException") + .contains("errorCode=FIXTURE_STATE_UNRESOLVED") + .contains("message=Fixture state remains unresolved.") + .doesNotContain(hostileMessage, "capability-bytes=secret", "tenant-token", "raw-pointer"); + } + + @Test + void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( + CapturedOutput output) { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + String hostileMessage = "grpc sensitive details capability bytes that must not appear"; + doThrow(new IllegalStateException(hostileMessage)) + .when(fixture.gameInstanceService) + .startRunOwnedInitialLaunch(any(), any()); + + try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - stubFixtureLoaders(loader, exhausted, exhausted.sourceReceipt); - for (int attempt = 0; attempt < 13; attempt++) { - exhausted.coordinator.retryRunOwnedFixtureBootstrap(); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); + + for (int attempt = 0; attempt < 12; attempt++) { + fixture.coordinator.retryRunOwnedFixtureBootstrap(); } } - verify(exhausted.launchOwner, times(12)).createVerifiedFixtureStartingLaunch(any()); - verify(exhausted.launchOwner, never()).readVerifiedFixtureLaunch(any()); + + assertThat(output) + .contains("did not reach a verified terminal result after the bounded retry budget") + .contains("exceptionType=IllegalStateException") + .contains("errorCode=FIXTURE_STATE_UNRESOLVED") + .contains("message=Fixture state remains unresolved.") + .doesNotContain(hostileMessage, "grpc sensitive details", "capability bytes"); } @Test - void scheduledRetryDoesNotOverlapAnInProgressLaunchOwnerAttempt() throws Exception { - Fixture fixture = fixture(true); - CountDownLatch enteredOwner = new CountDownLatch(1); - CountDownLatch releaseOwner = new CountDownLatch(1); + void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { + Fixture fixture = + fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); + AtomicInteger worldAcquisitions = new AtomicInteger(); doAnswer( invocation -> { - enteredOwner.countDown(); - if (!releaseOwner.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("Timed out waiting for owner release"); + int acquisition = worldAcquisitions.incrementAndGet(); + if (acquisition <= 12) { + throw new IllegalStateException("Simulated unresolved World response"); } - throw new IllegalStateException("Controlled unresolved owner result"); + String requestDigest = invocation.getArgument(5); + return AcquireInitialAdmissionBindHoldResponse.newBuilder() + .setHold( + hold( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, + NAMESPACE_ID, + requestDigest)) + .build(); }) - .when(fixture.launchOwner) - .createVerifiedFixtureStartingLaunch(any()); - ExecutorService executor = Executors.newSingleThreadExecutor(); - try { - var first = - executor.submit( - () -> { - try (MockedStatic loader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - stubFixtureLoaders(loader, fixture, fixture.sourceReceipt); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - }); - assertThat(enteredOwner.await(5, TimeUnit.SECONDS)).isTrue(); + .when(fixture.worldClient) + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong()); + + try (MockedStatic capabilityLoader = + mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .thenReturn(fixture.capability); + capabilityLoader + .when( + () -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) + .thenReturn(fixture.sourceReceipt); - try (MockedStatic mainLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - stubFixtureLoaders(mainLoader, fixture, fixture.sourceReceipt); + // Orchestration unit proof only; capability TLS and durable cross-service behavior have + // separate proof boundaries. + for (int attempt = 0; attempt < 12; attempt++) { fixture.coordinator.retryRunOwnedFixtureBootstrap(); } - verify(fixture.launchOwner, times(1)).createVerifiedFixtureStartingLaunch(any()); - releaseOwner.countDown(); - first.get(5, TimeUnit.SECONDS); - verify(fixture.launchOwner, times(1)).createVerifiedFixtureStartingLaunch(any()); - } finally { - releaseOwner.countDown(); - executor.shutdownNow(); + verify(fixture.ownerService, times(12)).beginIntent(any()); + verify(fixture.worldClient, times(12)) + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + eq(OPERATION_ID), + anyString(), + eq(REALM_ID), + eq(NAMESPACE_ID), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + eq(3L)); + verify(fixture.ownerService, never()).attachHold(any()); + verify(fixture.ownerService, never()).commit(any()); + capabilityLoader.verify( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + eq(Path.of(CAPABILITY_PATH)), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.grpcProperties)), + times(12)); + + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + fixture.coordinator.retryRunOwnedFixtureBootstrap(); + verify(fixture.ownerService, times(12)).beginIntent(any()); + verify(fixture.worldClient, times(12)) + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong()); + capabilityLoader.verify( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), anyString(), anyString(), any(CommonGrpcClientProperties.class)), + times(12)); + + RunOwnedInitialAdmissionFixtureCoordinator restarted = newCoordinator(fixture); + restarted.retryRunOwnedFixtureBootstrap(); + + ArgumentCaptor launchRequests = + ArgumentCaptor.forClass(StartSessionRequest.class); + verify(fixture.gameInstanceService, times(13)) + .startRunOwnedInitialLaunch( + launchRequests.capture(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); + assertThat(launchRequests.getAllValues()) + .allSatisfy( + request -> { + assertThat(request.tenantId()).isEqualTo(fixture.capability.tenantId()); + assertThat(request.gameTemplateId()).isEqualTo(fixture.capability.gameTemplateId()); + assertThat(request.ownerAccountId()).isEqualTo(fixture.capability.ownerAccountId()); + assertThat(request.controlPlaneRequestId()).isEqualTo(OPERATION_ID); + }); + ArgumentCaptor ownerRequests = + ArgumentCaptor.forClass(InitialAdmissionBindRequest.class); + verify(fixture.worldClient, times(13)) + .acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + eq(OPERATION_ID), + anyString(), + eq(REALM_ID), + eq(NAMESPACE_ID), + eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + eq(3L)); + verify(fixture.ownerService, times(13)).beginIntent(ownerRequests.capture()); + assertThat(ownerRequests.getAllValues()) + .extracting(InitialAdmissionBindRequest::initialAdmissionRequestId) + .containsOnly(OPERATION_ID); + assertThat(ownerRequests.getAllValues()) + .extracting(InitialAdmissionBindRequest::requestDigest) + .doesNotContainNull() + .containsOnly(ownerRequests.getValue().requestDigest()); + verify(fixture.ownerService).attachHold(any()); + verify(fixture.ownerService).commit(any()); + verify(fixture.ownerService, never()).abort(any()); + + capabilityLoader.verify( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + eq(Path.of(CAPABILITY_PATH)), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.grpcProperties)), + times(13)); + restarted.retryRunOwnedFixtureBootstrap(); + verify(fixture.ownerService, times(13)).beginIntent(any()); + verify(fixture.ownerService).commit(any()); } } - private static Fixture fixture(boolean enabled) { + private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { + GameInstanceService gameInstanceService = org.mockito.Mockito.mock(GameInstanceService.class); + InitialAdmissionBindOwnerService ownerService = + org.mockito.Mockito.mock(InitialAdmissionBindOwnerService.class); + WorldManagementClient worldClient = org.mockito.Mockito.mock(WorldManagementClient.class); CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); grpc.setPlaintext(true); - RunOwnedInitialAdmissionFixtureCapability capability = capability(); - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt = + RunOwnedInitialAdmissionFixtureCapability capability = + new RunOwnedInitialAdmissionFixtureCapability( + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + 7L, + 17L, + 27L, + "demo", + "Demo World", + "production", + "Live Realm", + true, + true, + false, + "SHARED", + "ALLOW_NEW", + GAME_SESSION_LEAF_SHA256, + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + CA_CERTIFICATE_SHA256, + RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, + WORLD_MANAGEMENT_LEAF_SHA256, + CLAIM_DIGEST); + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = 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); + GameInstanceDto target = + new GameInstanceDto( + 42L, + 7L, + "v1", + null, + null, + null, + null, + 17L, + "launch-descriptor-1", + 11L, + 13L, + 3L, + "config-1", + null, + 27L, + "RUNNING"); + when(gameInstanceService.startRunOwnedInitialLaunch(any(), any())) + .thenReturn(new RunOwnedInitialLaunchResult(target, 4L)); + + InitialAdmissionBindCatalog catalog = + new InitialAdmissionBindCatalog( + REALM_ID, + 7L, + 17L, + "demo", + "Demo World", + "production", + "Live Realm", + 3L, + NAMESPACE_ID, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + Instant.now()); + when(ownerService.registerPublicSharedFixtureCatalog( + any(InitialAdmissionBindCatalogDescriptor.class))) + .thenReturn(catalog); + + AtomicReference request = new AtomicReference<>(); + when(ownerService.beginIntent(any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindRequest received = invocation.getArgument(0); + request.set(received); + return attempt(received, catalog, null, null, Status.PENDING); + }); + when(worldClient.acquireInitialAdmissionBindHold( + anyLong(), + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + any(UUID.class), + any(UUID.class), + any(PlayableStateScope.class), + anyLong())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHoldStatus selectedStatus = holdStatus; + UUID namespaceId = invocation.getArgument(7); + String requestDigest = invocation.getArgument(5); + return AcquireInitialAdmissionBindHoldResponse.newBuilder() + .setHold(hold(selectedStatus, namespaceId, requestDigest)) + .build(); + }); + when(ownerService.attachHold(any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return attempt( + request.get(), + catalog, + UUID.fromString(binding.holdId()), + UUID.fromString(binding.holdFence()), + Status.PENDING); + }); + when(ownerService.commit(any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return proof( + binding, Outcome.COMMITTED, ATTEMPT_ID, "31", 1L, binding.requestDigest(), false); + }); RunOwnedInitialAdmissionFixtureCoordinator coordinator = new RunOwnedInitialAdmissionFixtureCoordinator( - enabled, + true, CAPABILITY_PATH, SOURCE_RECEIPT_PATH, RUN_ID, PROJECT_NAME, grpc, - launchOwner, - RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE); - return new Fixture(coordinator, capability, receipt, grpc, launchOwner, allocation); + gameInstanceService, + ownerService, + worldClient); + return new Fixture( + coordinator, + capability, + sourceReceipt, + grpc, + gameInstanceService, + ownerService, + worldClient, + request); } - 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( + private static RunOwnedInitialAdmissionFixtureCoordinator newCoordinator(Fixture fixture) { + return new RunOwnedInitialAdmissionFixtureCoordinator( + true, + CAPABILITY_PATH, + SOURCE_RECEIPT_PATH, 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, + fixture.grpcProperties, + fixture.gameInstanceService, + fixture.ownerService, + fixture.worldClient); + } + + private static InitialAdmissionBindAttempt attempt( + InitialAdmissionBindRequest request, + InitialAdmissionBindCatalog catalog, + UUID holdId, + UUID holdFence, + Status status) { + Instant now = Instant.now(); + return new InitialAdmissionBindAttempt( + ATTEMPT_ID, + request.tenantId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + catalog.realmId(), + catalog.playableStateNamespaceId(), "SHARED", - "ALLOW_NEW", - "a".repeat(64), - RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - "b".repeat(64), - RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, - "c".repeat(64), - CLAIM_DIGEST); + true, + catalog.catalogRevision(), + request.gameInstanceId(), + request.versionId(), + request.activeLifecycleEpoch(), + holdId, + holdFence, + status, + status == Status.COMMITTED ? 1L : null, + status == Status.COMMITTED ? 31L : null, + now, + now, + status == Status.PENDING ? null : now); } private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( RunOwnedInitialAdmissionFixtureCapability capability, long sourceGameRowId) { + return sourceReceipt(capability, sourceGameRowId, SOURCE_OPERATION_ID); + } + + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( + RunOwnedInitialAdmissionFixtureCapability capability, + long sourceGameRowId, + UUID operationId) { + UUID registrationRequestId = UUID.fromString(capability.operationId()); + UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); String targetNamespace = RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE; String tenantSlug = "fixture-tenant"; - String sourceGameTenantKey = "1"; + String worldSlug = capability.worldSlug(); + String worldDisplayName = capability.worldDisplayName(); + String sourceGameTenantKey = Long.toString(capability.tenantId()); String provenanceKind = "NEW_GAME_ROW"; - UUID registrationRequestId = UUID.fromString(capability.operationId()); - String sourceRequestDigest = + String requestDigest = AuthoredWorldSourceDigest.requestDigest( targetNamespace, registrationRequestId, - CANONICAL_TENANT_ID, + canonicalTenantId, tenantSlug, - capability.worldSlug(), - capability.worldDisplayName()); - AuthoredWorldSourceEvidence sourceEvidence = + worldSlug, + worldDisplayName); + AuthoredWorldSourceEvidence evidence = new AuthoredWorldSourceEvidence( 1, targetNamespace, registrationRequestId, - SOURCE_OPERATION_ID, - sourceRequestDigest, - CANONICAL_TENANT_ID, + operationId, + requestDigest, + canonicalTenantId, tenantSlug, - capability.worldSlug(), - capability.worldDisplayName(), + worldSlug, + worldDisplayName, sourceGameRowId, sourceGameTenantKey, provenanceKind, AuthoredWorldSourceDigest.evidenceDigest( targetNamespace, registrationRequestId, - SOURCE_OPERATION_ID, - sourceRequestDigest, - CANONICAL_TENANT_ID, + operationId, + requestDigest, + canonicalTenantId, tenantSlug, - capability.worldSlug(), - capability.worldDisplayName(), + worldSlug, + worldDisplayName, sourceGameRowId, sourceGameTenantKey, provenanceKind)); + var launchRead = launchReadEvidence(capability, evidence); String creationRequestDigest = GameTenantCreationDigest.requestDigest( - targetNamespace, - CREATION_REQUEST_ID, - sourceGameTenantKey, - capability.worldDisplayName(), - null); + targetNamespace, CREATION_REQUEST_ID, sourceGameTenantKey, worldDisplayName, null); FreshTenantCreationEvidence creationEvidence = new FreshTenantCreationEvidence( 1, @@ -490,7 +898,7 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec CREATION_REQUEST_ID, CREATION_OPERATION_ID, creationRequestDigest, - CANONICAL_TENANT_ID, + canonicalTenantId, sourceGameRowId, sourceGameTenantKey, provenanceKind, @@ -499,33 +907,11 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec CREATION_REQUEST_ID, CREATION_OPERATION_ID, creationRequestDigest, - CANONICAL_TENANT_ID, + canonicalTenantId, 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)); + var policySeal = fixturePolicySeal(capability, creationEvidence, evidence, launchRead); return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, capability.runId(), @@ -537,10 +923,82 @@ private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceRec capability.caCertificateSha256(), capability.worldManagementUriSan(), capability.worldManagementLeafSha256(), - sourceEvidence, + evidence, launchRead, creationEvidence, - seal); + policySeal); + } + + private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt + withPublishedReleaseBundleRef( + RunOwnedInitialAdmissionFixtureCapability capability, + RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt, + String bundleRef) { + var original = receipt.launchReadEvidence(); + var changedBundle = + original.publishedReleaseBundle().toBuilder() + .setPublishedReleaseBundleRef(bundleRef) + .build(); + var changedReadEvidence = + new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( + original.schema(), + original.gameTemplateId(), + changedBundle, + original.versionAssetArtifactState(), + original.versionState(), + launchDescriptor( + receipt.sourceEvidence(), + changedBundle, + original.versionState(), + original.gameTemplateId(), + receipt.fixtureOperationId())); + var changedPolicySeal = + fixturePolicySeal( + capability, receipt.creationEvidence(), receipt.sourceEvidence(), changedReadEvidence); + return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( + receipt.schema(), + receipt.runId(), + receipt.composeProjectName(), + receipt.fixtureOperationId(), + receipt.ownerService(), + receipt.gameSessionUriSan(), + receipt.gameSessionLeafSha256(), + receipt.caCertificateSha256(), + receipt.worldManagementUriSan(), + receipt.worldManagementLeafSha256(), + receipt.sourceEvidence(), + 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( @@ -548,8 +1006,8 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun AuthoredWorldSourceEvidence sourceEvidence) { String manifestHash = "sha256:" + "a".repeat(64); String artifactDigest = "sha256:" + "b".repeat(64); - PublishedReleaseBundle bundle = - PublishedReleaseBundle.newBuilder() + var bundle = + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() .setId(77L) .setVersionId(11L) .setVersionNumber(1) @@ -559,7 +1017,7 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun .addRequiredManifestAssetKeys("manifest.json") .setGenerationConfigRevision("genrev-11") .setPublishedAt("2026-04-15T10:00:00") - .setPublishedReleaseBundleRef("prb:7:11:77") + .setPublishedReleaseBundleRef("owner-release-ref-11") .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") .setManifestSchemaVersion(1) @@ -567,40 +1025,64 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() .setUsageKey("manifest.json") .setArtifactKind("manifest") - .setImmutableObjectKey("artifacts/sha256/" + artifactDigest.substring(7)) + .setImmutableObjectKey( + "artifacts/sha256/" + artifactDigest.substring("sha256:".length())) .setContentDigest(artifactDigest) .setContentType("application/json") .setArtifactSchemaVersion(1) .build()) .build(); - VersionAssetArtifactState artifactState = - VersionAssetArtifactState.newBuilder() + var artifactState = + net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() .setTenantId(Long.toString(capability.tenantId())) .setVersionId(11L) - .setArtifactState(ArtifactState.ARTIFACT_STATE_PUBLISHED) + .setArtifactState( + net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED) .setStateEpoch(2L) .setManifestHash(manifestHash) .setUpdatedAt("2026-04-15T10:00:00") .addExportedManifestAssetKeys("manifest.json") .setExportedVersionNumber(1) .build(); - VersionStateSnapshot versionState = - VersionStateSnapshot.newBuilder() + var versionState = + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() .setTenantId(Long.toString(capability.tenantId())) .setVersionId(11L) - .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) + .setVersionState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED) .setVersionStateEpoch(77L) .setUpdatedAt("2026-04-15T10:00:00") .build(); - AuthoredWorldLaunchDescriptorEvidence.Request request = + return new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( + RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, + capability.gameTemplateId(), + bundle, + artifactState, + versionState, + launchDescriptor( + sourceEvidence, + bundle, + versionState, + capability.gameTemplateId(), + capability.operationId())); + } + + private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor launchDescriptor( + AuthoredWorldSourceEvidence sourceEvidence, + net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, + net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, + long gameTemplateId, + String controlPlaneRequestId) { + var request = new AuthoredWorldLaunchDescriptorEvidence.Request( - RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE, - capability.operationId(), + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, + controlPlaneRequestId, sourceEvidence.canonicalTenantId(), sourceEvidence.worldSlug(), sourceEvidence.operationId(), sourceEvidence.evidenceDigest(), - capability.gameTemplateId(), + gameTemplateId, false, null, false, @@ -609,7 +1091,7 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun null, false, null); - var descriptorEvidence = + var evidence = AuthoredWorldLaunchDescriptorEvidence.create( request, "launch-descriptor-fixture-11", @@ -623,65 +1105,57 @@ private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence laun bundle.getPublishedReleaseBundleRef(), false, null); - LaunchDescriptor descriptor = - AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); - return new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( - RunOwnedInitialAdmissionFixtureCapability.LAUNCH_READ_EVIDENCE_SCHEMA, - capability.gameTemplateId(), - bundle, - artifactState, - versionState, - descriptor); + return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence); } - 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 static InitialAdmissionBindHold hold( + InitialAdmissionBindHoldStatus status, UUID namespaceId, String requestDigest) { + return InitialAdmissionBindHold.newBuilder() + .setHoldId(HOLD_ID.toString()) + .setHoldFence(HOLD_FENCE.toString()) + .setTenantId("7") + .setRealmUuid(REALM_ID.toString()) + .setPlayableStateNamespaceUuid(namespaceId.toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setGameInstanceId("42") + .setVersionId("11") + .setActiveLifecycleEpoch(4L) + .setInitialAdmissionRequestId(OPERATION_ID) + .setRequestDigest(requestDigest) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(3L) + .setStatus(status) + .build(); + } + + private static InitialAdmissionBindOwnerProof proof( + InitialAdmissionBindHoldBinding binding, + Outcome outcome, + UUID attemptId, + String auditId, + long pointerVersion, + String auditDigest, + boolean futureCommitPrevented) { + return new InitialAdmissionBindOwnerProof( + outcome, + binding.holdId(), + binding.holdFence(), + binding.tenantId(), + binding.realmUuid(), + binding.playableStateNamespaceUuid(), + binding.playableStateScope(), + binding.gameInstanceId(), + binding.versionId(), + binding.activeLifecycleEpoch(), + binding.initialAdmissionRequestId(), + binding.requestDigest(), + binding.expectedNoPriorPointer(), + binding.expectedCatalogRevision(), + attemptId.toString(), + auditId, + pointerVersion, + auditDigest, + futureCommitPrevented); } private record Fixture( @@ -689,6 +1163,8 @@ private record Fixture( RunOwnedInitialAdmissionFixtureCapability capability, RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt, CommonGrpcClientProperties grpcProperties, - GameSessionCanonicalInstanceLaunchRepository launchOwner, - FixtureCanonicalInstanceLaunch allocation) {} + GameInstanceService gameInstanceService, + InitialAdmissionBindOwnerService ownerService, + WorldManagementClient worldClient, + AtomicReference request) {} } 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/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 3929689f4a..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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -9,6 +10,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @@ -30,10 +32,12 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; import net.firedevops.firemud.gamesession.client.GameDesignClient; @@ -46,6 +50,7 @@ import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.junit.jupiter.api.BeforeEach; @@ -68,6 +73,8 @@ class GameInstanceServiceImplTest { private GameInstanceServiceImpl service; private Map store; private AtomicLong nextId; + private String runOwnedBundleRefOverride; + private LaunchDescriptor runOwnedDescriptorOverride; @Test void legacyDtoConstructorRejectsNonblankPatchWithoutCompleteTuple() { @@ -105,6 +112,8 @@ void setup() { meterRegistry = new SimpleMeterRegistry(); store = new HashMap<>(); nextId = new AtomicLong(10L); + runOwnedBundleRefOverride = null; + runOwnedDescriptorOverride = null; service = new GameInstanceServiceImpl( repository, @@ -214,18 +223,505 @@ void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority(String l } @Test - void verifiedRunOwnedLaunchCannotEnterUnavailableWorldPhaseOrNumericAllocation() { + void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { StartSessionRequest request = new StartSessionRequest( 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); - IllegalStateException denied = + configureRunOwnedWorld(request); + + var first = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); + clearInvocations(stateService, worldManagementClient); + var retry = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); + + assertEquals(first.gameInstance().id(), retry.gameInstance().id()); + assertEquals(10L, retry.gameInstance().id()); + assertEquals(11L, retry.gameInstance().versionId()); + assertEquals(2L, retry.activeLifecycleEpoch()); + assertEquals("RUNNING", store.get(10L).getStatus()); + assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); + assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); + assertEquals(64, store.get(10L).getRunOwnedStartRequestDigest().length()); + ArgumentCaptor repairedState = ArgumentCaptor.forClass(GameInstanceDto.class); + verify(stateService).saveState(repairedState.capture()); + assertEquals("RUNNING", repairedState.getValue().status()); + verify(worldManagementClient).getWorldInstanceLifecycle(1L, 10L); + verifyNoMoreInteractions(worldManagementClient); + } + + @Test + void runOwnedLaunchUsesOpaqueOwnerReferenceWithoutCallingDeniedReadRpcs() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + String opaqueBundleRef = "gds:owner-ref:immutable-release-77"; + runOwnedBundleRefOverride = opaqueBundleRef; + configureRunOwnedWorld(request); + + service.startRunOwnedInitialLaunch( + request, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, sourceEvidence(request), opaqueBundleRef)); + + ArgumentCaptor preparedBundleRef = ArgumentCaptor.forClass(String.class); + verify(worldManagementClient) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + preparedBundleRef.capture(), + anyLong(), + any()); + assertEquals(opaqueBundleRef, preparedBundleRef.getValue()); + assertEquals(opaqueBundleRef, store.get(10L).getRunOwnedStartPublishedReleaseBundleRef()); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + } + + @Test + void runOwnedLaunchRejectsDifferentValidResolveDescriptorBeforeMutation() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + var ownerEvidence = launchEvidence(request); + runOwnedDescriptorOverride = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, sourceEvidence(request), "gds:owner-ref:different-release") + .launchDescriptor(); + assertFalse( + ownerEvidence + .launchDescriptor() + .getAuthoredWorldBinding() + .getResultDigest() + .equals(runOwnedDescriptorOverride.getAuthoredWorldBinding().getResultDigest())); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, ownerEvidence)); + + assertEquals( + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor", + error.getMessage()); + verifyNoInteractions(stateService, worldManagementClient); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + } + + @Test + void runOwnedLaunchRejectsOwnerVersionEpochMismatchBeforeWorldPreparation() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + var original = launchEvidence(request); + var changed = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, + sourceEvidence(request), + original.publishedReleaseBundle(), + original.versionAssetArtifactState(), + original.versionState().toBuilder().setVersionStateEpoch(78L).build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, changed)); + + assertEquals( + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor", + error.getMessage()); + assertTrue(store.isEmpty()); + verifyNoInteractions(stateService, worldManagementClient); + } + + @Test + void runOwnedLaunchRejectsUnrecognizedOwnerVersionStateBeforeWorldPreparation() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + var original = launchEvidence(request); + var unchecked = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.createUncheckedForServicePreflightTests( + request, + sourceEvidence(request), + original.publishedReleaseBundle(), + original.versionAssetArtifactState(), + original.versionState().toBuilder().setVersionStateValue(999).build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, unchecked)); + + assertEquals( + "RUN_OWNED_LAUNCH_READ_EVIDENCE_MISMATCH: owner snapshot differs from the exact launch descriptor", + error.getMessage()); + verifyNoInteractions(worldManagementClient); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + } + + @Test + void runOwnedLaunchRejectsOwnerVersionIdentityMismatchBeforeWorldPreparation() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + var original = launchEvidence(request); + var changed = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, + sourceEvidence(request), + original.publishedReleaseBundle().toBuilder() + .setVersionId(12L) + .setCanonicalVersionId("10000000-0000-4000-8000-000000000012") + .build(), + original.versionAssetArtifactState().toBuilder().setVersionId(12L).build(), + original.versionState().toBuilder().setVersionId(12L).build()); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.startRunOwnedInitialLaunch(request, changed)); + + assertEquals( + "RUN_OWNED_LAUNCH_DESCRIPTOR_MISMATCH: resolved descriptor differs from the immutable" + + " owner receipt descriptor", + error.getMessage()); + assertTrue(store.isEmpty()); + verifyNoInteractions(stateService, worldManagementClient); + } + + @Test + void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + service.startRunOwnedInitialLaunch(request, launchEvidence(request)); + clearInvocations(stateService, worldManagementClient); + worldState.set( + runOwnedWorldSnapshot( + request, + 10L, + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); + + IllegalStateException error = assertThrows( IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); - assertTrue(denied.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); - assertTrue(store.isEmpty()); - verify(repository, never()).save(any()); - verifyNoInteractions(gameDesignClient, worldManagementClient, stateService); + + assertEquals( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World", + error.getMessage()); + assertEquals("RUNNING", store.get(10L).getStatus()); + assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); + verifyNoInteractions(stateService); + verify(worldManagementClient).getWorldInstanceLifecycle(1L, 10L); + verifyNoMoreInteractions(worldManagementClient); + } + + @Test + void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + AtomicInteger prepareCalls = new AtomicInteger(); + when(worldManagementClient.prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any())) + .thenAnswer( + invocation -> { + if (prepareCalls.getAndIncrement() == 0) { + worldState.set( + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); + throw new IllegalStateException("prepare response timed out"); + } + return net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse + .newBuilder() + .setWorldInstance(worldState.get()) + .build(); + }); + + IllegalStateException pending = + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); + + assertEquals("world preparation authority unavailable", pending.getMessage()); + assertEquals(1, store.size()); + assertEquals(10L, store.get(10L).getId()); + assertNull(store.get(10L).getRunOwnedStartPreparingEpoch()); + + var resumed = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); + + assertEquals(10L, resumed.gameInstance().id()); + assertEquals(2L, resumed.activeLifecycleEpoch()); + assertEquals(1, store.size()); + assertEquals("RUNNING", store.get(10L).getStatus()); + verify(worldManagementClient, times(2)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + + @Test + void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + doThrow(new IllegalStateException("activation response timed out")) + .when(worldManagementClient) + .activatePreparedWorldInstance(1L, 10L, 1L); + + IllegalStateException pending = + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); + + assertEquals("world activation authority unavailable", pending.getMessage()); + assertEquals("STARTING", store.get(10L).getStatus()); + assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); + assertNull(store.get(10L).getRunOwnedStartActiveEpoch()); + worldState.set( + runOwnedWorldSnapshot( + request, 10L, 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + + var resumed = service.startRunOwnedInitialLaunch(request, launchEvidence(request)); + + assertEquals(10L, resumed.gameInstance().id()); + assertEquals(2L, resumed.activeLifecycleEpoch()); + assertEquals(1, store.size()); + assertEquals("RUNNING", store.get(10L).getStatus()); + verify(worldManagementClient, times(1)).activatePreparedWorldInstance(1L, 10L, 1L); + verify(repository, never()).deleteById(10L); + } + + @Test + void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + configureRunOwnedWorld(request); + service.startRunOwnedInitialLaunch(request, launchEvidence(request)); + + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 43L), + launchEvidence(request))); + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + new StartSessionRequest( + 1L, 4L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L), + launchEvidence( + new StartSessionRequest( + 1L, + 4L, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + 42L)))); + + assertEquals(1, store.size()); + assertEquals(10L, store.get(10L).getId()); + verify(worldManagementClient, times(1)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + + @Test + void runOwnedInitialLaunchRequestIdConflictsOnChangedAuthoredWorldSource() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + configureRunOwnedWorld(request); + service.startRunOwnedInitialLaunch(request, launchEvidence(request)); + + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + request, launchEvidence(request, sourceEvidence(request, 30L)))); + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + request, + launchEvidence( + request, + sourceEvidence( + request, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c"))))); + + assertEquals(1, store.size()); + verify(worldManagementClient, times(1)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + + @Test + void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerReadSnapshot() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + configureRunOwnedWorld(request); + var original = launchEvidence(request); + service.startRunOwnedInitialLaunch(request, original); + var changed = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + request, + sourceEvidence(request), + original.publishedReleaseBundle().toBuilder() + .setPublishWorkflowId("publish-11-replayed-with-changed-input") + .build(), + original.versionAssetArtifactState(), + original.versionState()); + + assertThrows( + IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request, changed)); + + assertEquals(1, store.size()); + verify(worldManagementClient, times(1)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + + @Test + void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + doAnswer( + invocation -> + GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + worldState.get().toBuilder() + .setPublishedReleaseBundleRef("prb:1:11:78") + .build()) + .build()) + .when(worldManagementClient) + .getWorldInstanceLifecycle(anyLong(), anyLong()); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); + + assertEquals( + "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor", + error.getMessage()); + assertEquals(1, store.size()); + assertEquals("STARTING", store.get(10L).getStatus()); + assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); + verify(worldManagementClient, never()) + .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); + } + + @Test + void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { + StartSessionRequest request = + new StartSessionRequest( + 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + worldState.set( + runOwnedWorldSnapshot( + request, + 10L, + 2L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION)); + + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); + assertThrows( + IllegalStateException.class, + () -> service.startRunOwnedInitialLaunch(request, launchEvidence(request))); + + assertEquals(1, store.size()); + assertEquals( + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + store.get(10L).getRunOwnedStartRequestId()); + assertEquals("STARTING", store.get(10L).getStatus()); + verify(worldManagementClient, never()) + .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); } @Test @@ -1284,6 +1780,28 @@ private void configureLaunchPreflight() { .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) .build()) .build()); + when(gameDesignClient.resolveLaunchDescriptor( + any(Long.class), any(Long.class), anyString(), any(AuthoredWorldSourceEvidence.class))) + .thenAnswer( + invocation -> { + long tenantId = invocation.getArgument(0, Long.class); + long gameTemplateId = invocation.getArgument(1, Long.class); + String controlPlaneRequestId = invocation.getArgument(2, String.class); + AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); + LaunchDescriptor descriptor = runOwnedDescriptorOverride; + if (descriptor == null) { + descriptor = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + new StartSessionRequest( + tenantId, gameTemplateId, controlPlaneRequestId, 42L), + sourceEvidence, + runOwnedBundleRef(tenantId)) + .launchDescriptor(); + } + return ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor) + .build(); + }); when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() @@ -1416,7 +1934,9 @@ private static AuthoredWorldSourceEvidence sourceEvidence( } private String runOwnedBundleRef(long tenantId) { - return "prb:" + tenantId + ":11:77"; + return runOwnedBundleRefOverride == null + ? "prb:" + tenantId + ":11:77" + : runOwnedBundleRefOverride; } private static UUID sourceOperationId(StartSessionRequest request) { @@ -1758,6 +2278,94 @@ private void configureWorldActivation() { .build()); } + private AtomicReference configureRunOwnedWorld( + StartSessionRequest request) { + AtomicReference worldState = new AtomicReference<>(); + when(worldManagementClient.prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any())) + .thenAnswer( + invocation -> { + if (worldState.get() == null) { + worldState.set( + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING, + runOwnedBundleRef(request.tenantId()))); + } + return PrepareWorldInstanceResponse.newBuilder() + .setWorldInstance(worldState.get()) + .build(); + }); + when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) + .thenAnswer( + invocation -> + GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance(worldState.get()) + .build()); + when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstanceLifecycleSnapshot active = + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + invocation.getArgument(2, Long.class) + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, + runOwnedBundleRef(request.tenantId())); + worldState.set(active); + return net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse + .newBuilder() + .setWorldInstance(active) + .build(); + }); + return worldState; + } + + private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( + StartSessionRequest request, + long gameInstanceId, + long lifecycleEpoch, + WorldInstanceLifecycleStatus status) { + return runOwnedWorldSnapshot( + request, gameInstanceId, lifecycleEpoch, status, "prb:" + request.tenantId() + ":11:77"); + } + + private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( + StartSessionRequest request, + long gameInstanceId, + long lifecycleEpoch, + WorldInstanceLifecycleStatus status, + String publishedReleaseBundleRef) { + return WorldInstanceLifecycleSnapshot.newBuilder() + .setTenantId(Long.toString(request.tenantId())) + .setGameInstanceId(Long.toString(gameInstanceId)) + .setGameTemplateId(Long.toString(request.gameTemplateId())) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setReleaseBundleId("77") + .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(publishedReleaseBundleRef) + .setVersionStateEpoch(77L) + .setLifecycleEpoch(lifecycleEpoch) + .setStatus(status) + .build(); + } + private GameInstance persistExisting( Long id, Long tenantId, 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 index 1da48f7e0c..ed0d110277 100644 --- 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 @@ -27,7 +27,7 @@ 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.RunOwnedInitialAdmissionFixtureCoordinator; +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; @@ -228,8 +228,8 @@ void defaultOffAndMissingCoordinatorFailWithoutFixedOrOwnerReads() { private static Fixture fixture(boolean enabled, boolean withCoordinator) { RunOwnedInitialAdmissionLaunchEvidence evidence = evidence(); FixtureCanonicalInstanceLaunch launch = launch(evidence); - RunOwnedInitialAdmissionFixtureCoordinator coordinator = - withCoordinator ? mock(RunOwnedInitialAdmissionFixtureCoordinator.class) : null; + RunOwnedCanonicalLaunchPreparationOwner coordinator = + withCoordinator ? mock(RunOwnedCanonicalLaunchPreparationOwner.class) : null; if (coordinator != null) { when(coordinator.loadFixedVerifiedEvidenceForWorldPeer()) .thenAnswer( @@ -428,7 +428,7 @@ public void onCompleted() { private record Fixture( GameSessionControlPlaneGrpcService service, - RunOwnedInitialAdmissionFixtureCoordinator coordinator, + RunOwnedCanonicalLaunchPreparationOwner coordinator, RunOwnedInitialAdmissionLaunchEvidence evidence, FixtureCanonicalInstanceLaunch launch) {} } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java index 3374f44131..37ca38c9d3 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidence.java @@ -3,11 +3,9 @@ import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.Arrays; import java.util.HexFormat; import java.util.Objects; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; @@ -23,8 +21,6 @@ public final class RunOwnedWorldLaunchEvidence { private final RunOwnedInitialAdmissionFixtureWireCodec.Capability capability; private final RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt; private final AuthoredWorldLaunchDescriptorEvidence launchDescriptor; - private final CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult - gameSessionAssociation; private final byte[] capabilityBytes; private final byte[] sourceReceiptBytes; private final String gameSessionLeafSha256; @@ -41,8 +37,7 @@ public final class RunOwnedWorldLaunchEvidence { String gameSessionLeafSha256, String worldManagementUriSan, String worldManagementLeafSha256, - String caCertificateSha256, - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation) { + String caCertificateSha256) { this.capability = Objects.requireNonNull(capability, "capability"); this.sourceReceipt = Objects.requireNonNull(sourceReceipt, "sourceReceipt"); this.launchDescriptor = Objects.requireNonNull(launchDescriptor, "launchDescriptor"); @@ -56,10 +51,6 @@ public final class RunOwnedWorldLaunchEvidence { this.worldManagementLeafSha256 = Objects.requireNonNull(worldManagementLeafSha256, "worldManagementLeafSha256"); this.caCertificateSha256 = Objects.requireNonNull(caCertificateSha256, "caCertificateSha256"); - this.gameSessionAssociation = - Objects.requireNonNull(gameSessionAssociation, "gameSessionAssociation"); - requireExactGameSessionFixtureAssociation( - this.capability, this.sourceReceipt, this.gameSessionAssociation); } public RunOwnedInitialAdmissionFixtureWireCodec.Capability capability() { @@ -74,20 +65,6 @@ public AuthoredWorldLaunchDescriptorEvidence launchDescriptor() { return launchDescriptor; } - /** Exact authenticated allocation read from the existing Game Session launch owner. */ - public CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation() { - return gameSessionAssociation; - } - - /** The readback identifies the private Game Session keys; it grants no World write authority. */ - public void requireGameSessionAllocation(long tenantId, long gameInstanceId) { - if (tenantId != gameSessionAssociation.gameSessionTenantId() - || gameInstanceId != gameSessionAssociation.gameInstanceId()) { - throw new IllegalArgumentException( - "RUN_OWNED_WORLD_GAME_SESSION_ALLOCATION_MISMATCH: request differs from authenticated Game Session owner read"); - } - } - public String gameSessionLeafSha256() { return gameSessionLeafSha256; } @@ -118,7 +95,7 @@ public void requireMatches(PreparedWorldInstanceRequest request) { || version.getVersionState() == net.firedevops.firemud.gamedesign.v1.VersionLifecycleState .VERSION_LIFECYCLE_STATE_ACTIVE; - if (request.tenantId() <= 0L + if (request.tenantId() != capability.tenantId() || request.gameInstanceId() <= 0L || request.gameTemplateId() != capability.gameTemplateId() || !capability.operationId().equals(request.controlPlaneRequestId()) @@ -166,56 +143,6 @@ public void requireMatches(PreparedWorldInstanceRequest request) { throw new IllegalArgumentException( "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: prepared request differs from committed fixture evidence"); } - requireGameSessionAllocation(request.tenantId(), request.gameInstanceId()); - requireExactGameSessionFixtureAssociation(capability, sourceReceipt, gameSessionAssociation); - } - - static void requireExactGameSessionFixtureAssociation( - RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, - RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt, - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation) { - var expectedPolicy = - new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicyRequest( - capability, - sourceReceipt.creationEvidence(), - sourceReceipt.sourceEvidence(), - sourceReceipt.launchReadEvidence()); - byte[] expectedPolicyBytes = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( - capability, - sourceReceipt.creationEvidence(), - sourceReceipt.sourceEvidence(), - sourceReceipt.launchReadEvidence()); - if (!gameSessionAssociation - .request() - .fixtureOperationId() - .toString() - .equals(capability.operationId()) - || !gameSessionAssociation - .request() - .targetNamespace() - .equals(sourceReceipt.sourceEvidence().targetNamespace()) - || !gameSessionAssociation - .request() - .expectedFixturePolicyEvidenceDigest() - .equals(sourceReceipt.fixturePolicySeal().evidenceDigest()) - || !gameSessionAssociation.fixturePolicySeal().equals(sourceReceipt.fixturePolicySeal()) - || !Objects.equals(gameSessionAssociation.fixturePolicyRequest(), expectedPolicy) - || !Arrays.equals(gameSessionAssociation.fixturePolicyRequestBytes(), expectedPolicyBytes) - || !gameSessionAssociation - .canonicalTenantId() - .equals(sourceReceipt.sourceEvidence().canonicalTenantId()) - || !gameSessionAssociation - .canonicalVersionId() - .toString() - .equals( - sourceReceipt - .launchReadEvidence() - .publishedReleaseBundle() - .getCanonicalVersionId())) { - throw new IllegalArgumentException( - "RUN_OWNED_WORLD_GAME_SESSION_FIXTURE_ASSOCIATION_MISMATCH: owner read differs from immutable fixture receipt"); - } } /** diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java index 42bfeb4d6c..f5a29e382e 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProvider.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.worldmanagement.data; -import jakarta.annotation.PreDestroy; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -18,13 +17,9 @@ import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; -import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; -import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; @@ -34,19 +29,15 @@ import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; -import org.springframework.util.StringUtils; /** * Fixed-server reader and verifier for the run-owned World launch fixture. * *

Request data cannot select paths, principals, or evidence. Every call rereads and revalidates - * the configured immutable files and reads the exact authenticated Game Design and Game Session - * owner projections. The Game Session STARTING association is provenance only; it grants no World - * materialization or activation authority. + * the configured immutable files and performs the exact authenticated Game Design owner read. */ @Component public final class RunOwnedWorldLaunchEvidenceProvider { @@ -67,13 +58,7 @@ public final class RunOwnedWorldLaunchEvidenceProvider { private final String composeProjectName; private final CommonGrpcClientProperties grpcProperties; private final GameDesignClient gameDesignClient; - private final ServiceEndpointsProperties serviceEndpoints; - private final GrpcChannelFactory grpcChannelFactory; - private final GameSessionFixtureClientFactory gameSessionFixtureClientFactory; - private final String workloadNamespace; - private volatile CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient; - @Autowired public RunOwnedWorldLaunchEvidenceProvider( @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, @@ -81,38 +66,7 @@ public RunOwnedWorldLaunchEvidenceProvider( @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, CommonGrpcClientProperties grpcProperties, - GameDesignClient gameDesignClient, - ServiceEndpointsProperties serviceEndpoints, - GrpcChannelFactory grpcChannelFactory, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { - this( - enabled, - capabilityPath, - sourceReceiptPath, - runId, - composeProjectName, - grpcProperties, - gameDesignClient, - serviceEndpoints, - grpcChannelFactory, - workloadNamespace, - (endpoints, properties, factory, namespace) -> - new CanonicalGameInstanceLaunchAssociationClient( - endpoints, properties, factory, namespace)); - } - - RunOwnedWorldLaunchEvidenceProvider( - boolean enabled, - String capabilityPath, - String sourceReceiptPath, - String runId, - String composeProjectName, - CommonGrpcClientProperties grpcProperties, - GameDesignClient gameDesignClient, - ServiceEndpointsProperties serviceEndpoints, - GrpcChannelFactory grpcChannelFactory, - String workloadNamespace, - GameSessionFixtureClientFactory gameSessionFixtureClientFactory) { + GameDesignClient gameDesignClient) { this.enabled = enabled; this.capabilityPath = capabilityPath; this.sourceReceiptPath = sourceReceiptPath; @@ -120,11 +74,6 @@ public RunOwnedWorldLaunchEvidenceProvider( this.composeProjectName = composeProjectName; this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); - this.serviceEndpoints = serviceEndpoints == null ? null : serviceEndpoints.copy(); - this.grpcChannelFactory = grpcChannelFactory; - this.gameSessionFixtureClientFactory = - Objects.requireNonNull(gameSessionFixtureClientFactory, "gameSessionFixtureClientFactory"); - this.workloadNamespace = workloadNamespace; } /** Whether the server selected the run-owned fixture mode at startup. */ @@ -133,9 +82,8 @@ public boolean isEnabled() { } /** - * Independently loads the fixed evidence and verifies both authenticated owner readbacks. - * Returned Game Session STARTING state is source evidence only and does not authorize World - * writes or activation. + * Independently loads all fixed evidence and verifies the actual authenticated request context. + * This is invoked on every prepare, activate, and exact retry. */ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { VerificationStage stage = VerificationStage.ENABLED; @@ -201,18 +149,6 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { throw invalidEvidence(); } - stage = VerificationStage.GAME_SESSION_FIXTURE_READ; - var fixtureReadRequest = - new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( - freshFixtureReadRequestId(UUID.fromString(capability.operationId())), - receipt.sourceEvidence().targetNamespace(), - UUID.fromString(capability.operationId()), - receipt.fixturePolicySeal().evidenceDigest()); - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult gameSessionAssociation = - gameSessionFixtureClient() - .readFixture(fixtureReadRequest, capability.gameSessionLeafSha256()); - stage = VerificationStage.GAME_SESSION_FIXTURE_COMPARE; - return new RunOwnedWorldLaunchEvidence( capability, receipt, @@ -222,8 +158,7 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { capability.gameSessionLeafSha256(), worldPins.uriSan(), worldPins.leafSha256(), - worldPins.caSha256(), - gameSessionAssociation); + worldPins.caSha256()); } catch (RuntimeException exception) { if (exception instanceof InvalidRunOwnedWorldLaunchEvidenceException invalid) { throw invalid; @@ -236,53 +171,6 @@ public RunOwnedWorldLaunchEvidence requireAuthenticatedEvidence() { } } - private static UUID freshFixtureReadRequestId(UUID fixtureOperationId) { - UUID readRequestId; - do { - readRequestId = UUID.randomUUID(); - } while (readRequestId.equals(fixtureOperationId)); - return readRequestId; - } - - private synchronized CanonicalGameInstanceLaunchAssociationClient gameSessionFixtureClient() { - if (gameSessionFixtureClient != null) { - return gameSessionFixtureClient; - } - if (serviceEndpoints == null - || grpcChannelFactory == null - || !StringUtils.hasText(workloadNamespace)) { - throw invalidEvidence(); - } - CanonicalGameInstanceLaunchAssociationClient created = - gameSessionFixtureClientFactory.create( - serviceEndpoints, grpcProperties, grpcChannelFactory, workloadNamespace); - try { - created.init(); - gameSessionFixtureClient = created; - return created; - } catch (IOException | RuntimeException failure) { - try { - created.close(); - } catch (IOException ignored) { - // Keep the fixed content-free rejection; certificate paths never enter logs. - } - throw invalidEvidence(); - } - } - - @PreDestroy - public synchronized void closeGameSessionFixtureClient() { - CanonicalGameInstanceLaunchAssociationClient current = gameSessionFixtureClient; - gameSessionFixtureClient = null; - if (current != null) { - try { - current.close(); - } catch (IOException failure) { - logger.warn("Run-owned World Game Session owner client did not close cleanly"); - } - } - } - private static AuthoredWorldLaunchDescriptorEvidence.Request expectedDescriptorRequest( RunOwnedInitialAdmissionFixtureWireCodec.Capability capability, RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt) { @@ -445,15 +333,6 @@ private static InvalidRunOwnedWorldLaunchEvidenceException invalidEvidence() { private record CertificatePins(String leafSha256, String uriSan, String caSha256) {} - @FunctionalInterface - interface GameSessionFixtureClientFactory { - CanonicalGameInstanceLaunchAssociationClient create( - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProperties, - GrpcChannelFactory channelFactory, - String workloadNamespace); - } - private enum VerificationStage { ENABLED, RUN_BINDING, @@ -464,9 +343,7 @@ private enum VerificationStage { GAME_SESSION_PEER, DESCRIPTOR_PARSE, OWNER_DESCRIPTOR_READ, - OWNER_DESCRIPTOR_COMPARE, - GAME_SESSION_FIXTURE_READ, - GAME_SESSION_FIXTURE_COMPARE + OWNER_DESCRIPTOR_COMPARE } /** Content-free failure so malformed or secret-bearing fixture bytes never reach logs. */ diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java index e132c8f914..3a6c802b90 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.worldmanagement.data; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import net.firedevops.firemud.worldmanagement.entity.Region; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; @@ -10,7 +9,6 @@ import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; import net.firedevops.firemud.worldmanagement.repository.RoomRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -25,7 +23,6 @@ havingValue = "true", matchIfMissing = false) @RequiredArgsConstructor -@Slf4j public class TestDataSeeder implements ApplicationRunner { private static final long DEMO_TENANT_ID = 1L; private static final long DEMO_VERSION_ID = 1L; @@ -45,17 +42,9 @@ public class TestDataSeeder implements ApplicationRunner { private final RoomRepository roomRepository; private final RoomExitRepository roomExitRepository; - @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") - private boolean runOwnedFixtureMode; - @Override @Transactional public void run(ApplicationArguments args) { - if (runOwnedFixtureMode) { - log.warn( - "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture runtime seeding skipped until World-owned materialization is available"); - return; - } ensureDemoTopology(); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index b7072231c8..34d4f6ec2d 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; @@ -226,17 +227,41 @@ void initMetrics() { @Timed(value = "world.prepareInstance") public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( PreparedWorldInstanceRequest request) { - if (fixtureModeEnabled()) { - throw fixtureWritesUnavailable(); - } validatePrepareRequest(request); + RunOwnedWorldLaunchEvidence fixtureEvidence = configuredFixtureEvidence(); + if (fixtureEvidence != null) { + fixtureEvidence.requireMatches(request); + worldInstanceRepository.lockRunOwnedFixtureOperation( + request.tenantId(), request.controlPlaneRequestId()); + WorldInstance operationInstance = + worldInstanceRepository + .findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + request.tenantId(), request.controlPlaneRequestId()) + .orElse(null); + if (operationInstance != null + && !operationInstance.getGameInstanceId().equals(request.gameInstanceId())) { + throw fixtureIdentityConflict(); + } + } WorldInstance existing = - worldInstanceRepository - .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) - .orElse(null); + fixtureEvidence == null + ? worldInstanceRepository + .findByTenantIdAndGameInstanceId(request.tenantId(), request.gameInstanceId()) + .orElse(null) + : worldInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate( + request.tenantId(), request.gameInstanceId()) + .orElse(null); if (existing != null) { if (existing.getRunOwnedFixtureBindingSha256() != null) { - throw fixtureEvidenceUnavailable(); + if (fixtureEvidence == null) { + throw fixtureEvidenceUnavailable(); + } + requireRunOwnedFixtureBinding(existing, fixtureEvidence, request); + return snapshot(existing); + } + if (fixtureEvidence != null) { + throw fixtureIdentityConflict(); } if (!samePreparedRequest(existing, request)) { throw new IllegalArgumentException( @@ -244,7 +269,9 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( } return snapshot(existing); } - validateAttestedLaunchInputs(request); + if (fixtureEvidence == null) { + validateAttestedLaunchInputs(request); + } WorldInstance worldInstance = new WorldInstance(); worldInstance.setTenantId(request.tenantId()); worldInstance.setGameInstanceId(request.gameInstanceId()); @@ -262,6 +289,10 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( worldInstance.setRemapSetId(normalizeBlank(request.remapSetId())); worldInstance.setLifecycleEpoch(1L); worldInstance.setStatus(STATUS_PREPARING); + if (fixtureEvidence != null) { + worldInstance.setRunOwnedFixtureBindingSha256(fixtureEvidence.bindingDigest(request, 1L)); + worldInstance.setRunOwnedFixturePreparingLifecycleEpoch(1L); + } worldInstance.setCreatedAt(Instant.now()); worldInstance.setUpdatedAt(Instant.now()); WorldInstance saved = worldInstanceRepository.save(worldInstance); @@ -295,22 +326,42 @@ public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( @Timed(value = "world.activateInstance") public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { - if (fixtureModeEnabled()) { - throw fixtureWritesUnavailable(); - } WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { - throw fixtureEvidenceUnavailable(); - } - requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); - if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { - return snapshot(worldInstance); + if (!fixtureModeEnabled()) { + throw fixtureEvidenceUnavailable(); + } + RunOwnedWorldLaunchEvidence fixtureEvidence = + runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + PreparedWorldInstanceRequest preparedRequest = preparedRequest(worldInstance); + requireRunOwnedFixtureBinding(worldInstance, fixtureEvidence, preparedRequest); + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + long preparingEpoch = worldInstance.getRunOwnedFixturePreparingLifecycleEpoch(); + if (worldInstance.getLifecycleEpoch() != preparingEpoch + 1L + || (expectedLifecycleEpoch != preparingEpoch + && expectedLifecycleEpoch != worldInstance.getLifecycleEpoch())) { + throw lifecycleEpochMismatch(); + } + return snapshot(worldInstance); + } + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + } else { + if (fixtureModeEnabled()) { + throw fixtureIdentityConflict(); + } + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + return snapshot(worldInstance); + } } if (!STATUS_PREPARING.equals(worldInstance.getStatus())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance is not in PREPARING state"); } - validateAttestedLaunchInputs(preparedRequest(worldInstance)); + if (worldInstance.getRunOwnedFixtureBindingSha256() == null) { + validateAttestedLaunchInputs(preparedRequest(worldInstance)); + } worldInstance.setStatus(STATUS_ACTIVE); worldInstance.setLifecycleEpoch(worldInstance.getLifecycleEpoch() + 1L); worldInstance.setFailureReason(null); @@ -341,6 +392,30 @@ private PreparedWorldInstanceRequest preparedRequest(WorldInstance worldInstance worldInstance.getRemapSetId()); } + private void requireRunOwnedFixtureBinding( + WorldInstance instance, + RunOwnedWorldLaunchEvidence fixtureEvidence, + PreparedWorldInstanceRequest request) { + Long preparingEpoch = instance.getRunOwnedFixturePreparingLifecycleEpoch(); + if (instance.getRunOwnedFixtureBindingSha256() == null + || preparingEpoch == null + || preparingEpoch <= 0L + || preparingEpoch != 1L + || !samePreparedRequest(instance, request) + || !instance + .getRunOwnedFixtureBindingSha256() + .equals(fixtureEvidence.bindingDigest(request, preparingEpoch))) { + throw fixtureEvidenceMismatch(); + } + } + + private RunOwnedWorldLaunchEvidence configuredFixtureEvidence() { + if (!fixtureModeEnabled()) { + return null; + } + return runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + } + private boolean fixtureModeEnabled() { return runOwnedWorldLaunchEvidenceProvider != null && runOwnedWorldLaunchEvidenceProvider.isEnabled(); @@ -351,9 +426,19 @@ private static IllegalArgumentException fixtureEvidenceUnavailable() { "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_UNAVAILABLE: fixture-bound lifecycle requires verified run evidence"); } - private static IllegalArgumentException fixtureWritesUnavailable() { + private static IllegalArgumentException fixtureEvidenceMismatch() { + return new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH: stored fixture binding or prepared identity changed"); + } + + private static IllegalArgumentException fixtureIdentityConflict() { + return new IllegalArgumentException( + "RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT: fixture operation is bound to another instance"); + } + + private static IllegalArgumentException lifecycleEpochMismatch() { return new IllegalArgumentException( - "RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE: fixture prepare and activation are disabled until World-owned materialization is available"); + "WORLD_INSTANCE_LIFECYCLE_STALE: world instance lifecycle epoch mismatch"); } @Override 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 a101b0159a..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 @@ -2,6 +2,10 @@ 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.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import io.grpc.Server; @@ -40,8 +44,6 @@ import net.firedevops.firemud.common.config.ServiceEndpointsProperties; 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.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -67,29 +69,44 @@ 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.v1.GameSessionControlPlaneServiceGrpc; -import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationRequest; -import net.firedevops.firemud.gamesession.v1.GetRunOwnedFixtureLaunchAssociationResponse; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; -import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; +import net.firedevops.firemud.worldmanagement.config.WorldProperties; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; -import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleRequest; -import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldEventRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; import tools.jackson.databind.json.JsonMapper; -/** Socket-level proof of authenticated World launch provenance reads from GS and GDS owners. */ +/** Socket-level proof of authenticated GS to World and World to exact GDS descriptor transport. */ 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 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"; + private static final String WRONG_GS_URI = "spiffe://firemud/ns/other/sa/game-session-service"; private static final String RELEASE_REF = "8ce42642-53ae-4d07-aab8-37c43ce66e0c"; private static final String STORE_PASSWORD = "test-only-world-mtls-password"; private static final String TEST_JWT_SECRET = "testsecretkeytestsecretkeytest1234"; @@ -108,10 +125,8 @@ class RunOwnedWorldLaunchEvidenceMtlsIntegrationTest { private static TestPki pki; private Server worldServer; - private Server gameSessionOwnerServer; private Server gameDesignServer; private GameDesignClient gameDesignClient; - private RunOwnedWorldLaunchEvidenceProvider evidenceProvider; private ManagedChannel gameSessionChannel; @BeforeAll @@ -122,10 +137,6 @@ static void createCertificates() throws Exception { @AfterEach void stopTransport() throws Exception { SessionContext.clear(); - if (evidenceProvider != null) { - evidenceProvider.closeGameSessionFixtureClient(); - evidenceProvider = null; - } if (gameSessionChannel != null) { gameSessionChannel.shutdownNow(); assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); @@ -145,46 +156,27 @@ void stopTransport() throws Exception { assertThat(gameDesignServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); gameDesignServer = null; } - if (gameSessionOwnerServer != null) { - gameSessionOwnerServer.shutdownNow(); - assertThat(gameSessionOwnerServer.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - gameSessionOwnerServer = null; - } } @Test - void physicalMtlsReadsExactStartingFixtureProvenanceWithoutWorldWrites() throws Exception { + void physicalMtlsPrepareActivateAndOriginalEpochReplayReverifyReceiptAndOwnerDescriptor() + throws Exception { Fixture fixture = Fixture.create(temporaryDirectory, pki); AtomicInteger descriptorReads = new AtomicInteger(); - AtomicInteger fixtureReads = new AtomicInteger(); - AtomicReference worldAtGameDesign = new AtomicReference<>(); - AtomicReference worldCertificateAtGameDesign = - new AtomicReference<>(); - AtomicReference descriptorRequestAtOwner = new AtomicReference<>(); - AtomicReference worldAtGameSession = new AtomicReference<>(); - AtomicReference worldCertificateAtGameSession = - new AtomicReference<>(); - AtomicReference - fixtureRequestAtOwner = new AtomicReference<>(); + AtomicReference worldAtOwner = new AtomicReference<>(); + AtomicReference worldCertificateAtOwner = new AtomicReference<>(); + AtomicReference requestAtOwner = new AtomicReference<>(); AtomicBoolean returnChangedDescriptor = new AtomicBoolean(); startGameDesignServer( fixture, descriptorReads, - worldAtGameDesign, - worldCertificateAtGameDesign, - descriptorRequestAtOwner, + worldAtOwner, + worldCertificateAtOwner, + requestAtOwner, returnChangedDescriptor); - startGameSessionOwnerServer( - fixture, - fixtureReads, - worldAtGameSession, - worldCertificateAtGameSession, - fixtureRequestAtOwner); - CommonGrpcClientProperties worldTls = pki.worldClientProperties(); ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setGameDesignService("localhost:" + gameDesignServer.getPort()); - endpoints.setGameSessionService("localhost:" + gameSessionOwnerServer.getPort()); gameDesignClient = new GameDesignClient( endpoints, @@ -200,13 +192,22 @@ public > T customize(T stub) { System.setProperty("firemud.grpc.tls-reload.enabled", "false"); try { ReflectionTestUtils.invokeMethod(gameDesignClient, "init"); - evidenceProvider = fixture.provider(gameDesignClient, endpoints); - AtomicReference readEvidence = new AtomicReference<>(); - WorldManagementGrpcService readOnlyHandler = + RunOwnedWorldLaunchEvidenceProvider evidenceProvider = fixture.provider(gameDesignClient); + AtomicReference storedWorld = new AtomicReference<>(); + AtomicInteger worldSaves = new AtomicInteger(); + WorldInstanceRepository worldRepository = mockWorldRepository(storedWorld, worldSaves); + WorldLifecycleCommandServiceImpl commandService = + newCommandService(worldRepository, evidenceProvider, gameDesignClient); + WorldInstanceActivationServiceImpl activationService = + new WorldInstanceActivationServiceImpl( + commandService, java.util.Optional.empty(), evidenceProvider, worldRepository); + AtomicReference gameSessionAtWorld = new AtomicReference<>(); + AtomicBoolean injectPlayerContext = new AtomicBoolean(); + WorldManagementGrpcService grpcService = new WorldManagementGrpcService( null, null, - null, + activationService, null, null, null, @@ -215,114 +216,382 @@ public > T customize(T stub) { JsonMapper.builder().build(), "dev") { @Override - public void getWorldInstanceLifecycle( - GetWorldInstanceLifecycleRequest request, - StreamObserver responseObserver) { + public void prepareWorldInstance( + PrepareWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + super.prepareWorldInstance(request, responseObserver); + } + + @Override + public void activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest request, + StreamObserver< + net.firedevops.firemud.worldmanagement.v1 + .ActivatePreparedWorldInstanceResponse> + responseObserver) { + gameSessionAtWorld.set(GrpcPeerIdentity.current()); + if (injectPlayerContext.get()) { + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + } try { - readEvidence.set(evidenceProvider.requireAuthenticatedEvidence()); - responseObserver.onNext( - GetWorldInstanceLifecycleResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("TEST_READ_PROVENANCE_ONLY") - .setMessage( - "Controlled handler captured provenance without World reads or writes")) - .build()); - } catch (RuntimeException rejected) { - responseObserver.onNext( - GetWorldInstanceLifecycleResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_INVALID") - .setMessage("Controlled fixture provenance read was rejected")) - .build()); + super.activatePreparedWorldInstance(request, responseObserver); + } finally { + SessionContext.clear(); } - responseObserver.onCompleted(); } }; - worldServer = startWorldServer(readOnlyHandler); + worldServer = startWorldServer(grpcService); gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); - var response = - WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .getWorldInstanceLifecycle( - GetWorldInstanceLifecycleRequest.newBuilder() - .setTenantId("142") - .setGameInstanceId("1001") - .build()); + WorldManagementServiceGrpc.WorldManagementServiceBlockingStub gameSession = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel); - assertThat(response.hasError()).isTrue(); - assertThat(response.getError().getCode()).isEqualTo("TEST_READ_PROVENANCE_ONLY"); - assertThat(readEvidence.get()).isNotNull(); - assertThat(readEvidence.get().gameSessionAssociation().gameSessionTenantId()).isEqualTo(142L); - assertThat(readEvidence.get().gameSessionAssociation().gameInstanceId()).isEqualTo(1001L); - assertThat(readEvidence.get().gameSessionAssociation().currentGameInstanceStatus()) - .isEqualTo( - CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus - .STARTING); - assertThat(readEvidence.get().gameSessionAssociation().fixturePolicySeal()) - .isEqualTo(fixture.policySeal); - assertThat(readEvidence.get().gameSessionAssociation().fixturePolicyRequestBytes()) - .isEqualTo( - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( - fixture.capability, - fixture.creationEvidence, - fixture.source, - fixture.launchReadEvidence)); - assertThat(readEvidence.get().gameSessionAssociation().canonicalTenantId()) - .isEqualTo(fixture.source.canonicalTenantId()); - assertThat(readEvidence.get().gameSessionAssociation().canonicalVersionId().toString()) - .isEqualTo(fixture.bundle.getCanonicalVersionId()); - assertThat(fixtureReads).hasValue(1); - assertThat(descriptorReads).hasValue(1); - assertThat(fixtureRequestAtOwner.get()).isNotNull(); - assertThat(fixtureRequestAtOwner.get().fixtureOperationId().toString()) - .isEqualTo(fixture.operationId); - assertThat(fixtureRequestAtOwner.get().expectedFixturePolicyEvidenceDigest()) - .isEqualTo(fixture.policySeal.evidenceDigest()); - assertThat(worldAtGameSession.get()) + var prepare = + gameSession.prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setGameTemplateId("17") + .setControlPlaneRequestId(fixture.operationId()) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setVersionStateEpoch(77L) + .build()); + assertThat(prepare.hasError()).isFalse(); + assertThat(prepare.getWorldInstance().getStatus()) + .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING); + assertThat(storedWorld.get().getRunOwnedFixtureBindingSha256()).matches("[0-9a-f]{64}"); + assertThat(storedWorld.get().getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + int writesAfterPrepare = worldSaves.get(); + var wrongReference = + gameSession.prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setGameTemplateId("17") + .setControlPlaneRequestId(fixture.operationId()) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef("11111111-1111-4111-8111-111111111111") + .setVersionStateEpoch(77L) + .build()); + assertThat(wrongReference.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterPrepare); + assertThat(descriptorReads).hasValue(2); + + var activated = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(activated.hasError()).isFalse(); + assertThat(activated.getWorldInstance().getStatus()) + .isEqualTo(WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); + assertThat(activated.getWorldInstance().getLifecycleEpoch()).isEqualTo(2L); + int writesAfterActivation = worldSaves.get(); + + var replay = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(replay.hasError()).isFalse(); + assertThat(replay.getWorldInstance()).isEqualTo(activated.getWorldInstance()); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + assertThat(worldAtOwner.get()) .isNotNull() .extracting(GrpcPeerIdentity::uri) .isEqualTo(WORLD_URI); - assertThat(worldAtGameSession.get().isInNamespace("dev")).isTrue(); - assertThat(worldCertificateAtGameSession.get()) + assertThat(worldAtOwner.get().isService("world-management-service")).isTrue(); + assertThat(worldAtOwner.get().isInNamespace("dev")).isTrue(); + assertThat(worldCertificateAtOwner.get()) .isNotNull() .extracting(GrpcPeerCertificateEvidence::leafSha256) .isEqualTo(fingerprint(pki.worldManagement().certificate())); - assertThat(worldAtGameDesign.get()) + assertThat(requestAtOwner.get()).isNotNull(); + assertThat(requestAtOwner.get().getRequestId()).isNotBlank(); + assertThat(requestAtOwner.get().getCanonicalTenantId()) + .isEqualTo(fixture.descriptorEvidence().request().canonicalTenantId().toString()); + assertThat(requestAtOwner.get().getWorldSlug()) + .isEqualTo(fixture.descriptorEvidence().worldSlug()); + assertThat(requestAtOwner.get().getControlPlaneRequestId()).isEqualTo(fixture.operationId()); + assertThat(requestAtOwner.get().getExpectedRequestDigest()) + .isEqualTo(fixture.descriptorEvidence().requestDigest()); + assertThat(requestAtOwner.get().getExpectedResultDigest()) + .isEqualTo(fixture.descriptorEvidence().resultDigest()); + assertThat(gameSessionAtWorld.get()) .isNotNull() .extracting(GrpcPeerIdentity::uri) - .isEqualTo(WORLD_URI); - assertThat(worldCertificateAtGameDesign.get()) - .isNotNull() - .extracting(GrpcPeerCertificateEvidence::leafSha256) - .isEqualTo(fingerprint(pki.worldManagement().certificate())); - assertThat(descriptorRequestAtOwner.get()).isNotNull(); - assertThat(descriptorRequestAtOwner.get().getControlPlaneRequestId()) - .isEqualTo(fixture.operationId); - assertThat(descriptorRequestAtOwner.get().getExpectedRequestDigest()) - .isEqualTo(fixture.descriptorEvidence.requestDigest()); - assertThat(descriptorRequestAtOwner.get().getExpectedResultDigest()) - .isEqualTo(fixture.descriptorEvidence.resultDigest()); - assertThat(Files.readAllBytes(fixture.capabilityPath)) - .isEqualTo(fixture.originalCapabilityBytes); - assertThat(Files.readAllBytes(fixture.receiptPath)).isEqualTo(fixture.originalReceiptBytes); + .isEqualTo(GS_URI); + + injectPlayerContext.set(true); + var ordinaryCaller = + gameSession.activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + injectPlayerContext.set(false); + assertThat(ordinaryCaller.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); + assertThatThrownBy( + () -> + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongNamespaceGameSessionClient()); + var wrongPeer = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongPeer.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongGameSessionLeafClient()); + var wrongLeaf = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongLeaf.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = + channel("localhost", worldServer.getPort(), pki.wrongCaGameSessionClient()); + assertThatThrownBy( + () -> + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + gameSessionChannel.shutdownNow(); + assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + gameSessionChannel = channel("localhost", worldServer.getPort(), pki.gameSessionClient()); + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "caCertificateSha256", "f".repeat(64)); + var wrongCa = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongCa.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "worldManagementLeafSha256", "e".repeat(64)); + var wrongWorldRecipient = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongWorldRecipient.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + Fixture.writeFieldMismatch( + fixture, "worldManagementUriSan", "spiffe://firemud/ns/dev/sa/other-world-service"); + var wrongWorldUri = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(wrongWorldUri.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + fixture.reset(); + var unknownInstance = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("202") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(unknownInstance.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(4); + + var duplicateOperation = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .prepareWorldInstance( + PrepareWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("202") + .setGameTemplateId("17") + .setControlPlaneRequestId(fixture.operationId()) + .setLaunchDescriptorId("launch-descriptor-fixture-11") + .setVersionId("11") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setReleaseBundleId("77") + .setPublishedReleaseBundleRef(RELEASE_REF) + .setVersionStateEpoch(77L) + .build()); + assertThat(duplicateOperation.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(5); + + var staleAttempt = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(99L) + .build()); + assertThat(staleAttempt.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch(fixture, "sourceGameTenantKey", "43"); + var changedSource = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedSource.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "runId", "changed-run"); + var changedRun = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedRun.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeFieldMismatch(fixture, "composeProjectName", "different-project"); + var changedProject = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedProject.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch( + fixture, "fixtureOperationId", "11111111-1111-4111-8111-111111111111"); + var changedReceipt = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedReceipt.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); + Fixture.writeReceiptFieldMismatch(fixture, "launchDescriptorBase64", "AAAA"); + var changedReceiptDescriptor = + WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build()); + assertThat(changedReceiptDescriptor.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(6); + + fixture.reset(); returnChangedDescriptor.set(true); - var rejected = + var changedOwnerDescriptor = WorldManagementServiceGrpc.newBlockingStub(gameSessionChannel) - .getWorldInstanceLifecycle( - GetWorldInstanceLifecycleRequest.newBuilder() - .setTenantId("142") - .setGameInstanceId("1001") + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) .build()); - assertThat(rejected.hasError()).isTrue(); - assertThat(rejected.getError().getCode()) - .isEqualTo("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_INVALID"); - assertThat(descriptorReads).hasValue(2); - assertThat(fixtureReads).hasValue(1); - assertThat(Files.readAllBytes(fixture.capabilityPath)) - .isEqualTo(fixture.originalCapabilityBytes); - assertThat(Files.readAllBytes(fixture.receiptPath)).isEqualTo(fixture.originalReceiptBytes); + returnChangedDescriptor.set(false); + assertThat(changedOwnerDescriptor.hasError()).isTrue(); + assertThat(worldSaves).hasValue(writesAfterActivation); + assertThat(descriptorReads).hasValue(7); } finally { if (previousReload == null) { System.clearProperty("firemud.grpc.tls-reload.enabled"); @@ -401,9 +670,9 @@ public void getLaunchDescriptor( .canonicalTenantId() .toString() .equals(request.getCanonicalTenantId()) - || !isExpectedReadRequestId(request.getRequestId(), fixture.operationId) + || !isExpectedReadRequestId(request.getRequestId(), fixture.operationId()) || !fixture.descriptorEvidence().worldSlug().equals(request.getWorldSlug()) - || !fixture.operationId.equals(request.getControlPlaneRequestId()) + || !fixture.operationId().equals(request.getControlPlaneRequestId()) || !fixture .descriptorEvidence() .requestDigest() @@ -451,74 +720,6 @@ public void getLaunchDescriptor( .start(); } - private void startGameSessionOwnerServer( - Fixture fixture, - AtomicInteger fixtureReads, - AtomicReference worldAtOwner, - AtomicReference worldCertificateAtOwner, - AtomicReference - requestAtOwner) - throws Exception { - String expectedWorldFingerprint = fingerprint(pki.worldManagement().certificate()); - var service = - new GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceImplBase() { - @Override - public void getRunOwnedFixtureLaunchAssociation( - GetRunOwnedFixtureLaunchAssociationRequest request, - StreamObserver responseObserver) { - fixtureReads.incrementAndGet(); - worldAtOwner.set(GrpcPeerIdentity.current()); - worldCertificateAtOwner.set(GrpcPeerCertificateEvidence.current()); - try { - var selector = - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest(request); - requestAtOwner.set(selector); - if (worldAtOwner.get() == null - || !WORLD_URI.equals(worldAtOwner.get().uri()) - || !worldAtOwner.get().isService("world-management-service") - || !worldAtOwner.get().isInNamespace("dev") - || worldCertificateAtOwner.get() == null - || !expectedWorldFingerprint.equals(worldCertificateAtOwner.get().leafSha256()) - || !"dev".equals(selector.targetNamespace()) - || !fixture.operationId.equals(selector.fixtureOperationId().toString()) - || !fixture - .policySeal - .evidenceDigest() - .equals(selector.expectedFixturePolicyEvidenceDigest())) { - responseObserver.onError( - Status.PERMISSION_DENIED - .withDescription( - "World peer or exact fixture launch selector did not match") - .asRuntimeException()); - return; - } - responseObserver.onNext( - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse( - fixture.fixtureAssociation(selector))); - responseObserver.onCompleted(); - } catch (RuntimeException invalid) { - responseObserver.onError( - Status.INVALID_ARGUMENT - .withDescription("Fixture owner read selector was invalid") - .asRuntimeException()); - } - } - }; - gameSessionOwnerServer = - NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - SslContextBuilder.forServer( - pki.gameSessionClient().privateKey(), - pki.gameSessionClient().certificate())) - .trustManager(pki.caCertificateValue()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) - .build() - .start(); - } - private Server startWorldServer(WorldManagementGrpcService service) throws Exception { return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext( @@ -545,6 +746,16 @@ private ManagedChannel channel(String host, int port, TestIdentity identity) thr .build(); } + private ManagedChannel channelWithoutClientIdentity(String host, int port) throws Exception { + return NettyChannelBuilder.forAddress(host, port) + .overrideAuthority("localhost") + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forClient().trustManager(pki.caCertificateValue())) + .build()) + .build(); + } + private static boolean isExpectedReadRequestId(String requestId, String operationId) { try { return !operationId.equals(UUID.fromString(requestId).toString()); @@ -553,40 +764,148 @@ private static boolean isExpectedReadRequestId(String requestId, String operatio } } + private RunOwnedWorldLaunchEvidenceProvider provider(Path directory, GameDesignClient client) { + CommonGrpcClientProperties tls = pki.worldClientProperties(); + return new RunOwnedWorldLaunchEvidenceProvider( + true, + directory.resolve("capability.json").toString(), + directory.resolve("source-receipt.json").toString(), + RUN_ID, + PROJECT, + tls, + client); + } + + private WorldInstanceRepository mockWorldRepository( + AtomicReference storedWorld, AtomicInteger worldSaves) { + WorldInstanceRepository repository = mock(WorldInstanceRepository.class); + when(repository.findByTenantIdAndGameInstanceId(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + anyLong(), any(String.class))) + .thenAnswer( + invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getControlPlaneRequestId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); + when(repository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance instance = invocation.getArgument(0); + if (instance.getId() == null) { + instance.setId(101L); + } + worldSaves.incrementAndGet(); + storedWorld.set(instance); + return instance; + }); + return repository; + } + + private WorldLifecycleCommandServiceImpl newCommandService( + WorldInstanceRepository worldRepository, + RunOwnedWorldLaunchEvidenceProvider evidenceProvider, + GameDesignClient client) { + RegionInstanceRepository regionRepository = mock(RegionInstanceRepository.class); + ZoneRepository zoneRepository = mock(ZoneRepository.class); + ZoneInstanceRepository zoneInstanceRepository = mock(ZoneInstanceRepository.class); + RoomRepository roomRepository = mock(RoomRepository.class); + RoomExitRepository roomExitRepository = mock(RoomExitRepository.class); + RoomInstanceRepository roomInstanceRepository = mock(RoomInstanceRepository.class); + RoomInstanceExitRepository roomInstanceExitRepository = mock(RoomInstanceExitRepository.class); + when(regionRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(zoneInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(anyLong(), anyLong())) + .thenReturn(List.of()); + when(roomInstanceRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(roomInstanceExitRepository.save(any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + WorldProperties properties = new WorldProperties(); + properties.setLocalShardId(7); + WorldLifecycleCommandServiceImpl commandService = + new WorldLifecycleCommandServiceImpl( + worldRepository, + regionRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + mock(WorldEventRepository.class), + properties, + client, + mock(EntityManagementClient.class), + new SimpleMeterRegistry(), + new PlatformTransactionManager() { + @Override + public SimpleTransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + }, + evidenceProvider); + commandService.initMetrics(); + 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; private final Path capabilityPath; private final Path receiptPath; - private final String operationId; - private final String claimDigest; - private final byte[] originalCapabilityBytes; - private final byte[] originalReceiptBytes; + private final String originalCapabilityJson; + private final String originalReceiptJson; + private String capabilityJson; + private String receiptJson; private final AuthoredWorldSourceEvidence source; private final PublishedReleaseBundle bundle; private final VersionAssetArtifactState artifact; private final VersionStateSnapshot version; private final LaunchDescriptor launchDescriptor; private final AuthoredWorldLaunchDescriptorEvidence descriptorEvidence; - private final FreshTenantCreationEvidence creationEvidence; - private final RunOwnedInitialAdmissionFixtureWireCodec.Capability capability; - private final RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt sourceReceipt; - private final RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence launchReadEvidence; - private final RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal policySeal; + 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"); - claimDigest = - HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest((RUN_ID + "\n" + PROJECT + "\n").getBytes(StandardCharsets.UTF_8))); operationId = RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( - claimDigest, + CLAIM_DIGEST, RUN_ID, PROJECT, fingerprint(pki.gameSessionClient().certificate()), @@ -598,11 +917,12 @@ private Fixture(Path parent, TestPki pki) throws Exception { version = versionState(); descriptorEvidence = RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.descriptorEvidence( - source, bundle, version, operationId); + source, bundle, version); launchDescriptor = AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(descriptorEvidence); - creationEvidence = creationEvidence(source); - launchReadEvidence = + var capability = capability(pki, operationId); + var creationEvidence = creationEvidence(source); + var launchReadEvidence = new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( RunOwnedInitialAdmissionFixtureWireCodec.LAUNCH_READ_EVIDENCE_SCHEMA, 17L, @@ -612,12 +932,8 @@ private Fixture(Path parent, TestPki pki) throws Exception { launchDescriptor); String policyRequestDigest = RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( - RunOwnedInitialAdmissionFixtureWireCodec.parseCapability( - capabilityJson(pki, operationId, claimDigest).getBytes(StandardCharsets.UTF_8)), - creationEvidence, - source, - launchReadEvidence); - policySeal = + capability, creationEvidence, source, launchReadEvidence); + var policySeal = new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, @@ -625,8 +941,8 @@ private Fixture(Path parent, TestPki pki) throws Exception { policyRequestDigest, RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( UUID.fromString(operationId), policyRequestDigest)); - String capabilityJson = capabilityJson(pki, operationId, claimDigest); - String receiptJson = + capabilityJson = capabilityJson(capability); + receiptJson = receiptJson( source, bundle, @@ -635,55 +951,27 @@ private Fixture(Path parent, TestPki pki) throws Exception { launchDescriptor, creationEvidence, policySeal, - operationId, pki); - originalCapabilityBytes = capabilityJson.getBytes(StandardCharsets.UTF_8); - originalReceiptBytes = receiptJson.getBytes(StandardCharsets.UTF_8); - writeReadonly(capabilityPath, originalCapabilityBytes); - writeReadonly(receiptPath, originalReceiptBytes); - capability = - RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(originalCapabilityBytes); - sourceReceipt = - RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( - originalReceiptBytes, capability); + originalCapabilityJson = capabilityJson; + originalReceiptJson = receiptJson; + writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); } static Fixture create(Path parent, TestPki pki) throws Exception { return new Fixture(parent, pki); } - RunOwnedWorldLaunchEvidenceProvider provider( - GameDesignClient client, ServiceEndpointsProperties endpoints) { + RunOwnedWorldLaunchEvidenceProvider provider(GameDesignClient client) { + CommonGrpcClientProperties tls = pki.worldClientProperties(); return new RunOwnedWorldLaunchEvidenceProvider( true, - capabilityPath.toString(), - receiptPath.toString(), + directory.resolve("capability.json").toString(), + directory.resolve("source-receipt.json").toString(), RUN_ID, PROJECT, - pki.worldClientProperties(), - client, - endpoints, - new GrpcChannelFactory(), - "dev"); - } - - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult fixtureAssociation( - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request) { - return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( - request, - 142L, - 1001L, - source.canonicalTenantId(), - UUID.fromString("20000000-0000-4000-8000-000000000011"), - UUID.fromString(bundle.getCanonicalVersionId()), - UUID.fromString("30000000-0000-4000-8000-000000000011"), - UUID.fromString("40000000-0000-4000-8000-000000000011"), - 1L, - CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, - 0L, - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( - capability, creationEvidence, source, launchReadEvidence), - policySeal); + tls, + client); } LaunchDescriptor launchDescriptor() { @@ -693,12 +981,51 @@ LaunchDescriptor launchDescriptor() { AuthoredWorldLaunchDescriptorEvidence descriptorEvidence() { return descriptorEvidence; } + + String operationId() { + return operationId; + } + + void reset() throws IOException { + capabilityJson = originalCapabilityJson; + receiptJson = originalReceiptJson; + writeReadonly(capabilityPath, capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(receiptPath, receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + static void writeFieldMismatch(Fixture fixture, String fieldName, String replacement) + throws IOException { + fixture.capabilityJson = replaceField(fixture.capabilityJson, fieldName, replacement); + fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); + writeReadonly( + fixture.capabilityPath, fixture.capabilityJson.getBytes(StandardCharsets.UTF_8)); + writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + static void writeReceiptFieldMismatch(Fixture fixture, String fieldName, String replacement) + throws IOException { + fixture.receiptJson = replaceField(fixture.receiptJson, fieldName, replacement); + writeReadonly(fixture.receiptPath, fixture.receiptJson.getBytes(StandardCharsets.UTF_8)); + } + + private static String replaceField(String json, String fieldName, String replacement) { + String marker = "\"" + fieldName + "\":\""; + int start = json.indexOf(marker); + if (start < 0) { + throw new IllegalStateException("Fixture field was not present: " + fieldName); + } + int valueStart = start + marker.length(); + int end = json.indexOf('"', valueStart); + if (end < 0) { + throw new IllegalStateException("Fixture field value was not terminated: " + fieldName); + } + return json.substring(0, valueStart) + replacement + json.substring(end); + } } private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { UUID registrationId = UUID.fromString(operationId); UUID tenant = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); - UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); String requestDigest = AuthoredWorldSourceDigest.requestDigest( "dev", registrationId, tenant, "fixture-tenant", "demo", "Demo World"); @@ -706,7 +1033,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { 1, "dev", registrationId, - sourceOperationId, + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), requestDigest, tenant, "fixture-tenant", @@ -718,7 +1045,7 @@ private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { AuthoredWorldSourceDigest.evidenceDigest( "dev", registrationId, - sourceOperationId, + UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"), requestDigest, tenant, "fixture-tenant", @@ -729,33 +1056,6 @@ private static AuthoredWorldSourceEvidence sourceEvidence(String operationId) { "NEW_GAME_ROW")); } - private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { - UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); - UUID creationOperationId = UUID.fromString("31e36104-3336-4cf5-899a-cb419f2f361e"); - String requestDigest = - GameTenantCreationDigest.requestDigest( - "dev", creationRequestId, "42", "Fixture Game", null); - return new FreshTenantCreationEvidence( - 1, - "dev", - creationRequestId, - creationOperationId, - requestDigest, - source.canonicalTenantId(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind(), - GameTenantCreationDigest.evidenceDigest( - "dev", - creationRequestId, - creationOperationId, - requestDigest, - source.canonicalTenantId(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind())); - } - private static PublishedReleaseBundle publishedBundle(AuthoredWorldSourceEvidence source) { return PublishedReleaseBundle.newBuilder() .setId(77L) @@ -807,10 +1107,10 @@ private static VersionStateSnapshot versionState() { } private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( - AuthoredWorldSourceEvidence source, String operationId) { + AuthoredWorldSourceEvidence source) { return new AuthoredWorldLaunchDescriptorEvidence.Request( "dev", - operationId, + source.registrationRequestId().toString(), source.canonicalTenantId(), source.worldSlug(), source.operationId(), @@ -829,10 +1129,9 @@ private static AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest( private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( AuthoredWorldSourceEvidence source, PublishedReleaseBundle bundle, - VersionStateSnapshot version, - String operationId) { + VersionStateSnapshot version) { return AuthoredWorldLaunchDescriptorEvidence.create( - expectedRequest(source, operationId), + expectedRequest(source), "launch-descriptor-fixture-11", bundle.getVersionId(), false, @@ -846,21 +1145,92 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( null); } - private static String capabilityJson(TestPki pki, String operationId, String claimDigest) - 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","claimDigest":"%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, + 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, - fingerprint(pki.gameSessionClient().certificate()), - GS_URI, - fingerprint(pki.caCertificateValue()), - WORLD_URI, - fingerprint(pki.worldManagement().certificate()), - claimDigest); + requestDigest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); } private static String receiptJson( @@ -870,8 +1240,7 @@ private static String receiptJson( VersionStateSnapshot version, LaunchDescriptor descriptor, FreshTenantCreationEvidence creation, - RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal seal, - String operationId, + RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal policySeal, TestPki pki) throws Exception { return """ @@ -880,7 +1249,7 @@ private static String receiptJson( .formatted( RUN_ID, PROJECT, - operationId, + source.registrationRequestId(), GS_URI, fingerprint(pki.gameSessionClient().certificate()), fingerprint(pki.caCertificateValue()), @@ -911,11 +1280,11 @@ private static String receiptJson( creation.sourceGameTenantKey(), creation.provenanceKind(), creation.evidenceDigest(), - seal.schema(), - seal.ownerService(), - seal.operationId(), - seal.requestDigest(), - seal.evidenceDigest()); + policySeal.schema(), + policySeal.ownerService(), + policySeal.operationId(), + policySeal.requestDigest(), + policySeal.evidenceDigest()); } private static String encode(byte[] bytes) { @@ -927,7 +1296,25 @@ 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( + path, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.GROUP_READ)); + } Files.write(path, value); Files.setPosixFilePermissions( path, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); @@ -944,7 +1331,10 @@ private record TestPki( Path caCertificatePath, TestIdentity worldManagement, TestIdentity gameDesignServer, - TestIdentity gameSessionClient) { + TestIdentity gameSessionClient, + TestIdentity wrongNamespaceGameSessionClient, + TestIdentity wrongGameSessionLeafClient, + TestIdentity wrongCaGameSessionClient) { static TestPki create(Path directory) throws Exception { Path caStore = directory.resolve("world-mtls-ca.p12"); runKeytool( @@ -990,13 +1380,56 @@ static TestPki create(Path directory) throws Exception { caCertificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); } + Path wrongCaStore = directory.resolve("world-mtls-untrusted-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=Untrusted World mTLS test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + wrongCaStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path wrongCa = directory.resolve("world-mtls-untrusted-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + wrongCaStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + wrongCa.toString(), + "-rfc"); return new TestPki( caCertificate, ca, issueIdentity( directory, caStore, ca, "world-management", WORLD_URI, "serverAuth,clientAuth"), issueIdentity(directory, caStore, ca, "game-design", GDS_URI, "serverAuth"), - issueIdentity(directory, caStore, ca, "game-session", GS_URI, "serverAuth,clientAuth")); + issueIdentity(directory, caStore, ca, "game-session", GS_URI, "clientAuth"), + issueIdentity(directory, caStore, ca, "wrong-game-session", WRONG_GS_URI, "clientAuth"), + issueIdentity(directory, caStore, ca, "wrong-game-session-leaf", GS_URI, "clientAuth"), + issueIdentity( + directory, wrongCaStore, wrongCa, "wrong-ca-game-session", GS_URI, "clientAuth")); } CommonGrpcClientProperties worldClientProperties() { 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 d3a1a8894e..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 @@ -2,17 +2,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.clearInvocations; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -29,6 +27,7 @@ import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; import net.firedevops.firemud.worldmanagement.entity.WorldInstance; import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; @@ -40,12 +39,8 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; -import net.firedevops.firemud.worldmanagement.service.impl.InitialAdmissionBindHoldReconciler; -import net.firedevops.firemud.worldmanagement.service.impl.InstanceServiceImpl; -import net.firedevops.firemud.worldmanagement.service.impl.WorldEventServiceImpl; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; import org.jooq.DSLContext; -import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; @@ -54,7 +49,6 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; @@ -63,8 +57,7 @@ import org.testcontainers.junit.jupiter.Testcontainers; /** - * PostgreSQL proof of fixture lifecycle denial before effects and passive binding storage. - * Controlled storage rows do not establish World materialization or activation authority. + * Real PostgreSQL proof for fixture binding durability, uniqueness, lock serialization, and CAS. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -91,97 +84,107 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @Autowired private AutowireCapableBeanFactory beanFactory; - @MockitoSpyBean private WorldInstanceRepository repository; + @Autowired private WorldInstanceRepository repository; @Autowired private WorldLifecycleCommandService lifecycleService; @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; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; - // Keep unrelated scheduled writers inert so whole-schema snapshots measure fixture effects. - @MockitoBean private InitialAdmissionBindHoldReconciler initialAdmissionBindHoldReconciler; - @MockitoBean private WorldEventServiceImpl worldEventService; - @MockitoBean private InstanceServiceImpl instanceService; @Test - void fixturePrepareAndActivationRetryAndRestartDenyBeforeReadsOrPostgresEffects() { + void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurableBinding() { long tenantId = 8_810_001L; long gameInstanceId = uniqueId(); PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - // This pre-existing controlled storage row supplies no canonical association or authority. - repository.save(passiveStorageRow(request, "a".repeat(64))); - when(fixtureProvider.isEnabled()).thenReturn(true); - clearInvocations( - repository, - fixtureEvidence, - gameDesignClient, - gameSessionClient, - entityManagementClient, - bindProofClient); - Map> before = postgresState(); + String binding = "a".repeat(64); + configureEvidence(binding); try { - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); - assertFixtureDenied( - () -> lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); - assertFixtureDenied( - () -> - lifecycleService.prepareWorldInstance( - request(tenantId, uniqueId(), request.controlPlaneRequestId()))); + var prepared = lifecycleService.prepareWorldInstance(request); + WorldInstance stored = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(prepared.status()).isEqualTo("PREPARING"); + assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + assertThat(stored.getPublishedReleaseBundleRef()).isEqualTo(RELEASE_REF); + assertThat(stored.getRowVersion()).isZero(); + + var active = lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); + assertThat(active.status()).isEqualTo("ACTIVE"); + assertThat(active.lifecycleEpoch()).isEqualTo(2L); + WorldInstance activeRow = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(activeRow.getRunOwnedFixtureBindingSha256()).isEqualTo(binding); + assertThat(activeRow.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + long activeRowVersion = activeRow.getRowVersion(); RunOwnedWorldLaunchEvidenceProvider restartedProvider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence restartedEvidence = mock(RunOwnedWorldLaunchEvidence.class); when(restartedProvider.isEnabled()).thenReturn(true); - WorldInstanceRepository restartedRepository = spy(new WorldInstanceRepository(dsl)); + when(restartedProvider.requireAuthenticatedEvidence()).thenReturn(restartedEvidence); + when(restartedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + WorldInstanceRepository restartedRepository = new WorldInstanceRepository(dsl); WorldLifecycleCommandServiceImpl restartedService = restartedLifecycleService(restartedRepository, restartedProvider); - assertFixtureDenied(() -> restartedService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)); - assertThat(postgresState()).isEqualTo(before); - verifyNoInteractions(repository, restartedRepository); - org.mockito.Mockito.verify(restartedProvider, org.mockito.Mockito.never()) - .requireAuthenticatedEvidence(); - verifyNoUpstreamReads(); - } finally { - dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); - } - } - @Test - void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCas() { - clearInvocations(fixtureProvider, fixtureEvidence); - long tenantId = 8_810_004L; - long gameInstanceId = uniqueId(); - PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - try { - WorldInstance stored = repository.save(passiveStorageRow(request, "a".repeat(64))); - assertThat(stored.getStatus()).isEqualTo("PREPARING"); - assertThat(stored.getLifecycleEpoch()).isEqualTo(1L); - assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo("a".repeat(64)); - assertThat(stored.getPublishedReleaseBundleRef()).isEqualTo(RELEASE_REF); - assertThat(stored.getRowVersion()).isZero(); - WorldInstanceRepository restartedRepository = new WorldInstanceRepository(dsl); + var replay = restartedService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); + assertThat(replay).isEqualTo(active); + verify(restartedProvider).requireAuthenticatedEvidence(); assertThat( - restartedRepository + repository .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(stored); + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + var prepareReplay = restartedService.prepareWorldInstance(request); + assertThat(prepareReplay).isEqualTo(active); assertThat( - restartedRepository - .findRunOwnedFixtureByTenantIdAndControlPlaneRequestId( - tenantId, request.controlPlaneRequestId()) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(stored); + repository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + verify(restartedProvider, org.mockito.Mockito.times(2)).requireAuthenticatedEvidence(); + + RunOwnedWorldLaunchEvidenceProvider changedProvider = + mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence changedEvidence = mock(RunOwnedWorldLaunchEvidence.class); + when(changedProvider.isEnabled()).thenReturn(true); + when(changedProvider.requireAuthenticatedEvidence()).thenReturn(changedEvidence); + when(changedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("b".repeat(64)); + assertThatThrownBy( + () -> + restartedLifecycleService(new WorldInstanceRepository(dsl), changedProvider) + .activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); + assertThat( + repository + .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) + .orElseThrow() + .getRowVersion()) + .isEqualTo(activeRowVersion); + + PreparedWorldInstanceRequest duplicateOperation = + request(tenantId, uniqueId(), request.controlPlaneRequestId()); + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); + assertThatThrownBy(() -> lifecycleService.prepareWorldInstance(duplicateOperation)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:"); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); + verify(fixtureProvider, org.mockito.Mockito.atLeast(3)).requireAuthenticatedEvidence(); assertThatThrownBy( () -> @@ -208,13 +211,6 @@ void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCa gameInstanceId)) .isInstanceOf(RuntimeException.class); - assertThat( - restartedRepository - .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(stored); - WorldInstance staleCopy = repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); WorldInstance winningCopy = @@ -229,19 +225,27 @@ void controlledPassiveStorageRetainsBindingAndEnforcesConstraintsUniquenessAndCa repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); assertThat(durableWinner.getFailureReason()).isEqualTo("CAS winner"); assertThat(durableWinner.getRowVersion()).isEqualTo(savedWinningCopy.getRowVersion()); - assertThat(durableWinner.getRunOwnedFixtureBindingSha256()).isEqualTo("a".repeat(64)); - assertThat(durableWinner.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); - WorldInstance duplicate = - passiveStorageRow( - request(tenantId, uniqueId(), request.controlPlaneRequestId()), "c".repeat(64)); + + WorldInstance duplicate = new WorldInstance(); + duplicate.setTenantId(tenantId); + duplicate.setGameInstanceId(uniqueId()); + duplicate.setGameTemplateId(17L); + duplicate.setControlPlaneRequestId(request.controlPlaneRequestId()); + duplicate.setLaunchDescriptorId("launch-descriptor-fixture-11"); + duplicate.setVersionId(11L); + duplicate.setRuntimeFlagsJson("{}"); + duplicate.setGenerationConfigRevision("genrev-11"); + duplicate.setReleaseBundleId(77L); + duplicate.setPublishedReleaseBundleRef(RELEASE_REF); + duplicate.setVersionStateEpoch(77L); + duplicate.setLifecycleEpoch(1L); + duplicate.setStatus("PREPARING"); + duplicate.setCreatedAt(Instant.now()); + duplicate.setUpdatedAt(Instant.now()); + duplicate.setRowVersion(0L); + duplicate.setRunOwnedFixtureBindingSha256("c".repeat(64)); + duplicate.setRunOwnedFixturePreparingLifecycleEpoch(1L); assertThatThrownBy(() -> repository.save(duplicate)).isInstanceOf(RuntimeException.class); - assertThat( - restartedRepository - .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow()) - .usingRecursiveComparison() - .isEqualTo(durableWinner); - verifyNoInteractions(fixtureProvider, fixtureEvidence); } finally { dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); } @@ -285,126 +289,51 @@ void operationAdvisoryLockSerializesConcurrentRetriesOnPostgres() throws Excepti } @Test - void concurrentFixturePrepareAndActivationRetriesDenyWithoutPostgresOrUpstreamEffects() - throws Exception { + void concurrentPrepareRetriesCreateOneFixtureBoundWorldInstance() throws Exception { long tenantId = 8_810_003L; long gameInstanceId = uniqueId(); PreparedWorldInstanceRequest request = request(tenantId, gameInstanceId, operationId()); - when(fixtureProvider.isEnabled()).thenReturn(true); - clearInvocations( - repository, - fixtureEvidence, - gameDesignClient, - gameSessionClient, - entityManagementClient, - bindProofClient); - Map> before = postgresState(); + configureEvidence("d".repeat(64)); CountDownLatch ready = new CountDownLatch(2); CountDownLatch start = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { - Future first = + Future first = executor.submit( () -> { ready.countDown(); await(start); - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> - lifecycleService.activatePreparedWorldInstance( - tenantId, gameInstanceId, 1L)); + return lifecycleService.prepareWorldInstance(request); }); - Future second = + Future second = executor.submit( () -> { ready.countDown(); await(start); - assertFixtureDenied(() -> lifecycleService.prepareWorldInstance(request)); - assertFixtureDenied( - () -> - lifecycleService.activatePreparedWorldInstance( - tenantId, gameInstanceId, 1L)); + return lifecycleService.prepareWorldInstance(request); }); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); - first.get(20, TimeUnit.SECONDS); - second.get(20, TimeUnit.SECONDS); - assertThat(postgresState()).isEqualTo(before); - verifyNoInteractions(repository); - verifyNoUpstreamReads(); + + var firstResult = first.get(20, TimeUnit.SECONDS); + var secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.status()).isEqualTo("PREPARING"); + WorldInstance stored = + repository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).orElseThrow(); + assertThat(stored.getRunOwnedFixtureBindingSha256()).isEqualTo("d".repeat(64)); + assertThat(stored.getRunOwnedFixturePreparingLifecycleEpoch()).isEqualTo(1L); + verify(fixtureProvider, org.mockito.Mockito.atLeast(2)).requireAuthenticatedEvidence(); } finally { start.countDown(); + dsl.execute("DELETE FROM world_instance WHERE tenant_id = ?", tenantId); } } - private static void assertFixtureDenied( - org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { - assertThatThrownBy(call) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:"); - } - - private void verifyNoUpstreamReads() { - org.mockito.Mockito.verify(fixtureProvider, org.mockito.Mockito.never()) - .requireAuthenticatedEvidence(); - verifyNoInteractions( - fixtureEvidence, - gameDesignClient, - gameSessionClient, - entityManagementClient, - bindProofClient); - } - - private Map> postgresState() { - String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); - assertThat(schema).isEqualTo("world_management_service"); - List tables = - dsl.fetch("SELECT tablename FROM pg_tables WHERE schemaname = ? ORDER BY tablename", schema) - .getValues(0, String.class); - assertThat(tables).isNotEmpty().contains("world_instance"); - Map> state = new LinkedHashMap<>(); - for (String table : tables) { - // Entire rows and xmin retain source/resource bytes as well as lifecycle/CAS state. - state.put( - table, - dsl.fetch( - "SELECT to_jsonb(retained)::text || ':xmin=' || retained.xmin::text FROM " - + DSL.name(schema, table) - + " retained ORDER BY 1") - .getValues(0, String.class)); - } - List sequences = - dsl.fetch( - "SELECT to_jsonb(retained)::text FROM (SELECT sequencename, last_value " - + "FROM pg_sequences WHERE schemaname = ? ORDER BY sequencename) retained", - schema) - .getValues(0, String.class); - assertThat(sequences).isNotEmpty(); - state.put("sequences", sequences); - return state; - } - - private static WorldInstance passiveStorageRow( - PreparedWorldInstanceRequest request, String binding) { - WorldInstance row = new WorldInstance(); - row.setTenantId(request.tenantId()); - row.setGameInstanceId(request.gameInstanceId()); - row.setGameTemplateId(request.gameTemplateId()); - row.setControlPlaneRequestId(request.controlPlaneRequestId()); - row.setLaunchDescriptorId(request.launchDescriptorId()); - row.setVersionId(request.versionId()); - row.setRuntimeFlagsJson(request.runtimeFlagsJson()); - row.setGenerationConfigRevision(request.generationConfigRevision()); - row.setReleaseBundleId(request.releaseBundleId()); - row.setPublishedReleaseBundleRef(request.publishedReleaseBundleRef()); - row.setVersionStateEpoch(request.versionStateEpoch()); - row.setLifecycleEpoch(1L); - row.setStatus("PREPARING"); - row.setCreatedAt(Instant.now()); - row.setUpdatedAt(Instant.now()); - row.setRowVersion(0L); - row.setRunOwnedFixtureBindingSha256(binding); - row.setRunOwnedFixturePreparingLifecycleEpoch(1L); - return row; + private void configureEvidence(String binding) { + when(fixtureProvider.isEnabled()).thenReturn(true); + when(fixtureProvider.requireAuthenticatedEvidence()).thenReturn(fixtureEvidence); + when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn(binding); } private WorldLifecycleCommandServiceImpl restartedLifecycleService( 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 d5d7b7b000..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 @@ -2,67 +2,27 @@ 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.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -import io.grpc.Context; -import java.io.IOException; -import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.Security; -import java.security.cert.X509Certificate; -import java.time.Instant; -import java.util.Base64; -import java.util.Date; -import java.util.HexFormat; import java.util.Set; import java.util.UUID; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationClient; -import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerCertificateEvidence; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; 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.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.worldmanagement.client.GameDesignClient; -import net.firedevops.firemud.worldmanagement.client.GameDesignClient.LaunchDescriptorReadback; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.BasicConstraints; -import org.bouncycastle.asn1.x509.ExtendedKeyUsage; -import org.bouncycastle.asn1.x509.Extension; -import org.bouncycastle.asn1.x509.GeneralName; -import org.bouncycastle.asn1.x509.GeneralNames; -import org.bouncycastle.asn1.x509.KeyPurposeId; -import org.bouncycastle.asn1.x509.KeyUsage; -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; @@ -71,31 +31,15 @@ @ExtendWith(OutputCaptureExtension.class) class RunOwnedWorldLaunchEvidenceProviderTest { - private static final String CLAIM_DIGEST = controlledClaimDigest(); + 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), "c".repeat(64)) + 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; - static { - Security.addProvider(new BouncyCastleProvider()); - } - - private static String controlledClaimDigest() { - try { - // Exact controlled fixture bytes; this is not a physical run claim. - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest("fixture-run\nfiremud-fixture-run\n".getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException(exception); - } - } - @Test void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); @@ -105,54 +49,11 @@ void bindingDigestNormalizesAcceptedBlankOptionalOverridesToAbsent() { assertThat(evidence.bindingDigest(request(" ", " "), 1L)).isEqualTo(absent); } - @Test - void launchEvidenceBindsStartingAllocationPrivateKeysFromOwnerProjection() { - RunOwnedWorldLaunchEvidence evidence = fixtureEvidence(); - - evidence.requireMatches(request(null, null)); - assertThat(evidence.gameSessionAssociation().gameSessionTenantId()).isEqualTo(142L); - assertThat(evidence.gameSessionAssociation().gameInstanceId()).isEqualTo(1001L); - assertThat(evidence.gameSessionAssociation().currentGameInstanceStatus()) - .isEqualTo( - CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING); - assertThat(evidence.capability().tenantId()).isEqualTo(42L); - assertThat(evidence.gameSessionAssociation().gameSessionTenantId()) - .isNotEqualTo(evidence.capability().tenantId()); - assertThatThrownBy(() -> evidence.requireGameSessionAllocation(42L, 1001L)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_ALLOCATION_MISMATCH:"); - } - - @Test - void launchEvidenceConstructorRejectsMismatchedGameSessionFixtureAssociation() { - assertThatThrownBy(() -> fixtureEvidence(true)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_GAME_SESSION_FIXTURE_ASSOCIATION_MISMATCH:"); - } - - @Test - void fixtureOwnerWireResultRejectsNonStartingAllocationsBeforeWorldConsumption() { - var original = fixtureEvidence().gameSessionAssociation(); - var response = - net.firedevops.firemud.common.gamesession - .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(original); - for (var status : java.util.List.of("RUNNING", "STOPPED")) { - var changed = response.toBuilder().setCurrentGameInstanceStatus(status).build(); - assertThatThrownBy( - () -> - net.firedevops.firemud.common.gamesession - .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( - original.request(), changed)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Fixture launch association read requires the current STARTING snapshot"); - } - } - @Test void disabledFixtureFailsBeforeReadingFilesOrCallingGameDesign(CapturedOutput output) { GameDesignClient gameDesignClient = mock(GameDesignClient.class); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( false, temporaryDirectory.resolve("missing-capability.json").toString(), temporaryDirectory.resolve("missing-receipt.json").toString(), @@ -184,7 +85,7 @@ void malformedWireLogsOnlyTheFixedVerificationStageAndPreservesWireError(Capture Files.setPosixFilePermissions( receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, capability.toString(), receipt.toString(), @@ -227,7 +128,7 @@ void enabledFixtureRejectsRelativeCapabilityPathAtFileReadStage(CapturedOutput o String relativeCapabilityPath = workingDirectory.relativize(capability.toAbsolutePath().normalize()).toString(); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, relativeCapabilityPath, receipt.toString(), @@ -254,7 +155,7 @@ void enabledFixtureRejectsWritableCapabilityAtFileReadStage(CapturedOutput outpu Files.setPosixFilePermissions( receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, capability.toString(), receipt.toString(), @@ -285,7 +186,7 @@ void enabledFixtureRejectsCapabilitySymlinkAtFileReadStage(CapturedOutput output receipt, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); Files.createSymbolicLink(capability, target.getFileName()); RunOwnedWorldLaunchEvidenceProvider provider = - provider( + new RunOwnedWorldLaunchEvidenceProvider( true, capability.toString(), receipt.toString(), @@ -301,422 +202,16 @@ void enabledFixtureRejectsCapabilitySymlinkAtFileReadStage(CapturedOutput output assertFileRejectionStoppedBeforeWireParse(output); } - @Test - void fixtureOwnerReadFailureIsContentFreeAndLogsTheReadStage(CapturedOutput output) - throws Exception { - ProviderFixture fixture = providerFixture(); - GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); - CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); - when(fixtureClient.readFixture(any(), anyString())) - .thenThrow(new IllegalStateException("secret-owner-response")); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) - .hasMessage("Run-owned World launch evidence is invalid"); - } finally { - provider.closeGameSessionFixtureClient(); - } - - verify(fixtureClient) - .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); - verify(fixtureClient).close(); - assertThat(output) - .contains( - "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") - .doesNotContain("secret-owner-response", "IllegalStateException", "Caused by:"); - } - - @Test - void validFixtureOwnerReadReachesCompareAndReturnsStartingEvidence(CapturedOutput output) - throws Exception { - ProviderFixture fixture = providerFixture(); - GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); - CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); - when(fixtureClient.readFixture(any(), anyString())) - .thenAnswer(invocation -> fixture.association(invocation.getArgument(0))); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); - - RunOwnedWorldLaunchEvidence result; - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - result = provider.requireAuthenticatedEvidence(); - } finally { - provider.closeGameSessionFixtureClient(); - } - - assertThat(result.gameSessionAssociation().currentGameInstanceStatus()) - .isEqualTo( - CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING); - verify(fixtureClient) - .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); - verify(fixtureClient).close(); - assertThat(output) - .doesNotContain("Run-owned World launch evidence verification rejected", "Caused by:"); - } - - // The controlled owner-client return is valid for its alternate policy; the real common client - // rejects its different request digest before this provider comparison boundary. - @Test - void validAlternateFixtureAssociationIsRejectedAtCompareStage(CapturedOutput output) - throws Exception { - ProviderFixture fixture = providerFixture(); - GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); - CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); - RunOwnedWorldLaunchEvidence alternateFixture = - fixtureEvidence( - false, - fixture.gameSessionLeafSha256(), - fingerprint(fixture.pki().worldManagementCertificate()), - fingerprint(fixture.pki().caCertificate()), - UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6e")); - when(fixtureClient.readFixture(any(), anyString())) - .thenReturn(alternateFixture.gameSessionAssociation()); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, gameDesignClient, fixtureClient, fixture.endpoints(), fixture.tlsProperties()); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) - .hasMessage("Run-owned World launch evidence is invalid"); - } finally { - provider.closeGameSessionFixtureClient(); - } - - verify(fixtureClient) - .readFixture(any(), org.mockito.ArgumentMatchers.eq(fixture.gameSessionLeafSha256())); - verify(fixtureClient).close(); - assertThat(output) - .contains( - "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_COMPARE") - .doesNotContain( - "fixture-run", "firemud-fixture-run", "IllegalArgumentException", "Caused by:"); - } - - @Test - void fixtureClientInitializationFailureClosesPartialClient(CapturedOutput output) - throws Exception { - ProviderFixture fixture = providerFixture(); - GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); - CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); - doThrow(new IOException("private-init-detail")).when(fixtureClient).init(); - RunOwnedWorldLaunchEvidenceProvider provider = - new RunOwnedWorldLaunchEvidenceProvider( - true, - fixture.capabilityPath().toString(), - fixture.receiptPath().toString(), - "fixture-run", - "firemud-fixture-run", - fixture.tlsProperties(), - gameDesignClient, - fixture.endpoints(), - new GrpcChannelFactory(), - "dev", - (endpoints, tls, channelFactory, namespace) -> fixtureClient); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) - .hasMessage("Run-owned World launch evidence is invalid"); - } - - verify(fixtureClient).init(); - verify(fixtureClient).close(); - assertThat(output) - .contains( - "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") - .doesNotContain("private-init-detail", "IOException", "Caused by:"); - } - - @Test - void fixtureClientMissingConfigurationFailsAtReadStageWithoutCreatingClient(CapturedOutput output) - throws Exception { - ProviderFixture fixture = providerFixture(); - GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); - RunOwnedWorldLaunchEvidenceProvider provider = - provider(fixture, gameDesignClient, null, null, fixture.tlsProperties(), factory); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException.class) - .hasMessage("Run-owned World launch evidence is invalid"); - } - - verifyNoInteractions(factory); - assertThat(output) - .contains( - "Run-owned World launch evidence verification rejected; stage=GAME_SESSION_FIXTURE_READ") - .doesNotContain("fixture-run", "firemud-fixture-run"); - } - - @Test - void blankWorkloadNamespaceFailsBeforeCreatingFixtureClient() throws Exception { - ProviderFixture fixture = providerFixture(); - for (String namespace : new String[] {null, "", " "}) { - GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, - gameDesignClient, - null, - fixture.endpoints(), - fixture.tlsProperties(), - factory, - namespace); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - assertThatThrownBy(provider::requireAuthenticatedEvidence) - .isInstanceOf( - RunOwnedWorldLaunchEvidenceProvider.InvalidRunOwnedWorldLaunchEvidenceException - .class) - .hasMessage("Run-owned World launch evidence is invalid"); - } - - verifyNoInteractions(factory); - } - } - - @Test - void configuredWorkloadNamespaceIsPassedToFixtureClientFactory() throws Exception { - ProviderFixture fixture = providerFixture(); - GameDesignClient gameDesignClient = mockDescriptorReader(fixture.evidence()); - CanonicalGameInstanceLaunchAssociationClient fixtureClient = mock(); - when(fixtureClient.readFixture(any(), anyString())) - .thenAnswer(invocation -> fixture.association(invocation.getArgument(0))); - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory = mock(); - when(factory.create(any(), any(), any(), anyString())).thenReturn(fixtureClient); - RunOwnedWorldLaunchEvidenceProvider provider = - provider( - fixture, - gameDesignClient, - fixtureClient, - fixture.endpoints(), - fixture.tlsProperties(), - factory, - "dev"); - - try (PeerContext ignored = fixture.attachGameSessionPeer()) { - provider.requireAuthenticatedEvidence(); - } finally { - provider.closeGameSessionFixtureClient(); - } - - verify(factory).create(any(), any(), any(), eq("dev")); - } - private static void assertFileRejectionStoppedBeforeWireParse(CapturedOutput output) { assertThat(output) .contains("Run-owned World launch evidence verification rejected; stage=CAPABILITY_FILE") .doesNotContain("stage=WIRE_PARSE"); } - private RunOwnedWorldLaunchEvidenceProvider provider( - ProviderFixture fixture, - GameDesignClient gameDesignClient, - CanonicalGameInstanceLaunchAssociationClient fixtureClient, - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProperties) { - return provider( - fixture, - gameDesignClient, - fixtureClient, - endpoints, - tlsProperties, - (ignoredEndpoints, ignoredTls, ignoredChannelFactory, ignoredNamespace) -> fixtureClient); - } - - private RunOwnedWorldLaunchEvidenceProvider provider( - ProviderFixture fixture, - GameDesignClient gameDesignClient, - CanonicalGameInstanceLaunchAssociationClient fixtureClient, - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProperties, - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory) { - return provider( - fixture, gameDesignClient, fixtureClient, endpoints, tlsProperties, factory, "dev"); - } - - private RunOwnedWorldLaunchEvidenceProvider provider( - ProviderFixture fixture, - GameDesignClient gameDesignClient, - CanonicalGameInstanceLaunchAssociationClient fixtureClient, - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tlsProperties, - RunOwnedWorldLaunchEvidenceProvider.GameSessionFixtureClientFactory factory, - String namespace) { - return new RunOwnedWorldLaunchEvidenceProvider( - true, - fixture.capabilityPath().toString(), - fixture.receiptPath().toString(), - "fixture-run", - "firemud-fixture-run", - tlsProperties, - gameDesignClient, - endpoints, - new GrpcChannelFactory(), - namespace, - factory); - } - - private ProviderFixture providerFixture() throws Exception { - Path directory = - Files.createDirectories(temporaryDirectory.resolve("provider-" + UUID.randomUUID())); - TestPki pki = TestPki.create(); - String gameSessionLeaf = fingerprint(pki.gameSessionCertificate()); - String worldManagementLeaf = fingerprint(pki.worldManagementCertificate()); - String caFingerprint = fingerprint(pki.caCertificate()); - RunOwnedWorldLaunchEvidence evidence = - fixtureEvidence(false, gameSessionLeaf, worldManagementLeaf, caFingerprint); - Path capability = directory.resolve("capability.json"); - Path receipt = directory.resolve("receipt.json"); - Files.writeString(capability, capabilityJson(evidence.capability()), StandardCharsets.UTF_8); - Files.writeString(receipt, receiptJson(evidence.sourceReceipt()), StandardCharsets.UTF_8); - Set immutablePermissions = - Set.of( - PosixFilePermission.OWNER_READ, - PosixFilePermission.GROUP_READ, - PosixFilePermission.OTHERS_READ); - Files.setPosixFilePermissions(capability, immutablePermissions); - Files.setPosixFilePermissions(receipt, immutablePermissions); - Path worldCertificate = directory.resolve("world-management.crt"); - Path caCertificate = directory.resolve("ca.crt"); - Files.writeString( - worldCertificate, pem(pki.worldManagementCertificate()), StandardCharsets.UTF_8); - Files.writeString(caCertificate, pem(pki.caCertificate()), StandardCharsets.UTF_8); - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setCertChain(worldCertificate.toString()); - tls.setCaCert(caCertificate.toString()); - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - endpoints.setGameSessionService("localhost:6565"); - return new ProviderFixture(evidence, capability, receipt, pki, tls, endpoints, gameSessionLeaf); - } - - private static GameDesignClient mockDescriptorReader(RunOwnedWorldLaunchEvidence evidence) { - GameDesignClient client = mock(GameDesignClient.class); - var message = - net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec - .toLaunchDescriptorMessage(evidence.launchDescriptor()); - when(client.getLaunchDescriptor(any())) - .thenReturn(new LaunchDescriptorReadback(message, evidence.launchDescriptor())); - return client; - } - - private static String capabilityJson( - RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { - return """ - {"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"}%n\ - """ - .formatted( - 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 String receiptJson( - RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt receipt) { - var source = receipt.sourceEvidence(); - var creation = receipt.creationEvidence(); - var launch = receipt.launchReadEvidence(); - var seal = receipt.fixturePolicySeal(); - 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"},"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"}}%n\ - """ - .formatted( - receipt.schema(), - receipt.runId(), - receipt.composeProjectName(), - receipt.fixtureOperationId(), - receipt.ownerService(), - receipt.gameSessionUriSan(), - receipt.gameSessionLeafSha256(), - receipt.caCertificateSha256(), - receipt.worldManagementUriSan(), - receipt.worldManagementLeafSha256(), - 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(), - launch.schema(), - launch.gameTemplateId(), - base64(launch.publishedReleaseBundle().toByteArray()), - base64(launch.versionAssetArtifactState().toByteArray()), - base64(launch.versionState().toByteArray()), - base64(launch.launchDescriptor().toByteArray()), - creation.schemaVersion(), - creation.targetNamespace(), - creation.creationRequestId(), - creation.operationId(), - creation.requestDigest(), - creation.canonicalTenantId(), - creation.sourceGameRowId(), - creation.sourceGameTenantKey(), - creation.provenanceKind(), - creation.evidenceDigest(), - seal.schema(), - seal.ownerService(), - seal.operationId(), - seal.requestDigest(), - seal.evidenceDigest()); - } - - private static String base64(byte[] value) { - return Base64.getEncoder().encodeToString(value); - } - - private static String pem(X509Certificate certificate) throws Exception { - return "-----BEGIN CERTIFICATE-----\n" - + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(certificate.getEncoded()) - + "\n-----END CERTIFICATE-----\n"; - } - - private static String fingerprint(X509Certificate certificate) throws Exception { - return HexFormat.of() - .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); - } - private static PreparedWorldInstanceRequest request(String patch, String remap) { return new PreparedWorldInstanceRequest( - 142L, - 1001L, + 42L, + 101L, 17L, OPERATION_ID, "launch-descriptor-fixture-11", @@ -731,42 +226,9 @@ private static PreparedWorldInstanceRequest request(String patch, String remap) } private static RunOwnedWorldLaunchEvidence fixtureEvidence() { - return fixtureEvidence(false); - } - - private static RunOwnedWorldLaunchEvidence fixtureEvidence(boolean mismatchedSeal) { - return fixtureEvidence(mismatchedSeal, "a".repeat(64), "b".repeat(64), "c".repeat(64)); - } - - private static RunOwnedWorldLaunchEvidence fixtureEvidence( - boolean mismatchedSeal, - String gameSessionLeafSha256, - String worldManagementLeafSha256, - String caCertificateSha256) { - return fixtureEvidence( - mismatchedSeal, - gameSessionLeafSha256, - worldManagementLeafSha256, - caCertificateSha256, - UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d")); - } - - private static RunOwnedWorldLaunchEvidence fixtureEvidence( - boolean mismatchedSeal, - String gameSessionLeafSha256, - String worldManagementLeafSha256, - String caCertificateSha256, - UUID canonicalTenantId) { - String operationId = - RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( - CLAIM_DIGEST, - "fixture-run", - "firemud-fixture-run", - gameSessionLeafSha256, - caCertificateSha256) - .toString(); - UUID registrationId = UUID.fromString(operationId); + UUID registrationId = UUID.fromString(OPERATION_ID); UUID sourceOperationId = UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); + UUID canonicalTenantId = UUID.fromString("ed5d1541-a33e-4f8b-9b54-38c27d76ba6d"); String requestDigest = AuthoredWorldSourceDigest.requestDigest( "dev", registrationId, canonicalTenantId, "fixture-tenant", "demo", "Demo World"); @@ -801,7 +263,7 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence( var descriptorRequest = new AuthoredWorldLaunchDescriptorEvidence.Request( "dev", - operationId, + OPERATION_ID, canonicalTenantId, "demo", sourceOperationId, @@ -855,19 +317,19 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence( VersionStateSnapshot.newBuilder() .setTenantId("42") .setVersionId(11L) + .setUpdatedAt("2026-10-15T03:00:00") .setVersionState(VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED) .setVersionStateEpoch(77L) - .setUpdatedAt("2026-10-11T10:00:00Z") .build(); RunOwnedInitialAdmissionFixtureWireCodec.Capability capability = new RunOwnedInitialAdmissionFixtureWireCodec.Capability( RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, "fixture-run", "firemud-fixture-run", - operationId, + OPERATION_ID, 42L, 17L, - 1L, + 9L, "demo", "Demo World", "production", @@ -877,20 +339,19 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence( false, "SHARED", "ALLOW_NEW", - gameSessionLeafSha256, + "a".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - caCertificateSha256, + "b".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - worldManagementLeafSha256, + "c".repeat(64), CLAIM_DIGEST); - // Controlled constructor data remains untrusted; these commitments do not prove owner writes. - UUID creationRequestId = UUID.fromString("1b3fdbda-a9f6-4cf5-b21e-b43f0e855f65"); - UUID creationOperationId = UUID.fromString("31e36104-3336-4cf5-899a-cb419f2f361e"); + UUID creationRequestId = UUID.fromString(OPERATION_ID); + UUID creationOperationId = UUID.fromString("b2af0092-07d6-433b-93ae-21120d88dd51"); String creationRequestDigest = - GameTenantCreationDigest.requestDigest( - "dev", creationRequestId, "42", "Fixture Game", null); + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.requestDigest( + "dev", creationRequestId, "42", "Demo World", null); var creation = - new FreshTenantCreationEvidence( + new net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence( 1, "dev", creationRequestId, @@ -900,7 +361,7 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence( 29L, "42", "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( + net.firedevops.firemud.common.tenant.GameTenantCreationDigest.evidenceDigest( "dev", creationRequestId, creationOperationId, @@ -921,229 +382,39 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence( String policyRequestDigest = RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( capability, creation, source, launchRead); - var policySeal = + var seal = new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, - UUID.fromString(operationId), + UUID.fromString(OPERATION_ID), policyRequestDigest, RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - UUID.fromString(operationId), policyRequestDigest)); - UUID otherSealOperation = UUID.fromString("20000000-0000-4000-8000-000000000012"); - var receiptSeal = - mismatchedSeal - ? new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( - policySeal.schema(), - policySeal.ownerService(), - otherSealOperation, - policySeal.requestDigest(), - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - otherSealOperation, policySeal.requestDigest())) - : policySeal; + UUID.fromString(OPERATION_ID), policyRequestDigest)); var receipt = new RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt( RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_SCHEMA, "fixture-run", "firemud-fixture-run", - operationId, + OPERATION_ID, RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_RECEIPT_OWNER_SERVICE, RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - gameSessionLeafSha256, - caCertificateSha256, + "a".repeat(64), + "b".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - worldManagementLeafSha256, + "c".repeat(64), source, launchRead, creation, - receiptSeal); - var policyRequestBytes = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( - capability, creation, source, launchRead); - UUID readRequestId = UUID.fromString("5d85bfbe-ae28-4a86-a72a-57471a5761bf"); - var associationRequest = - new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest( - readRequestId, "dev", UUID.fromString(operationId), policySeal.evidenceDigest()); - var association = - new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( - associationRequest, - 142L, - 1001L, - canonicalTenantId, - UUID.fromString("20000000-0000-4000-8000-000000000011"), - UUID.fromString(bundle.getCanonicalVersionId()), - UUID.fromString("30000000-0000-4000-8000-000000000011"), - UUID.fromString("40000000-0000-4000-8000-000000000011"), - 1L, - CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus.STARTING, - 0L, - policyRequestBytes, - policySeal); + seal); return new RunOwnedWorldLaunchEvidence( capability, receipt, descriptor, new byte[] {1}, new byte[] {2}, - gameSessionLeafSha256, + "a".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN, - worldManagementLeafSha256, - caCertificateSha256, - association); - } - - private static RunOwnedWorldLaunchEvidenceProvider provider( - boolean enabled, - String capabilityPath, - String receiptPath, - String runId, - String composeProjectName, - CommonGrpcClientProperties grpcProperties, - GameDesignClient gameDesignClient) { - return new RunOwnedWorldLaunchEvidenceProvider( - enabled, - capabilityPath, - receiptPath, - runId, - composeProjectName, - grpcProperties, - gameDesignClient, - null, - null, - "dev"); - } - - private record ProviderFixture( - RunOwnedWorldLaunchEvidence evidence, - Path capabilityPath, - Path receiptPath, - TestPki pki, - CommonGrpcClientProperties tlsProperties, - ServiceEndpointsProperties endpoints, - String gameSessionLeafSha256) { - private CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult association( - CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureRequest request) { - var original = evidence.gameSessionAssociation(); - return new CanonicalGameInstanceLaunchAssociationReadEvidence.FixtureResult( - request, - original.gameSessionTenantId(), - original.gameInstanceId(), - original.canonicalTenantId(), - original.gameInstanceUuid(), - original.canonicalVersionId(), - original.canonicalRealmId(), - original.playableStateNamespaceId(), - original.catalogRevision(), - original.currentGameInstanceStatus(), - original.currentRowVersion(), - original.fixturePolicyRequestBytes(), - original.fixturePolicySeal()); - } - - private PeerContext attachGameSessionPeer() throws Exception { - Context context = - Context.current() - .withValue( - GrpcPeerIdentity.CONTEXT_KEY, - new GrpcPeerIdentity( - RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, - "dev", - "game-session-service")) - .withValue( - GrpcPeerCertificateEvidence.CONTEXT_KEY, - GrpcPeerCertificateEvidence.fromCertificate(pki.gameSessionCertificate()) - .orElseThrow()); - return new PeerContext(context.attach()); - } - } - - private record PeerContext(io.grpc.Context previous) implements AutoCloseable { - @Override - public void close() { - Context.current().detach(previous); - } - } - - private record TestPki( - X509Certificate caCertificate, - X509Certificate worldManagementCertificate, - X509Certificate gameSessionCertificate) { - private static TestPki create() throws Exception { - KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); - generator.initialize(2048); - KeyPair caKey = generator.generateKeyPair(); - X500Name caName = new X500Name("CN=World provider test CA"); - X509Certificate ca = issueCertificate(caName, caKey.getPublic(), caName, caKey, true, null); - X509Certificate world = - issueLeaf( - caName, - caKey, - generator, - "world-management-service", - RunOwnedInitialAdmissionFixtureWireCodec.WORLD_MANAGEMENT_URI_SAN); - X509Certificate gameSession = - issueLeaf( - caName, - caKey, - generator, - "game-session-service", - RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN); - return new TestPki(ca, world, gameSession); - } - - private static X509Certificate issueLeaf( - X500Name caName, - KeyPair caKey, - KeyPairGenerator generator, - String service, - String workloadUri) - throws Exception { - KeyPair leafKey = generator.generateKeyPair(); - GeneralNames names = - new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, workloadUri)); - return issueCertificate( - new X500Name("CN=" + service), leafKey.getPublic(), caName, caKey, false, names); - } - - private static X509Certificate issueCertificate( - X500Name subject, - java.security.PublicKey publicKey, - X500Name issuer, - KeyPair issuerKey, - boolean ca, - GeneralNames subjectAltNames) - throws Exception { - Instant now = Instant.now().minusSeconds(60); - JcaX509v3CertificateBuilder builder = - new JcaX509v3CertificateBuilder( - issuer, - BigInteger.valueOf(Math.abs(UUID.randomUUID().getMostSignificantBits()) + 1L), - Date.from(now), - Date.from(now.plusSeconds(86400L)), - subject, - publicKey); - builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(ca)); - if (ca) { - builder.addExtension( - Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); - } else { - builder.addExtension( - Extension.keyUsage, - true, - new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); - builder.addExtension( - Extension.extendedKeyUsage, - false, - new ExtendedKeyUsage( - new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); - builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); - } - return new JcaX509CertificateConverter() - .setProvider(BouncyCastleProvider.PROVIDER_NAME) - .getCertificate( - builder.build( - new JcaContentSignerBuilder("SHA256withRSA") - .setProvider(BouncyCastleProvider.PROVIDER_NAME) - .build(issuerKey.getPrivate()))); - } + "c".repeat(64), + "b".repeat(64)); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java index dee68973b3..c7b61de93d 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java @@ -7,7 +7,6 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.List; @@ -26,7 +25,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.DefaultApplicationArguments; -import org.springframework.test.util.ReflectionTestUtils; class TestDataSeederTest { @Mock RegionRepository regionRepository; @@ -109,14 +107,6 @@ void runSeedsCanonicalTopologyWhenMissing() throws Exception { assertEquals(1021L, exitCaptor.getAllValues().get(1).getToRoom().getId()); } - @Test - void fixtureModeSkipsSeedingWithoutPreventingStartupOrAccessingRepositories() { - ReflectionTestUtils.setField(seeder, "runOwnedFixtureMode", true); - - seeder.run(new DefaultApplicationArguments(new String[] {})); - verifyNoInteractions(regionRepository, zoneRepository, roomRepository, roomExitRepository); - } - @Test void runReassertsCanonicalTopologyWhenRowsAlreadyExist() throws Exception { Region existingRegion = new Region(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 99182918b5..9f66c370a0 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -9,6 +9,7 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -31,8 +32,10 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidence; import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldLaunchEvidenceProvider; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; +import net.firedevops.firemud.worldmanagement.entity.RegionInstance; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; import net.firedevops.firemud.worldmanagement.entity.RoomInstance; @@ -749,52 +752,241 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { } @Test - void fixturePrepareRefusesBeforeProviderEvidenceOrRepositoryInteraction() { + void fixturePrepareBindsOriginalPreparingEpochAndExactRetryDoesNotRepeatMaterialization() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("a".repeat(64)); + AtomicReference persisted = new AtomicReference<>(); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setId(101L); + persisted.set(copyWorldInstance(submitted)); + return submitted; + }); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + PreparedWorldInstanceRequest request = ordinaryPreparedRequest(); + + var prepared = fixtureService.prepareWorldInstance(request); + + assertEquals("PREPARING", prepared.status()); + assertEquals(1L, prepared.lifecycleEpoch()); + assertEquals("a".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); + verify(evidence).requireMatches(request); + verify(worldInstanceRepository).lockRunOwnedFixtureOperation(42L, "cp-1"); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + verify(gameDesignClient, never()).getVersionAssetArtifactState(42L, 11L); + verify(gameDesignClient, never()).getVersionState(42L, 11L); + + var retry = fixtureService.prepareWorldInstance(request); + + assertEquals(prepared, retry); + persisted.get().setStatus("ACTIVE"); + persisted.get().setLifecycleEpoch(2L); + + var activeReplay = fixtureService.prepareWorldInstance(request); + + assertEquals("ACTIVE", activeReplay.status()); + assertEquals(2L, activeReplay.lifecycleEpoch()); + assertEquals("a".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + assertEquals(1L, persisted.get().getRunOwnedFixturePreparingLifecycleEpoch()); + verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); + verify(regionInstanceRepository, org.mockito.Mockito.times(1)).save(any(RegionInstance.class)); + verify(roomInstanceRepository, org.mockito.Mockito.times(1)).save(any(RoomInstance.class)); + verify(evidence, org.mockito.Mockito.times(3)).requireMatches(request); + } + + @Test + void fixturePrepareRejectsChangedBindingForExistingActiveRow() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("d".repeat(64)); + WorldInstance active = boundFixtureInstance("ACTIVE", 2L); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenReturn(Optional.of(active)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(active)); IllegalArgumentException error = assertThrows( IllegalArgumentException.class, - () -> fixtureService.prepareWorldInstance(ordinaryPreparedRequest())); + () -> fixtureService(provider).prepareWorldInstance(ordinaryPreparedRequest())); - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); - verify(provider).isEnabled(); - verify(provider, never()).requireAuthenticatedEvidence(); - verifyNoWorldRepositoryOrOwnerInteraction(); + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); } @Test - void fixtureActivationRefusesBeforeWorldReadOrProviderEvidence() { + void fixtureOperationCannotBeAssignedToASecondWorldInstance() { RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); - WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("b".repeat(64)); + WorldInstance operationInstance = new WorldInstance(); + operationInstance.setGameInstanceId(101L); + when(worldInstanceRepository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( + 42L, "cp-1")) + .thenReturn(Optional.of(operationInstance)); IllegalArgumentException error = assertThrows( IllegalArgumentException.class, - () -> fixtureService.activatePreparedWorldInstance(42L, 101L, 1L)); + () -> + fixtureService(provider) + .prepareWorldInstance( + new PreparedWorldInstanceRequest( + 42L, + 202L, + 7L, + "cp-1", + "ld-1", + 11L, + null, + "{}", + "genrev-11", + 77L, + PUBLISHED_RELEASE_BUNDLE_REF, + 77L))); + + assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + } + + @Test + void fixtureActivationVerifiesBindingThenAllowsOnlyOriginalEpochActiveReplayWithoutWrite() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance preparing = boundFixtureInstance("PREPARING", 1L); + AtomicReference persisted = new AtomicReference<>(copyWorldInstance(preparing)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer( + invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setRowVersion(submitted.getRowVersion() + 1L); + persisted.set(copyWorldInstance(submitted)); + return copyWorldInstance(submitted); + }); + WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + + var active = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); + assertEquals("ACTIVE", active.status()); + assertEquals(2L, active.lifecycleEpoch()); + assertEquals("c".repeat(64), persisted.get().getRunOwnedFixtureBindingSha256()); + + var replay = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); + assertEquals(active, replay); + verify(worldInstanceRepository, org.mockito.Mockito.times(1)).save(any(WorldInstance.class)); + verify(provider, org.mockito.Mockito.times(2)).requireAuthenticatedEvidence(); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); + + var inOrder = inOrder(provider, worldInstanceRepository); + inOrder.verify(provider).requireAuthenticatedEvidence(); + inOrder.verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); + inOrder.verify(provider).requireAuthenticatedEvidence(); + inOrder.verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); + } + + @Test + void configuredFixtureRejectsUnboundExistingRowsAndStaleActiveReplayEpoch() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldInstance unbound = activeWorldInstance(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(unbound)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(unbound)); + + IllegalArgumentException unboundError = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 2L)); + assertTrue(unboundError.getMessage().startsWith("RUN_OWNED_WORLD_LAUNCH_IDENTITY_CONFLICT:")); + verify(gameDesignClient, never()).getPublishedReleaseBundle(42L, 11L); - assertTrue(error.getMessage().startsWith("RUN_OWNED_WORLD_MATERIALIZATION_UNAVAILABLE:")); - verify(provider).isEnabled(); - verify(provider, never()).requireAuthenticatedEvidence(); - verifyNoWorldRepositoryOrOwnerInteraction(); + WorldInstance active = boundFixtureInstance("ACTIVE", 2L); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(active)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(active)); + IllegalArgumentException stale = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService(provider).activatePreparedWorldInstance(42L, 101L, 0L)); + assertTrue(stale.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); } - private void verifyNoWorldRepositoryOrOwnerInteraction() { - org.mockito.Mockito.verifyNoInteractions( - worldInstanceRepository, - regionInstanceRepository, - zoneRepository, - zoneInstanceRepository, - roomRepository, - roomExitRepository, - roomInstanceRepository, - roomInstanceExitRepository, - worldEventRepository, - gameDesignClient, - entityManagementClient); + @Test + void fixtureActivationRejectsOriginalEpochForNonActiveRowsWithoutWrites() { + RunOwnedWorldLaunchEvidenceProvider provider = mock(RunOwnedWorldLaunchEvidenceProvider.class); + RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); + when(provider.isEnabled()).thenReturn(true); + when(provider.requireAuthenticatedEvidence()).thenReturn(evidence); + when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) + .thenReturn("c".repeat(64)); + WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); + AtomicReference currentRow = new AtomicReference<>(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenAnswer(invocation -> Optional.of(currentRow.get())); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer(invocation -> Optional.of(currentRow.get())); + + String[] statuses = {"FAILED_PRE_ACTIVATION", "TERMINATING", "TERMINATED"}; + long[] lifecycleEpochs = {2L, 3L, 4L}; + for (int index = 0; index < statuses.length; index++) { + WorldInstance row = boundFixtureInstance(statuses[index], lifecycleEpochs[index]); + currentRow.set(row); + + IllegalArgumentException stale = + assertThrows( + IllegalArgumentException.class, + () -> fixtureService.activatePreparedWorldInstance(42L, 101L, 1L)); + + assertTrue(stale.getMessage().startsWith("WORLD_INSTANCE_LIFECYCLE_STALE:")); + assertEquals(statuses[index], row.getStatus()); + assertEquals(lifecycleEpochs[index], row.getLifecycleEpoch()); + } + + verify(worldInstanceRepository, never()).save(any(WorldInstance.class)); + verify(regionInstanceRepository, never()).save(any()); + verify(zoneInstanceRepository, never()).save(any()); + verify(roomInstanceRepository, never()).save(any()); + verify(roomInstanceExitRepository, never()).save(any()); + verify(worldEventRepository, never()).save(any()); + verify(regionInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(zoneInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(roomInstanceRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(roomInstanceExitRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(worldEventRepository, never()).deleteByTenantIdAndGameInstanceId(42L, 101L); } private WorldLifecycleCommandServiceImpl fixtureService( @@ -838,6 +1030,15 @@ private static PreparedWorldInstanceRequest ordinaryPreparedRequest() { 77L); } + private WorldInstance boundFixtureInstance(String status, long lifecycleEpoch) { + WorldInstance instance = activeWorldInstance(); + instance.setLifecycleEpoch(lifecycleEpoch); + instance.setStatus(status); + instance.setRunOwnedFixtureBindingSha256("c".repeat(64)); + instance.setRunOwnedFixturePreparingLifecycleEpoch(1L); + return instance; + } + private WorldInstance activeWorldInstance() { WorldInstance instance = new WorldInstance(); instance.setId(101L); From 49684e4680bc9dc47151c902f8c48e9f2aac567b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:56:54 +1300 Subject: [PATCH 22/26] Align fixture source proof status with completed bootstrap checks --- .../game-session-runtime-and-tick-coordination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 770fa6cd7e..3077fe9ba5 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 @@ -20,7 +20,7 @@ The migration-preservation correction restores the exact original V1005/V1006 Gi 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. -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 `GameSessionFixtureLaunchAssociationReadGrpcServiceTest` sources have not been run. 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. Fresh packaged `PLAY`/`LOOK` remains unqualified for the current candidate, as described above. 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. From f98e2e6309a2d771286ba7743a1bbb73c10c4c24 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:00:22 +1300 Subject: [PATCH 23/26] Align World runtime limitation with source-first staging --- .../microservices/world-management-service/runtime-and-data.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 94675a4035..67b9ec31a9 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -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 prepared run-owned fixture provider independently authenticates the Game Design descriptor and canonical Game Session `STARTING` allocation as source capability; no current production lifecycle caller invokes those reads. World fixture bootstrap skips seeding and prepare/activate refuse before repository effects pending actual World source/Version materialization, association, fixed-preset preparation and holds. Retained fixture binding/epoch columns and passive repository readback do not establish lifecycle authority. The complete target ordering and replay contract remain in [Testing Strategy](../../system-architecture-testing.md#run-owned-v1-launch-read-evidence); candidate-specific implementation and proof limits are in [the World runtime tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md#canonical-fixture-launch-receiving-boundary). +- 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 From ba24cde401464373f0b1cecf074367d167f85dc3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:46:51 +1300 Subject: [PATCH 24/26] fix: serialize canonical launch capture before pin locks --- .../game-session-service/api-contracts.md | 6 +- ...meInstanceLaunchAssociationRepository.java | 2 +- ...tingInstanceRepositoryIntegrationTest.java | 116 ++++++++++++++++++ 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 9173fcfd48..a68182fbdd 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -8,11 +8,11 @@ Target state makes Game Session the authoritative owner of region/tick coordinat ## Implementation Status -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. No World materialization/activation, canonical first-`OPEN`, or admission result is established. +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, and the retained published bootstrap does not establish completion of that phase or a completed admission. Generic `StartSession` cannot construct the verified fixture carrier, and this stage grants no Human activation or production Game Design release-read permission. +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). @@ -68,7 +68,7 @@ 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 run-owned Compose coordinator currently completes only canonical `STARTING` launch preparation and its independent owner readback under the existing default-off fixture configuration. The later World materialization, activation, initial-bind intent, hold and first-`OPEN` phases remain unavailable. Fixture bootstrap refuses those phases before effects and returns no completed admission. 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). +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. 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 827ca3963c..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 @@ -88,6 +88,7 @@ public CanonicalGameInstanceLaunchAssociation capture( || 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); @@ -95,7 +96,6 @@ public CanonicalGameInstanceLaunchAssociation capture( 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); 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 6b89f1f367..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,9 +4,12 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; +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; @@ -18,6 +21,7 @@ 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; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; @@ -275,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, @@ -390,6 +504,7 @@ private static UUID uuid(int value) { private record Fixture( DSLContext dsl, + DriverManagerDataSource dataSource, TransactionTemplate transactions, GameSessionAuthoredWorldSourceRepository sourceRepository, GameSessionFreshTenantAssociationRepository tenantAssociationRepository, @@ -497,6 +612,7 @@ private static Fixture fixture(boolean createRealm) { dsl, transactions, ORIGINAL_TUPLE, source.source(), publishedSet, binding); return new Fixture( dsl, + dataSource, transactions, sourceRepository, tenantAssociationRepository, From 9751159e084cd74f8ae433e2daff445fd514aa5e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:43:03 +1300 Subject: [PATCH 25/26] Fix canonical tenant conflict and qualify exact peer review boundaries --- .../world-management-service/api-contracts.md | 4 +- ...e-session-runtime-and-tick-coordination.md | 8 +- .../world-runtime-and-movement.md | 2 +- ...ServerPeerIdentityCallCredentialsTest.java | 102 +++++++++++++++++ ...ssionFreshTenantAssociationRepository.java | 5 + ...tAssociationRepositoryIntegrationTest.java | 105 ++++++++++++++++++ ...ratorAttemptRepositoryIntegrationTest.java | 23 +--- ...edCanonicalLaunchPreparationOwnerTest.java | 1 + 8 files changed, 222 insertions(+), 28 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityCallCredentialsTest.java diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 2599359007..2a1d03f7ea 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -275,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. -The retained 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. The current run-owned coordinator completes Game Session STARTING allocation and readback only; it does not acquire a World hold or authorize the first admission pointer. 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. +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. @@ -285,7 +285,7 @@ Operator procedure: use the scoped World reconciliation log fields to identify t 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). -Current fixture bootstrap skips runtime seeding; prepare and activate refuse before repository effects because World-owned materialization remains unavailable. The provider’s bounded descriptor and authenticated Game Session read exist as source capability, with controlled proof, but no current production lifecycle caller invokes them. 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). +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/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 3077fe9ba5..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 @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick 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. This proves the retained bootstrap composition; canonical player-flow closure remains open. Earlier failed receipt-constructor, operation-ID and test-format gates remain recorded separately. +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). @@ -38,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: 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. The fixture coordinator completes only canonical `STARTING` allocation/readback; materialization, activation, holds 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. +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). @@ -71,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, 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 new tests are unrun and 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); they are unrun for this candidate and do not establish scheduled canonical preparation. 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.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. | @@ -214,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 prepares an opt-in canonical STARTING allocation with exact replay/readback; its later World and first OPEN phases remain unavailable, 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). +- 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 b731371e67..a6f6016ec4 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -149,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 current run-owned Compose coordinator completes canonical Game Session STARTING allocation/readback only. World fixture bootstrap, prepare and activate remain unavailable before effects; materialization, activation, holds and first OPEN are explicit gaps. Earlier coordinator/hold implementation and proof are historical. 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) and [focused integration proof](../../../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/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/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 079d31b3cc..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 @@ -601,6 +601,11 @@ private void rejectOrphanOrRetainedClaim(FreshTenantCreationEvidence evidence) { 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," 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 3cbc7a7891..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 @@ -335,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(); @@ -479,6 +571,19 @@ private static FreshTenantCreationEvidence creationEvidence( 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(), 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 8106cad084..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 @@ -4,14 +4,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; @@ -455,7 +451,7 @@ private static void seedV34_3SourceAndCatalog( private static String v34_3CatalogRequestDigest( CreateCanonicalRealmCatalogRequest request, IntakeReceipt sourceReceipt) { AuthoredWorldSourceEvidence source = sourceReceipt.source(); - return v34_3Digest( + return CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( "game-session-canonical-realm-catalog-request/v1", "1", request.requestId().toString(), @@ -494,7 +490,7 @@ private static String v34_3CatalogReceiptDigest( UUID namespaceId, long revision, String requestDigest) { - return v34_3Digest( + return CanonicalHumanPublicationOwnerTestFixtures.historicalDigest( "game-session-canonical-realm-catalog-receipt/v1", "1", request.targetNamespace(), @@ -508,21 +504,6 @@ private static String v34_3CatalogReceiptDigest( sourceReceipt.receiptDigest()); } - private static String v34_3Digest(String... values) { - try { - MessageDigest hash = MessageDigest.getInstance("SHA-256"); - for (String value : values) { - 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:" + HexFormat.of().formatHex(hash.digest()); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } - private static void seedV34_3TenantAssociation(DSLContext tx, PriorRuntime target) { tx.execute( "INSERT INTO game_session_tenant_scope_reservation" 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 index 747018299e..7e4d15a63e 100644 --- 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 @@ -294,6 +294,7 @@ void fixedEvidenceReadRequiresTheExactWorldPeerAndRetainedWorldLeafBeforeDecodin assertThatThrownBy(fixture.coordinator::loadFixedVerifiedEvidenceForWorldPeer) .isInstanceOf(AdminAuthorizationException.class); + when(certificate.leafSha256()).thenReturn(fixture.capability.worldManagementLeafSha256()); Context wrongWorldContext = Context.current() .withValue( From e5ef94600f04195a7792e3d4fcbb4481b8aa21df Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:23:35 +1300 Subject: [PATCH 26/26] Clarify fixture baseline proof and historical test preconditions --- .../implementation-tracking/world-runtime-and-movement.md | 4 ++-- ...ssionCanonicalLaunchPreparationServiceIntegrationTest.java | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) 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 a6f6016ec4..32689f5585 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for world runtime and movement. C ### 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`; original-capability teardown removed the claimed project containers, network and volumes. These packaged results qualify the retained bootstrap, while canonical owner-chain closure remains open. +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. @@ -58,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 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. 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; the retained bootstrap has separate qualified runtime proof. 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.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. | 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 9f477cc5e0..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 @@ -954,6 +954,10 @@ private record Fixture( 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,