From 2f2572a7f352615f56d0f81656699f90b543903b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:29:13 +1300 Subject: [PATCH 01/34] Define non-admitting canonical Entity roster wire contract --- .../v1/entity_management_service.proto | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 3bc971bcde..3996021eff 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -36,6 +36,86 @@ service EntityManagementService { returns (ValidateEntityUpgradeMappingsResponse); } +// Canonical gameplay roster discovery is a separate non-admitting boundary. This wire contract +// does not authorize the legacy numeric ListCharactersByAccount RPC for canonical gameplay. +service CanonicalGameplayRosterService { + rpc ListPreseededRoster(CanonicalGameplayRosterRequest) + returns (CanonicalGameplayRosterResponse); + rpc ReadSelectedPreseededAssignment(CanonicalGameplayRosterSelectedAssignmentRequest) + returns (CanonicalGameplayRosterSelectedAssignmentResponse); +} + +message CanonicalGameplayRosterRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + CanonicalGameplayRosterTarget expected_target = 3; +} + +message CanonicalGameplayRosterTarget { + string tenant_uuid = 1; + string realm_uuid = 2; + string world_slug = 3; + string realm_slug = 4; + string game_instance_uuid = 5; + int64 catalog_revision = 6; + reserved 7, 8; + string published_policy_digest = 9; + string published_release_bundle_ref = 10; + string admission_pointer_snapshot_digest = 11; + string published_owner_proof_digest = 12; + string playable_state_namespace_uuid = 13; + PlayableStateScope playable_state_scope = 14; + CanonicalGameplayRosterEntryPolicy entry_policy = 15; + string canonical_version_uuid = 16; + // Exact positive counters observed from the current owning Game Session target. + int64 pointer_version = 17; + int64 active_world_epoch = 18; +} + +enum CanonicalGameplayRosterEntryPolicy { + CANONICAL_ROSTER_ENTRY_POLICY_UNSPECIFIED = 0; + CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED = 1; + CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY = 2; + CANONICAL_ROSTER_ENTRY_POLICY_AUTO_PROVISIONED = 3; +} + +message CanonicalGameplayRosterResponse { + string canonical_account_uuid = 1; + CanonicalGameplayRosterTarget target = 2; + string snapshot_uuid = 3; + string snapshot_digest = 4; + repeated CanonicalGameplayRosterActor actors = 5; + shared.v1.ErrorDetail error = 6; +} + +message CanonicalGameplayRosterActor { + string character_uuid = 1; + string display_name = 2; + CanonicalGameplayRosterActorKind actor_kind = 3; +} + +message CanonicalGameplayRosterSelectedAssignmentRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget expected_target = 4; +} + +message CanonicalGameplayRosterSelectedAssignmentResponse { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget target = 4; + string assignment_uuid = 5; + string intent_digest = 6; + shared.v1.ErrorDetail error = 7; +} + +enum CanonicalGameplayRosterActorKind { + CANONICAL_ROSTER_ACTOR_KIND_UNSPECIFIED = 0; + CANONICAL_ROSTER_ACTOR_KIND_PLAYER = 1; +} + message CreateCharacterRequest { string tenant_id = 1; string account_id = 2; From fa9069f12f52bec57c65b7d0a09c636140fc7aef Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 06:45:45 +1300 Subject: [PATCH 02/34] Prepare canonical Game Session roster and assignment source reads --- .../game-session-service/api-contracts.md | 11 + .../game-session-service/runtime-and-data.md | 2 + ...e-session-runtime-and-tick-coordination.md | 2 + .../player-access-and-session.md | 2 + .../client/CanonicalGameplayRosterClient.java | 581 +++++++ .../GameDesignPublishedRealmPolicyClient.java | 128 ++ .../text/CanonicalGameplayActorSelection.java | 283 ++++ ...nceLaunchAssociationReadConfiguration.java | 31 + ...calInitialAdmissionOwnerConfiguration.java | 42 + ...CanonicalPlayerRouteReadConfiguration.java | 77 + ...nonicalClosedAdmissionPointerSnapshot.java | 60 + ...anonicalGameInstanceLaunchAssociation.java | 92 ++ ...CanonicalInitialAdmissionLaunchTarget.java | 28 + .../dto/CanonicalInitialAdmissionRequest.java | 4 +- .../CanonicalInitialAdmissionWorldProof.java | 85 + .../dto/CanonicalPublishedPlayerRoute.java | 39 + .../dto/CanonicalRealmCatalogSnapshot.java | 62 + ...anonicalClosedAdmissionPointerRequest.java | 73 + .../CreateCanonicalRealmCatalogRequest.java | 95 ++ ...nicalCurrentOpenPointerSnapshotDigest.java | 262 +++ ...meInstanceLaunchAssociationRepository.java | 732 ++++++++ .../CanonicalInitialAdmissionRepository.java | 1472 +++++++++++++++++ .../GameSessionAuthoredWorldIntakeDigest.java | 65 + ...eSessionAuthoredWorldSourceRepository.java | 517 ++++++ ...onCanonicalAdmissionPointerRepository.java | 1076 ++++++++++++ ...essionCanonicalRealmCatalogRepository.java | 1148 +++++++++++++ ...meplayAdmissionPointerEventRepository.java | 138 ++ ...tectedGameSessionLoginGrpcInterceptor.java | 38 + ...eInstanceLaunchAssociationReadRequest.java | 55 + ...eInstanceLaunchAssociationReadService.java | 54 + .../CanonicalInitialAdmissionService.java | 14 + ...anonicalInitialAdmissionWorldVerifier.java | 14 + .../CanonicalPlayerRouteReadService.java | 272 +++ ...onicalPublishedPlayerRouteReadService.java | 519 ++++++ .../FreshGameSessionTenantAssociation.java | 26 + ...calGameplayRosterOwnerReadGrpcAdapter.java | 166 ++ ...lGameplayRosterOwnerReadWorkloadGuard.java | 58 + ...abaseCanonicalInitialAdmissionService.java | 104 ++ ...anonicalInitialAdmissionWorldVerifier.java | 28 + .../src/main/resources/application.yml | 2 + ...RealmCatalogRepositoryIntegrationTest.java | 718 ++++++++ ...lCurrentOpenPointerSnapshotDigestTest.java | 234 +++ .../CanonicalGameplayRosterClientTest.java | 809 +++++++++ ...eDesignPublishedRealmPolicyClientTest.java | 293 ++++ .../CanonicalGameplayActorSelectionTest.java | 135 ++ ...aunchAssociationReadConfigurationTest.java | 56 + ...nitialAdmissionOwnerConfigurationTest.java | 87 + ...nicalPlayerRouteReadConfigurationTest.java | 162 ++ ...icalGameInstanceLaunchAssociationTest.java | 189 +++ .../CanonicalInitialAdmissionRequestTest.java | 209 ++- ...stanceLaunchAssociationRepositoryTest.java | 63 + ...eSessionAuthoredWorldIntakeDigestTest.java | 118 ++ ...nonicalAdmissionPointerRepositoryTest.java | 232 +++ ...onCanonicalRealmCatalogRepositoryTest.java | 222 +++ ...ayAdmissionPointerEventRepositoryTest.java | 26 + ...ayRosterOwnerReadInterceptorChainTest.java | 315 ++++ ...signmentOwnerReadInterceptorChainTest.java | 321 ++++ .../CanonicalPlayerRouteReadServiceTest.java | 478 ++++++ ...alPublishedPlayerRouteReadServiceTest.java | 307 ++++ ...ameplayRosterOwnerReadGrpcAdapterTest.java | 300 ++++ .../PublishedRealmPolicyEvidenceFixture.java | 765 +++++++++ 61 files changed, 14446 insertions(+), 50 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPublishedPlayerRoute.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapter.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadWorkloadGuard.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelectionTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java create mode 100644 services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..311a73c7a0 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -53,6 +53,17 @@ Lost responses reconcile through the exact hold identity and authoritative World The first admission-pointer bind for a realm is a separate owner transaction from replacement cutover. Game Session owns a durable attempt ledger with one stable request identity and canonical digest, plus the terminal outcome `COMMITTED` or `ABORTED`. Its initial pointer transaction must prove that no pointer exists for the exact `{tenantId, realmId}` and atomically bind the World-issued initial-bind hold identity/fence, the same request identity/digest, `{tenantId, realmId, playableStateNamespaceId, playableStateScope}`, target `gameInstanceId`/`versionId` and exact `ACTIVE` lifecycle epoch, and `catalogRevision` with the new pointer and matching append-only audit event. The durable `COMMITTED` attempt outcome commits in that same transaction. This owner-side no-prior-pointer check is not replaced by a bootstrap snapshot, startup configuration, public raw-pointer RPC, or external operator write bypass. 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 internal `CanonicalGameplayRosterOwnerReadService.GetCanonicalGameplayRosterOwnerRead` method is an Entity-only point-in-time source read. It requires the exact same-namespace Entity Management mTLS workload and no authenticated caller context; the request retains its exact caller-observed pointer-version and World-epoch preconditions. The route-reader composition is disabled unless `firemud.canonical-gameplay-roster-owner-read.enabled=true`; the bearer-check allowlist does not enable its source beans. The read returns source evidence only and does not create actors, bind sessions, or activate `PLAY` or `LOOK`. + +For the Entity-only canonical roster-owner read, Game Session returns `admissionPointerSnapshotDigest` from [`CanonicalInitialAdmissionRepository.readCurrentOpenSnapshotForRealm`](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java) only after validating one current V3 `OPEN` pointer, matching its exact durable `COMMITTED` attempt and append-only audit readback, and confirming the entire pointer row is unchanged across the before/after read. Its raw lowercase 64-hex SHA-256 preimage has domain `gs-canonical-current-open-pointer-snapshot/v1` and, in fixed order, binds: representation version; target namespace; canonical tenant UUID; world slug/display name; realm UUID/slug/display name; playable-state namespace UUID and scope; positive catalog revision and pointer version; admission state; visible and public-production flags; the required-null character-selection flag; character-creation policy; canonical game-instance and version UUIDs; initial-admission request ID/digest; origin kind and nullable expected prior-pointer version; positive active World epoch; hold UUID/fence/binding digest; last-updated actor/reason; the required-null prepared-version-upgrade ID; committed outcome; owner proof digest; positive audit event ID; and terminal timestamp. `pointer.updated_at` and audit occurrence time are validated against that terminal timestamp before hashing. Pointer surrogate ID, retained numeric tenant/game-instance/runtime-version IDs, and row creation time are not canonical identity inputs; canonical UUIDs remain the identity. + +Encoding is closed and unambiguous: strings use strict UTF-8 with a signed 32-bit byte length (`-1` only for null), without Unicode normalization; UUIDs are lowercase canonical strings; representation version is fixed-width big-endian int32; every long counter uses the unique base-10 `Long.toString()` representation in the same length-prefixed UTF-8 form; booleans use one byte; nullable booleans use `0=null`, `1=false`, `2=true`; nullable prior-pointer versions use a presence boolean followed by the canonical decimal counter string when present; and the terminal instant uses canonical UTC `Instant.toString()` after database-microsecond validation. The [Common evidence carrier](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java) and [roster-read response proto](../../../../protos/game-session/v1/canonical_gameplay_roster_owner_read.proto) transport this exact digest; they do not recompute it or treat it as a second authority. It is a point-in-time current-pointer commitment, not a permission spanning a later mutation, a fresh lifecycle check, membership proof, actor ownership, or `PLAY` admission. The opaque committed owner-proof digest is included as evidence; it is not a mapping from a retained numeric row key to canonical identity. + +### Entity preseeded-actor assignment source read + +`CanonicalGameplayRosterOwnerReadService.GetPreseededActorAssignmentOwnerRead` is an internal, Entity-only source read for non-admitting PRESEEDED actor assignment. It requires Entity Management's exact same-namespace workload identity over mTLS and no authenticated caller context. Its request selects the canonical Account and tenant plus the exact immutable realm, namespace/scope, current instance/version, catalog, policy-digest, and release selectors. It does not accept `pointerVersion` or `activeWorldEpoch`: Game Session derives both from its current OPEN pointer and terminal COMMITTED World-hold proof, then checks the complete current catalog, launch binding, and sealed Game Design policy set and rereads them before returning the request-bound evidence. The response carries the complete source proof and policy-set evidence plus the current pointer projection digest. + +Entity consumer code remains outside this Game Session source slice. The read itself is not permission to mutate actor data; Account remains the identity and membership authority, and this source method is not `JOIN` or `PLAY` admission. 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 workload leaf and CA fingerprints; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the published 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). 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). diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index df28765195..2eeae8c3e3 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -56,6 +56,8 @@ The sections below define the target-state runtime contract. Current implementat Game Session does not persist or allocate the primary actor. It resolves the realm target, asks Entity Management for the valid roster/policy result, and keeps `CHARS` as discovery before `PLAY`. A normal binding requires one persisted `characterId`; controller uniqueness is `{tenantId, playableStateNamespaceId, characterId}`, with `accountId` owner evidence and `playableStateScope`, `gameInstanceId`, and region/epoch as routing/fence evidence. See [Entity Runtime and Data](../entity-management-service/runtime-and-data.md) for allocation, policy, descriptor/template, and fork-copy rules. +The current Game Session route and published-policy readers, plus the Entity-only roster and preseeded-assignment source reads, remain behind default-off composition. They return bounded source evidence; they do not persist actor assignments, attach a gameplay session, or activate `PLAY`/`LOOK`. See [API Contracts](./api-contracts.md#initial-admission-bind) for the local read boundary. + The local runtime stores only active attachment, protocol state, presence, and controller-fence data. A playtest copy is selected by its new fork-local `characterId`; `sourceCharacterId` is not used as authority. Current per-instance lookup, unresolved-character fallback, and complete cross-service proof remain gaps. ## Owner-Local Gameplay Restrictions 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 94bfeb2333..20941caecd 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,6 +8,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. +The Entity-only roster and preseeded-assignment owner reads are a separate default-off, read-only source boundary; they do not change tick execution, attach sessions, or activate `PLAY`/`LOOK`. Focused route/client/guard and isolated selection proof artifacts are present but unrun in this preparation. See [Player Access and Session](./player-access-and-session.md) for AA-2.1 status and [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) for the source boundary. + Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). Retained bootstrap correction: V8 recognizes only the unchanged, provenance-backed historical demo/sandbox pair that was seeded with two public-production realms. It changes sandbox's public flag and advances only its catalog revision, retains runtime pointer and durable realm/namespace identity, and appends an immutable repair event in the same transaction. Unknown, operator-edited, incomplete, extra-public, or conflicting-history catalogs remain untouched and fail closed. This is not World-owner lifecycle or initial-bind proof. PostgreSQL execution remains a required separate check; the local environment has no Docker or PostgreSQL runtime. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8faf668d98..8376d61778 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +Game Session now carries a default-off source path for current route and published-policy evidence, with exact Entity-only roster and preseeded-assignment reads. Focused proof sources cover default-off and enabled route-reader composition (real reader beans with controlled repository/channel doubles), owner-caller guards, source clients, and actor selection using an isolated fixture. They were not run in this extraction and do not establish database or live owner-RPC execution. Entity consumer wiring and `PLAY`/`LOOK` activation remain outside this slice; `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). + The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. Earlier Account checkpoints `d619948920469228814d8d2ef60f9dac8672e7ea` and `f086de2896f885e33745d1482872ec2ae1c480c2` have reported green required CI, including full-stack Smoke. Reported local validation passed 535 Account unit tests, integration-test source compilation, and documentation checks; local physical PostgreSQL validation was not run. The newer reconciled head `5deaf573be3774b4eb8285ff857907f03b2ba5e0` and subsequent retained-source denial correction do not inherit an exact-head green claim. The correction passed 249 focused Account unit tests, integration-test source compilation, and documentation checks; exact-head required CI and physical PostgreSQL proof remain pending. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java new file mode 100644 index 0000000000..f927385853 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -0,0 +1,581 @@ +package net.firedevops.firemud.gamesession.client; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.ManagedChannel; +import jakarta.annotation.PostConstruct; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Set; +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.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Default-off, authenticated point-in-time reader for Entity's persisted PRESEEDED roster. */ +@Component +@ConditionalOnProperty( + prefix = "firemud.canonical-gameplay-roster-owner-read", + name = "enabled", + havingValue = "true") +public final class CanonicalGameplayRosterClient + extends AbstractReloadingBlockingGrpcClient< + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + // Matches Entity's bounded CanonicalGameplayRosterSnapshotDigest contract. + private static final int MAX_ROSTER_SIZE = 100; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String SNAPSHOT_DIGEST_DOMAIN = + "firemud.entity.canonical-gameplay-roster.v3"; + + private final String workloadNamespace; + + public CanonicalGameplayRosterClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProperties), + channelFactory, + CanonicalGameplayRosterClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + @PostConstruct + void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub buildStub( + ManagedChannel channel) { + return CanonicalGameplayRosterServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/entity-management-service")) + .withCompression("gzip"); + } + + /** + * Reads one complete Entity snapshot for an exact current published route. The result is + * discovery evidence only: it does not establish Account membership, admission, or PLAY. + */ + public PreseededRosterSnapshot listPreseededRoster( + CanonicalPublishedPlayerRoute publishedRoute, UUID canonicalAccountUuid) { + Objects.requireNonNull(publishedRoute, "publishedRoute"); + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + CanonicalGameplayRosterTarget expectedTarget = toExpectedTarget(publishedRoute); + CanonicalGameplayRosterRequest request = + CanonicalGameplayRosterRequest.newBuilder() + // This random UUID identifies only the read request; actor identity comes from Entity. + .setRequestUuid(UUID.randomUUID().toString()) + .setCanonicalAccountUuid(canonicalAccountUuid.toString()) + .setExpectedTarget(expectedTarget) + .build(); + + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Entity canonical gameplay roster client is not initialized"); + } + CanonicalGameplayRosterResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .listPreseededRoster(request); + return validateResponse(canonicalAccountUuid, expectedTarget, response); + } + + /** + * Reads Entity's owner-issued assignment reference for one actor selected from the exact + * previously validated SHARED PRESEEDED_ONLY roster snapshot. This point-in-time reference is not + * Account eligibility or admission evidence; the later World hold revalidates assignment. + */ + public VerifiedPreseededAssignment readSelectedPreseededAssignment( + PreseededRosterSnapshot roster, UUID selectedCharacterUuid) { + requireOutsideTransactionAndSynchronization(); + Objects.requireNonNull(roster, "roster"); + requireNonNil(selectedCharacterUuid, "selectedCharacterUuid"); + requireValidSelectedRosterSnapshot(roster); + CanonicalGameplayRosterTarget expectedTarget = roster.target(); + long actorMatches = + roster.actors().stream() + .filter(actor -> actor.characterUuid().equals(selectedCharacterUuid)) + .count(); + if (actorMatches != 1L) { + throw new IllegalArgumentException( + "Selected character must occur exactly once in the validated Entity roster"); + } + + UUID requestUuid = UUID.randomUUID(); + CanonicalGameplayRosterSelectedAssignmentRequest request = + CanonicalGameplayRosterSelectedAssignmentRequest.newBuilder() + .setRequestUuid(requestUuid.toString()) + .setCanonicalAccountUuid(roster.canonicalAccountUuid().toString()) + .setSelectedCharacterUuid(selectedCharacterUuid.toString()) + .setExpectedTarget(expectedTarget) + .build(); + + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Entity canonical gameplay roster client is not initialized"); + } + CanonicalGameplayRosterSelectedAssignmentResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readSelectedPreseededAssignment(request); + return validateSelectedAssignmentResponse(requestUuid, roster, selectedCharacterUuid, response); + } + + private static void requireOutsideTransactionAndSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Entity selected assignment reads cannot run inside a Game Session transaction " + + "or synchronization"); + } + } + + private static void requireValidSelectedRosterSnapshot(PreseededRosterSnapshot roster) { + CanonicalGameplayRosterTarget target = Objects.requireNonNull(roster.target(), "roster.target"); + if (!target.getUnknownFields().asMap().isEmpty() + || target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) { + throw new IllegalArgumentException( + "Selected assignment reads require an exact SHARED PRESEEDED_ONLY roster target"); + } + if (roster.actors().size() > MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Validated Entity roster exceeds its maximum size"); + } + Set characterUuids = new HashSet<>(); + for (RosterActor actor : roster.actors()) { + if (actor == null) { + throw new IllegalArgumentException("Validated Entity roster contains an absent actor"); + } + UUID characterUuid = actor.characterUuid(); + requireNonNil(characterUuid, "roster character UUID"); + if (!characterUuids.add(characterUuid)) { + throw new IllegalArgumentException("Validated Entity roster contains a duplicate actor"); + } + String displayName = actor.displayName(); + if (displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.length() > 100 + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Validated Entity roster contains a malformed actor"); + } + } + if (!roster + .snapshotDigest() + .equals(calculateSnapshotDigest(roster.canonicalAccountUuid(), target, roster.actors()))) { + throw new IllegalArgumentException( + "Selected assignment input is not the exact validated Entity roster snapshot"); + } + } + + private static VerifiedPreseededAssignment validateSelectedAssignmentResponse( + UUID requestUuid, + PreseededRosterSnapshot roster, + UUID selectedCharacterUuid, + CanonicalGameplayRosterSelectedAssignmentResponse response) { + if (response == null) { + throw invalidSelectedAssignmentResponse("response is absent"); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidSelectedAssignmentResponse("response contains unknown fields"); + } + if (response.hasError()) { + if (!response.getError().getUnknownFields().asMap().isEmpty()) { + throw invalidSelectedAssignmentResponse("error contains unknown fields"); + } + String code = response.getError().getCode(); + throw new IllegalStateException( + "Entity selected assignment read failed" + + (code == null || code.isBlank() ? "" : ": " + code)); + } + if (!requestUuid.toString().equals(response.getRequestUuid())) { + throw invalidSelectedAssignmentResponse("response changed the request correlation"); + } + if (!roster.canonicalAccountUuid().toString().equals(response.getCanonicalAccountUuid())) { + throw invalidSelectedAssignmentResponse("response changed the canonical account UUID"); + } + if (!selectedCharacterUuid.toString().equals(response.getSelectedCharacterUuid())) { + throw invalidSelectedAssignmentResponse("response changed the selected character UUID"); + } + if (!response.hasTarget() + || !response.getTarget().getUnknownFields().asMap().isEmpty() + || !roster.target().equals(response.getTarget())) { + throw invalidSelectedAssignmentResponse("response changed the complete expected target"); + } + UUID assignmentOperationId = + parseCanonicalUuid(response.getAssignmentUuid(), "assignment_uuid"); + String intentDigest = response.getIntentDigest(); + if (intentDigest == null || !intentDigest.matches("[0-9a-f]{64}")) { + throw invalidSelectedAssignmentResponse( + "intent_digest is not bare canonical lowercase SHA-256 hex"); + } + return new VerifiedPreseededAssignment( + roster.canonicalAccountUuid(), + selectedCharacterUuid, + roster.target(), + roster.snapshotUuid(), + roster.snapshotDigest(), + assignmentOperationId, + intentDigest); + } + + private static IllegalStateException invalidSelectedAssignmentResponse(String message) { + return new IllegalStateException("Entity selected assignment response is invalid: " + message); + } + + private static PreseededRosterSnapshot validateResponse( + UUID expectedAccountUuid, + CanonicalGameplayRosterTarget expectedTarget, + CanonicalGameplayRosterResponse response) { + if (response == null) { + throw invalidResponse("response is absent"); + } + if (response.hasError()) { + String code = response.getError().getCode(); + throw new IllegalStateException( + "Entity canonical gameplay roster read failed" + + (code == null || code.isBlank() ? "" : ": " + code)); + } + if (!response.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("response contains unknown fields"); + } + if (!expectedAccountUuid.toString().equals(response.getCanonicalAccountUuid())) { + throw invalidResponse("response changed the canonical account UUID"); + } + if (!response.hasTarget() + || !response.getTarget().getUnknownFields().asMap().isEmpty() + || !expectedTarget.equals(response.getTarget())) { + throw invalidResponse("response changed the complete expected target"); + } + UUID snapshotUuid = parseCanonicalUuid(response.getSnapshotUuid(), "snapshot_uuid"); + String snapshotDigest = response.getSnapshotDigest(); + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw invalidResponse("snapshot_digest is not canonical lowercase SHA-256 hex"); + } + if (response.getActorsCount() > MAX_ROSTER_SIZE) { + throw invalidResponse("actor roster exceeds its maximum size"); + } + + Set characterUuids = new HashSet<>(); + List actors = new ArrayList<>(response.getActorsCount()); + for (CanonicalGameplayRosterActor actor : response.getActorsList()) { + if (!actor.getUnknownFields().asMap().isEmpty()) { + throw invalidResponse("actor contains unknown fields"); + } + UUID characterUuid = parseCanonicalUuid(actor.getCharacterUuid(), "character_uuid"); + if (!characterUuids.add(characterUuid)) { + throw invalidResponse("actor roster contains a duplicate character UUID"); + } + if (actor.getActorKind() + != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) { + throw invalidResponse("actor roster contains an unsupported actor kind"); + } + String displayName = actor.getDisplayName(); + if (displayName == null + || displayName.isBlank() + || !displayName.equals(displayName.trim()) + || displayName.length() > 100 + || displayName.codePoints().anyMatch(Character::isISOControl)) { + throw invalidResponse("actor display name is malformed"); + } + actors.add(new RosterActor(characterUuid, displayName)); + } + if (!snapshotDigest.equals( + calculateSnapshotDigest(expectedAccountUuid, expectedTarget, actors))) { + throw invalidResponse("snapshot_digest does not bind the returned target and roster"); + } + return new PreseededRosterSnapshot( + expectedAccountUuid, snapshotUuid, snapshotDigest, expectedTarget, actors); + } + + private static CanonicalGameplayRosterTarget toExpectedTarget( + CanonicalPublishedPlayerRoute publishedRoute) { + CanonicalPlayableTarget route = publishedRoute.route(); + RealmEntryPolicy policy = publishedRoute.entryPolicy(); + if (policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !"SHARED".equals(route.playableStateScope())) { + throw new IllegalArgumentException( + "Canonical roster reads require the exact published SHARED PRESEEDED_ONLY route"); + } + PublishedRealmEntryPolicyEvidence selectedPolicy = publishedRoute.selectedPolicyEvidence(); + publishedRoute.policySetEvidence().requireValidDigest(); + selectedPolicy.requireValidDigest(publishedRoute.policySetEvidence()); + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(route.canonicalTenantId().toString()) + .setRealmUuid(route.realmId().toString()) + .setWorldSlug(route.worldSlug()) + .setRealmSlug(route.realmSlug()) + .setGameInstanceUuid(route.canonicalGameInstanceId().toString()) + .setCatalogRevision(route.catalogRevision()) + .setPublishedPolicyDigest(rawPublishedPolicyDigest(selectedPolicy.policyDigest())) + .setPublishedReleaseBundleRef( + publishedRoute.policySetEvidence().publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest(route.admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest(rawOwnerProofDigest(route.ownerProofDigest())) + .setPlayableStateNamespaceUuid(route.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .setCanonicalVersionUuid(route.canonicalVersionId().toString()) + .setPointerVersion(route.pointerVersion()) + .setActiveWorldEpoch(route.activeWorldEpoch()) + .build(); + } + + private static String rawOwnerProofDigest(String prefixedDigest) { + if (prefixedDigest == null || !prefixedDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Canonical route owner-proof digest is malformed"); + } + return prefixedDigest.substring("sha256:".length()); + } + + private static String rawPublishedPolicyDigest(String prefixedDigest) { + if (prefixedDigest == null || !prefixedDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Published route policy digest is malformed"); + } + return prefixedDigest.substring("sha256:".length()); + } + + private static String calculateSnapshotDigest( + UUID canonicalAccountUuid, CanonicalGameplayRosterTarget target, List actors) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + // Mirrors Entity's canonical roster digest/v3; divergence fails closed at the client. + write(output, SNAPSHOT_DIGEST_DOMAIN); + write(output, canonicalAccountUuid.toString()); + write(output, target.getTenantUuid()); + write(output, target.getRealmUuid()); + write(output, target.getWorldSlug()); + write(output, target.getRealmSlug()); + write(output, target.getGameInstanceUuid()); + write(output, Long.toString(target.getCatalogRevision())); + write(output, Long.toString(target.getPointerVersion())); + write(output, Long.toString(target.getActiveWorldEpoch())); + write(output, target.getCanonicalVersionUuid()); + write(output, target.getPublishedPolicyDigest()); + write(output, target.getPublishedReleaseBundleRef()); + write(output, target.getAdmissionPointerSnapshotDigest()); + write(output, target.getPublishedOwnerProofDigest()); + write(output, target.getPlayableStateNamespaceUuid()); + write(output, target.getPlayableStateScope().name()); + write(output, "PRESEEDED_ONLY"); + write(output, Integer.toString(actors.size())); + for (RosterActor actor : actors) { + write(output, actor.characterUuid().toString()); + write(output, actor.displayName()); + } + } + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } catch (NoSuchAlgorithmException | IOException impossible) { + throw new IllegalStateException( + "Unable to validate Entity roster snapshot digest", impossible); + } + } + + private static void write(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } + + private static UUID parseCanonicalUuid(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw invalidResponse(fieldName + " is missing"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw invalidResponse(fieldName + " is not a canonical UUID", malformed); + } + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw invalidResponse(fieldName + " is not a canonical non-nil UUID"); + } + return parsed; + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical non-nil UUID"); + } + } + + private static IllegalStateException invalidResponse(String message) { + return new IllegalStateException( + "Entity canonical gameplay roster response is invalid: " + message); + } + + private static IllegalStateException invalidResponse(String message, Throwable cause) { + return new IllegalStateException( + "Entity canonical gameplay roster response is invalid: " + 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( + "Canonical roster reads require Game Session workload mTLS"); + } + if (!hasText(tlsProperties.getCertChain()) + || !hasText(tlsProperties.getPrivateKey()) + || !hasText(tlsProperties.getCaCert())) { + throw new IllegalArgumentException( + "Canonical roster 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( + "Canonical roster reads require file-backed Game Session workload mTLS"); + } + return tlsProperties; + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + /** Entity-authenticated assignment reference bound to one exact roster actor and target. */ + public static final class VerifiedPreseededAssignment { + private final UUID canonicalAccountUuid; + private final UUID selectedCharacterUuid; + private final CanonicalGameplayRosterTarget target; + private final UUID rosterSnapshotUuid; + private final String rosterSnapshotDigest; + private final UUID assignmentOperationId; + private final String intentDigest; + + private VerifiedPreseededAssignment( + UUID canonicalAccountUuid, + UUID selectedCharacterUuid, + CanonicalGameplayRosterTarget target, + UUID rosterSnapshotUuid, + String rosterSnapshotDigest, + UUID assignmentOperationId, + String intentDigest) { + this.canonicalAccountUuid = + Objects.requireNonNull(canonicalAccountUuid, "canonicalAccountUuid"); + this.selectedCharacterUuid = + Objects.requireNonNull(selectedCharacterUuid, "selectedCharacterUuid"); + this.target = Objects.requireNonNull(target, "target"); + this.rosterSnapshotUuid = Objects.requireNonNull(rosterSnapshotUuid, "rosterSnapshotUuid"); + this.rosterSnapshotDigest = + Objects.requireNonNull(rosterSnapshotDigest, "rosterSnapshotDigest"); + this.assignmentOperationId = + Objects.requireNonNull(assignmentOperationId, "assignmentOperationId"); + this.intentDigest = Objects.requireNonNull(intentDigest, "intentDigest"); + } + + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + public UUID selectedCharacterUuid() { + return selectedCharacterUuid; + } + + public CanonicalGameplayRosterTarget target() { + return target; + } + + public UUID rosterSnapshotUuid() { + return rosterSnapshotUuid; + } + + public String rosterSnapshotDigest() { + return rosterSnapshotDigest; + } + + public UUID assignmentOperationId() { + return assignmentOperationId; + } + + public String intentDigest() { + return intentDigest; + } + } + + public record RosterActor(UUID characterUuid, String displayName) {} + + /** Entity's exact source snapshot; its UUID is not admission or controller authority. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The target is an immutable built protobuf message; actor lists are copied.") + public record PreseededRosterSnapshot( + UUID canonicalAccountUuid, + UUID snapshotUuid, + String snapshotDigest, + CanonicalGameplayRosterTarget target, + List actors) { + public PreseededRosterSnapshot { + requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); + requireNonNil(snapshotUuid, "snapshotUuid"); + Objects.requireNonNull(target, "target"); + if (snapshotDigest == null || !snapshotDigest.matches("[0-9a-f]{64}")) { + throw new IllegalArgumentException( + "snapshotDigest must be canonical lowercase SHA-256 hex"); + } + actors = List.copyOf(Objects.requireNonNull(actors, "actors")); + if (actors.size() > MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Roster exceeds the maximum supported size"); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java new file mode 100644 index 0000000000..79ac391b87 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.gamesession.client; + +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.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; + +/** Unwired Game Session receiver for complete immutable Game Design realm-policy sets. */ +public final class GameDesignPublishedRealmPolicyClient + extends AbstractReloadingBlockingGrpcClient< + PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final String workloadNamespace; + + public GameDesignPublishedRealmPolicyClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireGameSessionMtls(tlsProps), + channelFactory, + GameDesignPublishedRealmPolicyClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace must be one DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes the owner client only when an explicit caller owns this handoff. */ + 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 PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + buildStub(ManagedChannel channel) { + return PublishedRealmEntryPolicyServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) + .withCompression("gzip"); + } + + /** Reads and verifies the complete bounded owner set for an exact published tenant version. */ + public PublishedRealmEntryPolicySetEvidence listPublishedRealmEntryPolicies( + UUID canonicalTenantId, UUID canonicalVersionId) { + requireNonNil(canonicalTenantId, "canonical tenant ID"); + requireNonNil(canonicalVersionId, "canonical version ID"); + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException( + "Game Design published realm policy client is not initialized"); + } + + PublishedRealmEntryPolicyReadGrpcCodec.ListRequest request = + new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( + workloadNamespace, UUID.randomUUID(), canonicalTenantId, canonicalVersionId); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .listPublishedRealmEntryPolicies( + PublishedRealmEntryPolicyReadGrpcCodec.toRequest(request)); + try { + return PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Game Design published realm policy response is invalid", invalid); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); + } + } + + private static CommonGrpcClientProperties requireGameSessionMtls( + CommonGrpcClientProperties tlsProps) { + if (tlsProps == null) { + throw new IllegalArgumentException("Game Session gRPC TLS configuration is required"); + } + if (tlsProps.isPlaintext()) { + throw new IllegalArgumentException( + "Published realm policy reads require Game Session workload mTLS"); + } + if (!hasText(tlsProps.getCertChain()) + || !hasText(tlsProps.getPrivateKey()) + || !hasText(tlsProps.getCaCert())) { + throw new IllegalArgumentException( + "Published realm policy reads require Game Session certificate, key, and CA files"); + } + if (tlsProps.getCertChain().trim().startsWith("classpath:") + || tlsProps.getPrivateKey().trim().startsWith("classpath:") + || tlsProps.getCaCert().trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + "Published realm policy reads require file-backed Game Session workload mTLS"); + } + return tlsProps; + } + + 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/command/text/CanonicalGameplayActorSelection.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java new file mode 100644 index 0000000000..2d1007e4bd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java @@ -0,0 +1,283 @@ +package net.firedevops.firemud.gamesession.command.text; + +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.publication.RealmEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; + +/** + * Validates and selects actors only from one Account- and route-bound canonical roster snapshot. + */ +public final class CanonicalGameplayActorSelection { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int MAX_ROSTER_SIZE = 100; + + private CanonicalGameplayActorSelection() {} + + /** + * Returns an opaque validated view only when the complete Entity snapshot matches the trusted + * Account and the exact current published route. A rejected snapshot must not reach PLAY. + */ + public static Optional validate( + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot, + UUID expectedAccountUuid, + CanonicalPublishedPlayerRoute expectedRoute) { + try { + if (snapshot == null + || !isNonNil(expectedAccountUuid) + || !expectedAccountUuid.equals(snapshot.canonicalAccountUuid()) + || !isNonNil(snapshot.snapshotUuid()) + || !isCanonicalDigest(snapshot.snapshotDigest()) + || expectedRoute == null + || !matchesExactPublishedTarget(snapshot.target(), expectedRoute)) { + return Optional.empty(); + } + List actors = snapshot.actors(); + if (actors == null || actors.size() > MAX_ROSTER_SIZE) { + return Optional.empty(); + } + Set actorIds = new HashSet<>(); + for (CanonicalGameplayRosterClient.RosterActor actor : actors) { + if (actor == null + || !isNonNil(actor.characterUuid()) + || !actorIds.add(actor.characterUuid()) + || !isCanonicalDisplayName(actor.displayName())) { + return Optional.empty(); + } + } + return Optional.of(new ValidatedRoster(snapshot, expectedAccountUuid, expectedRoute)); + } catch (RuntimeException malformed) { + return Optional.empty(); + } + } + + /** + * Resolves an optional one-based menu ordinal. Actor UUIDs and actor names are never accepted as + * user selectors; the selected UUID remains internal output from this exact validated snapshot. + */ + public static SelectionResult select(ValidatedRoster roster, String selector) { + if (roster == null) { + return new Denied(Denial.INVALID_SNAPSHOT); + } + List actors = roster.snapshot().actors(); + if (actors.isEmpty()) { + return new Denied(Denial.NO_PRESEEDED_ACTOR); + } + if (selector == null || selector.isBlank()) { + if (actors.size() == 1) { + return selected(roster, 1, actors.getFirst()); + } + return new SelectionRequired( + actors.stream() + .map(actor -> new Choice(actors.indexOf(actor) + 1, actor.displayName())) + .toList()); + } + if (!selector.matches("[1-9][0-9]{0,2}")) { + return new Denied(Denial.INVALID_SELECTOR); + } + int ordinal; + try { + ordinal = Integer.parseInt(selector); + } catch (NumberFormatException malformed) { + return new Denied(Denial.INVALID_SELECTOR); + } + if (ordinal > actors.size()) { + return new Denied(Denial.SELECTOR_OUT_OF_RANGE); + } + return selected(roster, ordinal, actors.get(ordinal - 1)); + } + + private static Selected selected( + ValidatedRoster roster, int ordinal, CanonicalGameplayRosterClient.RosterActor actor) { + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot = roster.snapshot(); + return new Selected( + roster.canonicalAccountUuid(), + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + snapshot.target(), + actor.characterUuid(), + actor.displayName(), + ordinal); + } + + private static boolean matchesExactPublishedTarget( + CanonicalGameplayRosterTarget target, CanonicalPublishedPlayerRoute publishedRoute) { + if (target == null || !target.getUnknownFields().asMap().isEmpty()) { + return false; + } + var route = publishedRoute.route(); + RealmEntryPolicy policy = publishedRoute.entryPolicy(); + if (policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !"SHARED".equals(route.playableStateScope())) { + return false; + } + publishedRoute.policySetEvidence().requireValidDigest(); + publishedRoute.selectedPolicyEvidence().requireValidDigest(publishedRoute.policySetEvidence()); + return target.getTenantUuid().equals(route.canonicalTenantId().toString()) + && target.getRealmUuid().equals(route.realmId().toString()) + && target.getWorldSlug().equals(route.worldSlug()) + && target.getRealmSlug().equals(route.realmSlug()) + && target.getGameInstanceUuid().equals(route.canonicalGameInstanceId().toString()) + && target.getCatalogRevision() == route.catalogRevision() + && target + .getPublishedPolicyDigest() + .equals(rawDigest(publishedRoute.selectedPolicyEvidence().policyDigest())) + && target + .getPublishedReleaseBundleRef() + .equals(publishedRoute.policySetEvidence().publishedReleaseBundleRef()) + && target.getAdmissionPointerSnapshotDigest().equals(route.admissionPointerSnapshotDigest()) + && target.getPublishedOwnerProofDigest().equals(rawDigest(route.ownerProofDigest())) + && target + .getPlayableStateNamespaceUuid() + .equals(route.playableStateNamespaceId().toString()) + && target.getPlayableStateScope() == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && target.getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY + && target.getCanonicalVersionUuid().equals(route.canonicalVersionId().toString()) + && target.getPointerVersion() == route.pointerVersion() + && target.getActiveWorldEpoch() == route.activeWorldEpoch(); + } + + private static String rawDigest(String prefixedDigest) { + if (prefixedDigest == null || !prefixedDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Published route digest is malformed"); + } + return prefixedDigest.substring("sha256:".length()); + } + + private static boolean isCanonicalDisplayName(String value) { + return value != null + && !value.isBlank() + && value.equals(value.trim()) + && value.length() <= 100 + && value.codePoints().noneMatch(Character::isISOControl); + } + + private static boolean isCanonicalDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private static boolean isNonNil(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + /** Snapshot-bound selection data; instances can only be created by {@link #validate}. */ + public static final class ValidatedRoster { + private final CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot; + private final UUID canonicalAccountUuid; + private final CanonicalPublishedPlayerRoute route; + + private ValidatedRoster( + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot, + UUID canonicalAccountUuid, + CanonicalPublishedPlayerRoute route) { + this.snapshot = snapshot; + this.canonicalAccountUuid = canonicalAccountUuid; + this.route = route; + } + + public CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot() { + return snapshot; + } + + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + public CanonicalPublishedPlayerRoute route() { + return route; + } + + public List actors() { + return snapshot.actors(); + } + } + + public sealed interface SelectionResult permits Selected, SelectionRequired, Denied {} + + /** The UUID is usable only as internal input to downstream exact target/account validation. */ + public static final class Selected implements SelectionResult { + private final UUID canonicalAccountUuid; + private final UUID rosterSnapshotUuid; + private final String rosterSnapshotDigest; + private final CanonicalGameplayRosterTarget target; + private final UUID characterUuid; + private final String displayName; + private final int ordinal; + + private Selected( + UUID canonicalAccountUuid, + UUID rosterSnapshotUuid, + String rosterSnapshotDigest, + CanonicalGameplayRosterTarget target, + UUID characterUuid, + String displayName, + int ordinal) { + this.canonicalAccountUuid = canonicalAccountUuid; + this.rosterSnapshotUuid = rosterSnapshotUuid; + this.rosterSnapshotDigest = rosterSnapshotDigest; + this.target = target; + this.characterUuid = characterUuid; + this.displayName = displayName; + this.ordinal = ordinal; + } + + public UUID canonicalAccountUuid() { + return canonicalAccountUuid; + } + + public UUID rosterSnapshotUuid() { + return rosterSnapshotUuid; + } + + public String rosterSnapshotDigest() { + return rosterSnapshotDigest; + } + + public CanonicalGameplayRosterTarget target() { + return target; + } + + public UUID characterUuid() { + return characterUuid; + } + + public String displayName() { + return displayName; + } + + public int ordinal() { + return ordinal; + } + } + + public record Choice(int ordinal, String displayName) {} + + public record SelectionRequired(List choices) implements SelectionResult { + public SelectionRequired { + choices = List.copyOf(Objects.requireNonNull(choices, "choices")); + } + } + + public record Denied(Denial reason) implements SelectionResult { + public Denied { + Objects.requireNonNull(reason, "reason"); + } + } + + public enum Denial { + INVALID_SNAPSHOT, + NO_PRESEEDED_ACTOR, + INVALID_SELECTOR, + SELECTOR_OUT_OF_RANGE + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java new file mode 100644 index 0000000000..0248369bb5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfiguration.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadService; +import org.jooq.DSLContext; +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; + +/** Explicit opt-in wiring for the World-only canonical Game Session owner read boundary. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-game-instance-launch-association-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalGameInstanceLaunchAssociationReadConfiguration { + @Bean + CanonicalGameInstanceLaunchAssociationRepository canonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new CanonicalGameInstanceLaunchAssociationRepository(dsl, workloadNamespace); + } + + @Bean + CanonicalGameInstanceLaunchAssociationReadService + canonicalGameInstanceLaunchAssociationReadService( + CanonicalGameInstanceLaunchAssociationRepository repository, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new CanonicalGameInstanceLaunchAssociationReadService(repository, workloadNamespace); + } +} 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 new file mode 100644 index 0000000000..66fa77ed47 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfiguration.java @@ -0,0 +1,42 @@ +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.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionService; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import net.firedevops.firemud.gamesession.service.impl.DatabaseCanonicalInitialAdmissionService; +import org.jooq.DSLContext; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Explicit opt-in composition for the canonical initial-admission owner. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-game-instance-launch-association-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalInitialAdmissionOwnerConfiguration { + @Bean + CanonicalInitialAdmissionRepository canonicalInitialAdmissionRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + return new CanonicalInitialAdmissionRepository( + dsl, catalogRepository, pointerRepository, launchRepository, eventRepository); + } + + @Bean + CanonicalInitialAdmissionService canonicalInitialAdmissionService( + CanonicalInitialAdmissionRepository repository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalInitialAdmissionWorldVerifier worldVerifier) { + return new DatabaseCanonicalInitialAdmissionService( + repository, pointerRepository, worldVerifier); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java new file mode 100644 index 0000000000..dda265fb34 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java @@ -0,0 +1,77 @@ +package net.firedevops.firemud.gamesession.config; + +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.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import org.springframework.beans.factory.ObjectProvider; +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; + +/** Default-off composition for exact canonical route reads. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.canonical-gameplay-roster-owner-read", + name = "enabled", + havingValue = "true") +public class CanonicalPlayerRouteReadConfiguration { + @Bean(initMethod = "init", destroyMethod = "close") + GameDesignPublishedRealmPolicyClient canonicalPlayerRoutePolicyClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameDesignPublishedRealmPolicyClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + } + + @Bean + CanonicalPlayerRouteReadService canonicalPlayerRouteReadService( + ObjectProvider catalogRepositoryProvider, + ObjectProvider admissionRepositoryProvider, + ObjectProvider launchRepositoryProvider, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + GameSessionCanonicalRealmCatalogRepository catalogRepository = + catalogRepositoryProvider.getIfAvailable(); + CanonicalInitialAdmissionRepository admissionRepository = + admissionRepositoryProvider.getIfAvailable(); + CanonicalGameInstanceLaunchAssociationRepository launchRepository = + launchRepositoryProvider.getIfAvailable(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || catalogRepository == null + || admissionRepository == null + || launchRepository == null) { + return CanonicalPlayerRouteReadService.unavailable(); + } + return new CanonicalPlayerRouteReadService( + workloadNamespace, catalogRepository, admissionRepository, launchRepository); + } + + @Bean + CanonicalPublishedPlayerRouteReadService canonicalPublishedPlayerRouteReadService( + CanonicalPlayerRouteReadService routeReader, + ObjectProvider catalogRepositoryProvider, + ObjectProvider launchRepositoryProvider, + GameDesignPublishedRealmPolicyClient policyClient, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + GameSessionCanonicalRealmCatalogRepository catalogRepository = + catalogRepositoryProvider.getIfAvailable(); + CanonicalGameInstanceLaunchAssociationRepository launchRepository = + launchRepositoryProvider.getIfAvailable(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || catalogRepository == null + || launchRepository == null) { + return CanonicalPublishedPlayerRouteReadService.unavailable(); + } + return new CanonicalPublishedPlayerRouteReadService( + workloadNamespace, routeReader, catalogRepository, launchRepository, policyClient); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java new file mode 100644 index 0000000000..6ac773e430 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalClosedAdmissionPointerSnapshot.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; +import org.springframework.lang.Nullable; + +/** Exact committed owner evidence for one initial canonical CLOSED route. */ +public record CanonicalClosedAdmissionPointerSnapshot( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long pointerVersion, + long catalogRevision, + String admissionState, + @Nullable UUID admissibleGameInstanceId, + UUID requestId, + String requestDigest, + String receiptDigest, + String actorPrincipal, + String reason, + long auditEventId, + Instant updatedAt, + CanonicalRealmCatalogSnapshot catalogSnapshot) { + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "CLOSED routing requires the nullable admissible instance to be absent; this constructor rejects any supplied UUID.") + public CanonicalClosedAdmissionPointerSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(admissionState, "admissionState"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(actorPrincipal, "actorPrincipal"); + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(updatedAt, "updatedAt"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + if (!"CLOSED".equals(admissionState) + || admissibleGameInstanceId != null + || pointerVersion != 1L + || catalogRevision != catalogSnapshot.catalogRevision() + || !targetNamespace.equals(catalogSnapshot.targetNamespace()) + || !canonicalTenantId.equals(catalogSnapshot.tenantId()) + || !realmId.equals(catalogSnapshot.realmId()) + || !worldSlug.equals(catalogSnapshot.worldSlug()) + || !realmSlug.equals(catalogSnapshot.realmSlug()) + || auditEventId <= 0L) { + throw new IllegalArgumentException( + "Canonical closed pointer snapshot does not match its exact initial catalog evidence"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java new file mode 100644 index 0000000000..d58cdedeba --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Durable fresh-tenant launch association plus a separate current Game Session row projection. */ +public record CanonicalGameInstanceLaunchAssociation( + String targetNamespace, + long gameSessionTenantId, + UUID tenantAssociationOperationId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + String worldSlug, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + String launchDescriptorId, + long capturedStartingRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public enum CurrentGameInstanceStatus { + STARTING, + RUNNING, + STOPPING, + STOPPED + } + + public CanonicalGameInstanceLaunchAssociation { + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requireNonNil(tenantAssociationOperationId, "tenantAssociationOperationId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + if (playableStateScope != RealmEntryPolicy.StateScope.SHARED) { + throw new IllegalArgumentException("Canonical launch association requires SHARED scope"); + } + if (!publicProduction) { + throw new IllegalArgumentException( + "Canonical launch association requires owner-confirmed public production"); + } + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + if (capturedStartingRowVersion < 0) { + throw new IllegalArgumentException("capturedStartingRowVersion must not be negative"); + } + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); + if (currentRowVersion < capturedStartingRowVersion) { + throw new IllegalArgumentException( + "currentRowVersion must not precede the captured STARTING row version"); + } + + var descriptor = launchBindingEvidence.descriptor(); + descriptor.requireValid(); + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (!targetNamespace.equals(descriptor.targetNamespace()) + || !canonicalTenantId.equals(descriptor.canonicalTenantId()) + || !worldSlug.equals(descriptor.worldSlug()) + || !controlPlaneRequestId.equals(descriptor.controlPlaneRequestId()) + || !launchDescriptorId.equals(descriptor.launchDescriptorId())) { + throw new IllegalArgumentException( + "Launch association does not match its complete authored launch binding"); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java new file mode 100644 index 0000000000..4a6a5502dc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; + +/** The exact canonical launch association and its owner-local runtime row locked together. */ +public record CanonicalInitialAdmissionLaunchTarget( + CanonicalGameInstanceLaunchAssociation association, + UUID realmId, + long gameInstanceId, + long runtimeVersionId) { + public CanonicalInitialAdmissionLaunchTarget { + Objects.requireNonNull(association, "association"); + Objects.requireNonNull(realmId, "realmId"); + if (gameInstanceId <= 0L || runtimeVersionId <= 0L) { + throw new IllegalArgumentException("Canonical launch target identifiers must be positive"); + } + if (association.launchBindingEvidence().descriptor().versionId() != runtimeVersionId) { + throw new IllegalArgumentException( + "Current runtime version does not match the canonical launch descriptor"); + } + } + + /** Canonical content version from retained publication evidence, never from the numeric row. */ + public UUID canonicalVersionId() { + return association.launchBindingEvidence().releaseAttestation().canonicalVersionId(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java index 3d8be169e7..9cbe4afc27 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java @@ -67,8 +67,8 @@ public enum OriginKind { throw new IllegalArgumentException( "EXPECT_CLOSED requires a positive exact expectedPriorPointerVersion"); } - // Match the 128-character owner attempt and immutable intent ledgers. - requireText(initialAdmissionRequestId, "initialAdmissionRequestId", 128); + // The immutable compatibility audit's control_plane_request_id is varchar(120). + requireText(initialAdmissionRequestId, "initialAdmissionRequestId", 120); if (!REQUEST_DIGEST.matcher(Objects.requireNonNull(requestDigest, "requestDigest")).matches()) { throw new IllegalArgumentException( "requestDigest must be bare lowercase 64-character SHA-256 hex"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java new file mode 100644 index 0000000000..610fd2f04d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionWorldProof.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** Exact World-owned ACTIVE lifecycle and initial-admission hold read returned outside SQL. */ +public record CanonicalInitialAdmissionWorldProof( + String initialAdmissionRequestId, + String requestDigest, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + String lifecycleState, + long activeLifecycleEpoch, + CanonicalInitialAdmissionRequest.OriginKind originKind, + long expectedCatalogRevision, + Long expectedPriorPointerVersion, + UUID holdId, + UUID holdFence, + String holdBindingDigest) { + private static final Pattern WORLD_BINDING_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalInitialAdmissionWorldProof { + Objects.requireNonNull(initialAdmissionRequestId, "initialAdmissionRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(canonicalGameInstanceId, "canonicalGameInstanceId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(lifecycleState, "lifecycleState"); + Objects.requireNonNull(originKind, "originKind"); + Objects.requireNonNull(holdId, "holdId"); + Objects.requireNonNull(holdFence, "holdFence"); + if (!WORLD_BINDING_DIGEST + .matcher(Objects.requireNonNull(holdBindingDigest, "holdBindingDigest")) + .matches()) { + throw new IllegalArgumentException("World hold proof has an invalid binding digest"); + } + if (activeLifecycleEpoch <= 0L + || expectedCatalogRevision <= 0L + || !"ACTIVE".equals(lifecycleState)) { + throw new IllegalArgumentException("World proof must contain an exact positive ACTIVE epoch"); + } + if ((originKind == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) + || (originKind == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED + && (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L))) { + throw new IllegalArgumentException("World hold proof has an invalid tagged origin"); + } + } + + public void requireMatches(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + if (!initialAdmissionRequestId.equals(request.initialAdmissionRequestId()) + || !requestDigest.equals(request.requestDigest()) + || !targetNamespace.equals(request.targetNamespace()) + || !canonicalTenantId.equals(request.canonicalTenantId()) + || !worldSlug.equals(request.worldSlug()) + || !realmId.equals(request.realmId()) + || !playableStateNamespaceId.equals(request.playableStateNamespaceId()) + || !playableStateScope.equals(request.playableStateScope()) + || !canonicalGameInstanceId.equals(request.canonicalGameInstanceId()) + || !canonicalVersionId.equals(request.canonicalVersionId()) + || activeLifecycleEpoch != request.activeLifecycleEpoch() + || originKind != request.originKind() + || expectedCatalogRevision != request.expectedCatalogRevision() + || !Objects.equals(expectedPriorPointerVersion, request.expectedPriorPointerVersion()) + || !holdId.equals(request.holdId()) + || !holdFence.equals(request.holdFence()) + || !holdBindingDigest.equals(request.holdBindingDigest())) { + throw new IllegalArgumentException( + "World ACTIVE/hold proof does not match the exact initial admission request"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPublishedPlayerRoute.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPublishedPlayerRoute.java new file mode 100644 index 0000000000..34b196e6d0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalPublishedPlayerRoute.java @@ -0,0 +1,39 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; + +/** + * Source-only current route plus its exact selected row from Game Design's complete sealed policy + * set. This evidence is not gameplay admission or actor-entry authorization. + */ +public record CanonicalPublishedPlayerRoute( + CanonicalPlayableTarget route, + PublishedRealmEntryPolicySetEvidence policySetEvidence, + PublishedRealmEntryPolicyEvidence selectedPolicyEvidence) { + public CanonicalPublishedPlayerRoute { + Objects.requireNonNull(route, "route"); + Objects.requireNonNull(policySetEvidence, "policySetEvidence"); + Objects.requireNonNull(selectedPolicyEvidence, "selectedPolicyEvidence"); + RealmEntryPolicy policy = selectedPolicyEvidence.policy(); + if (!policySetEvidence.policies().contains(selectedPolicyEvidence) + || !policySetEvidence.target().canonicalTenantId().equals(route.canonicalTenantId()) + || !policySetEvidence.target().canonicalVersionId().equals(route.canonicalVersionId()) + || !policy.worldSlug().equals(route.worldSlug()) + || !policy.realmSlug().equals(route.realmSlug()) + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !"SHARED".equals(route.playableStateScope())) { + throw new IllegalArgumentException( + "Selected PRESEEDED_ONLY policy does not belong to the exact public route and set"); + } + } + + public RealmEntryPolicy entryPolicy() { + return selectedPolicyEvidence.policy(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java new file mode 100644 index 0000000000..c6ddb1c37e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalRealmCatalogSnapshot.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Immutable catalog evidence for one public-production realm; it is not admission authority. */ +public record CanonicalRealmCatalogSnapshot( + String targetNamespace, + UUID tenantId, + String tenantSlug, + String worldSlug, + UUID realmId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + UUID playableStateNamespaceId, + String characterCreationPolicy, + long catalogRevision, + UUID creationRequestId, + String requestDigest, + String receiptDigest, + IntakeReceipt sourceIntakeReceipt) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CanonicalRealmCatalogSnapshot { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + requireNonNil(tenantId, "tenantId"); + Objects.requireNonNull(tenantSlug, "tenantSlug"); + Objects.requireNonNull(worldSlug, "worldSlug"); + requireNonNil(realmId, "realmId"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + Objects.requireNonNull(stateScope, "stateScope"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + requireNonNil(creationRequestId, "creationRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + if (!visible || !publicProduction || catalogRevision != 1L) { + throw new IllegalArgumentException("Unsupported canonical initial realm catalog state"); + } + var source = sourceIntakeReceipt.source(); + if (!targetNamespace.equals(source.targetNamespace()) + || !tenantId.equals(source.canonicalTenantId()) + || !tenantSlug.equals(source.tenantSlug()) + || !worldSlug.equals(source.worldSlug())) { + throw new IllegalArgumentException( + "Catalog selectors do not match the persisted authored-world source receipt"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java new file mode 100644 index 0000000000..c07f92c6e1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalClosedAdmissionPointerRequest.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Local audit inputs for one immutable initial canonical CLOSED admission pointer. */ +public record CreateCanonicalClosedAdmissionPointerRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + String actorPrincipal, + String reason) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalClosedAdmissionPointerRequest { + requireNonNil(requestId, "requestId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + validateBoundedText(actorPrincipal, "actorPrincipal", 200, 800); + validateBoundedText(reason, "reason", 500, 2000); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void validateBoundedText( + String value, String name, int maximumCodePoints, int maximumUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() + || value.codePointCount(0, value.length()) > maximumCodePoints + || bytes.length > maximumUtf8Bytes) { + throw new IllegalArgumentException(name + " must be bounded and nonblank"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java new file mode 100644 index 0000000000..8bee96d53e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalRealmCatalogRequest.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.gamesession.dto; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.lang.Nullable; + +/** Explicit input for one immutable public-production realm catalog creation. */ +public record CreateCanonicalRealmCatalogRequest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + @Nullable UUID playtestLifecycleId, + @Nullable Long playtestStateGeneration) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "The two nullable lifecycle fields are rejected when supplied; null is their required ABSENT state for initial public production.") + public CreateCanonicalRealmCatalogRequest { + requireNonNil(requestId, "requestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + Objects.requireNonNull(realmSlug, "realmSlug"); + if (realmSlug.isBlank() || strictUtf8(realmSlug, "realmSlug").length > 120) { + throw new IllegalArgumentException( + "realmSlug must be a nonblank selector of at most 120 UTF-8 bytes"); + } + Objects.requireNonNull(realmDisplayName, "realmDisplayName"); + if (realmDisplayName.isBlank() + || realmDisplayName.codePointCount(0, realmDisplayName.length()) > 100 + || strictUtf8(realmDisplayName, "realmDisplayName").length > 400) { + throw new IllegalArgumentException("realmDisplayName must be bounded and nonblank"); + } + if (!visible || !publicProduction) { + throw new IllegalArgumentException( + "Initial canonical realm creation requires visible public production"); + } + if (!"SHARED".equals(stateScope) && !"ISOLATED".equals(stateScope)) { + throw new IllegalArgumentException("stateScope must be exactly SHARED or ISOLATED"); + } + Objects.requireNonNull(characterCreationPolicy, "characterCreationPolicy"); + if (characterCreationPolicy.isBlank() + || characterCreationPolicy.codePointCount(0, characterCreationPolicy.length()) > 64 + || strictUtf8(characterCreationPolicy, "characterCreationPolicy").length > 256) { + throw new IllegalArgumentException( + "characterCreationPolicy must be an explicit bounded nonblank owner value"); + } + if (playtestLifecycleId != null || playtestStateGeneration != null) { + throw new IllegalArgumentException( + "Initial public-production creation cannot carry private/playtest lifecycle evidence"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8 text", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java new file mode 100644 index 0000000000..5ba3c50e1c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigest.java @@ -0,0 +1,262 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; + +/** Closed canonical bytes for the owner-resolved current OPEN pointer projection. */ +final class CanonicalCurrentOpenPointerSnapshotDigest { + static final String DOMAIN = "gs-canonical-current-open-pointer-snapshot/v1"; + + private static final int MAX_STRING_BYTES = 4096; + private static final Pattern REQUEST_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern OWNER_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String AUDIT_ACTOR = "game-session-canonical-initial-admission"; + private static final String AUDIT_REASON = "World-held initial admission"; + + private CanonicalCurrentOpenPointerSnapshotDigest() {} + + static String digest(Projection projection) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(canonicalBytes(projection))); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + static byte[] canonicalBytes(Projection projection) { + Objects.requireNonNull(projection, "projection"); + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writeString(output, DOMAIN); + output.writeInt(projection.representationVersion()); + writeString(output, projection.targetNamespace()); + writeUuid(output, projection.canonicalTenantId()); + writeString(output, projection.worldSlug()); + writeString(output, projection.worldDisplayName()); + writeUuid(output, projection.realmId()); + writeString(output, projection.realmSlug()); + writeString(output, projection.realmDisplayName()); + writeUuid(output, projection.playableStateNamespaceId()); + writeString(output, projection.playableStateScope()); + writeCounter(output, projection.catalogRevision()); + writeCounter(output, projection.pointerVersion()); + writeString(output, projection.admissionState()); + output.writeBoolean(projection.visible()); + output.writeBoolean(projection.publicProductionRealm()); + writeNullableBoolean(output, projection.requiresCharacterSelection()); + writeString(output, projection.characterCreationPolicy()); + writeUuid(output, projection.canonicalGameInstanceId()); + writeUuid(output, projection.canonicalVersionId()); + writeString(output, projection.initialAdmissionRequestId()); + writeString(output, projection.initialAdmissionRequestDigest()); + writeString(output, projection.originKind().name()); + writeNullableLong(output, projection.expectedPriorPointerVersion()); + writeCounter(output, projection.activeWorldEpoch()); + writeUuid(output, projection.holdId()); + writeUuid(output, projection.holdFence()); + writeString(output, projection.holdBindingDigest()); + writeString(output, projection.lastUpdatedBy()); + writeString(output, projection.lastUpdateReason()); + writeString(output, projection.preparedVersionUpgradeId()); + writeString(output, "COMMITTED"); + writeString(output, projection.ownerProofDigest()); + writeCounter(output, projection.auditEventId()); + writeString(output, projection.terminalAt().toString()); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Canonical pointer snapshot encoding failed", impossible); + } + } + + private static void writeUuid(DataOutputStream output, UUID value) throws IOException { + writeString(output, Objects.requireNonNull(value, "UUID").toString()); + } + + /** Strings are exact UTF-8 with a signed 32-bit byte count; -1 is the sole null marker. */ + private static void writeString(DataOutputStream output, String value) throws IOException { + if (value == null) { + output.writeInt(-1); + return; + } + byte[] encoded = strictUtf8(value); + if (encoded.length > MAX_STRING_BYTES) { + throw new IllegalArgumentException("Canonical snapshot string exceeds its byte bound"); + } + output.writeInt(encoded.length); + output.write(encoded); + } + + private static byte[] strictUtf8(String value) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException invalid) { + throw new IllegalArgumentException("Canonical snapshot string is not valid Unicode", invalid); + } + } + + private static void writeNullableBoolean(DataOutputStream output, Boolean value) + throws IOException { + output.writeByte(value == null ? 0 : value ? 2 : 1); + } + + private static void writeNullableLong(DataOutputStream output, Long value) throws IOException { + output.writeBoolean(value != null); + if (value != null) { + writeCounter(output, value); + } + } + + /** Long counters use their unique, nonlocalized base-10 representation. */ + private static void writeCounter(DataOutputStream output, long value) throws IOException { + writeString(output, Long.toString(value)); + } + + /** Values are copied from one validated V3 OPEN row and its exact terminal owner readback. */ + record Projection( + int representationVersion, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + String worldDisplayName, + UUID realmId, + String realmSlug, + String realmDisplayName, + UUID playableStateNamespaceId, + String playableStateScope, + long catalogRevision, + long pointerVersion, + String admissionState, + boolean visible, + boolean publicProductionRealm, + Boolean requiresCharacterSelection, + String characterCreationPolicy, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + String initialAdmissionRequestId, + String initialAdmissionRequestDigest, + OriginKind originKind, + Long expectedPriorPointerVersion, + long activeWorldEpoch, + UUID holdId, + UUID holdFence, + String holdBindingDigest, + String lastUpdatedBy, + String lastUpdateReason, + String preparedVersionUpgradeId, + String ownerProofDigest, + long auditEventId, + Instant terminalAt) { + @SuppressFBWarnings( + value = "NP_LOAD_OF_KNOWN_NULL_VALUE", + justification = + "Canonical OPEN projection requires absent selection and upgrade fields; the record stores those validated nulls without dereferencing them.") + Projection { + if (originKind == null) { + throw new IllegalArgumentException("Current OPEN pointer snapshot origin is required"); + } + OriginKind validatedOriginKind = originKind; + if (representationVersion != 3 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !nonNil(canonicalTenantId) + || !RealmEntryPolicy.isCanonicalSlug(worldSlug) + || !text(worldDisplayName, 200) + || !nonNil(realmId) + || !RealmEntryPolicy.isCanonicalSlug(realmSlug) + || !text(realmDisplayName, 200) + || !nonNil(playableStateNamespaceId) + || !"SHARED".equals(playableStateScope) + || catalogRevision <= 0L + || pointerVersion <= 0L + || !"OPEN".equals(admissionState) + || !visible + || !publicProductionRealm + || requiresCharacterSelection != null + || !text(characterCreationPolicy, 32) + || !nonNil(canonicalGameInstanceId) + || !nonNil(canonicalVersionId) + || !text(initialAdmissionRequestId, 120) + || !REQUEST_DIGEST + .matcher(Objects.requireNonNull(initialAdmissionRequestDigest)) + .matches() + || (validatedOriginKind == OriginKind.NO_PRIOR_POINTER + && expectedPriorPointerVersion != null) + || (validatedOriginKind == OriginKind.EXPECT_CLOSED + && (expectedPriorPointerVersion == null || expectedPriorPointerVersion <= 0L)) + || activeWorldEpoch <= 0L + || !nonNil(holdId) + || !nonNil(holdFence) + || !OWNER_DIGEST.matcher(Objects.requireNonNull(holdBindingDigest)).matches() + || !AUDIT_ACTOR.equals(lastUpdatedBy) + || !AUDIT_REASON.equals(lastUpdateReason) + || preparedVersionUpgradeId != null + || !OWNER_DIGEST.matcher(Objects.requireNonNull(ownerProofDigest)).matches() + || auditEventId <= 0L + || terminalAt == null + || terminalAt.getNano() % 1_000 != 0) { + throw new IllegalArgumentException( + "Current OPEN pointer snapshot is incomplete or invalid"); + } + // Reject malformed UTF-16 rather than allowing replacement-byte collisions in the digest. + for (String value : + new String[] { + targetNamespace, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + playableStateScope, + admissionState, + characterCreationPolicy, + initialAdmissionRequestId, + initialAdmissionRequestDigest, + validatedOriginKind.name(), + holdBindingDigest, + lastUpdatedBy, + lastUpdateReason, + ownerProofDigest + }) { + strictUtf8(value); + } + } + + private static boolean nonNil(UUID value) { + return value != null && !NIL_UUID.equals(value); + } + + private static boolean text(String value, int maxChars) { + return value != null + && !value.isBlank() + && value.equals(value.trim()) + && value.length() <= maxChars; + } + } +} 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 new file mode 100644 index 0000000000..c9600a515d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -0,0 +1,732 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +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.tenant.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.jooq.JSONB; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.JacksonException; +import tools.jackson.databind.ObjectMapper; + +/** Explicit Game Session owner persistence for the exact launch-to-instance binding. */ +public final class CanonicalGameInstanceLaunchAssociationRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ASSOCIATION_TABLE = "game_session_canonical_instance_launch"; + + private final DSLContext dsl; + private final String workloadNamespace; + + public CanonicalGameInstanceLaunchAssociationRepository( + DSLContext dsl, String workloadNamespace) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * 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. + */ + public CanonicalGameInstanceLaunchAssociation capture( + FreshGameSessionTenantAssociation tenantAssociation, + long gameInstanceId, + CompleteLaunchBindingEvidence launchBindingEvidence) { + requireWritableReadCommittedOwnerTransaction(); + Objects.requireNonNull(tenantAssociation, "tenantAssociation"); + requirePositive(gameInstanceId, "gameInstanceId"); + ValidatedBinding binding = validateBinding(launchBindingEvidence); + if (!workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new IllegalArgumentException("Launch binding targets another Game Session namespace"); + } + + RuntimeTenantIdentityEvidence source = tenantAssociation.sourceEvidence(); + requireFreshSourceIdentity(tenantAssociation, source); + if (!binding.descriptor().canonicalTenantId().equals(source.canonicalTenantId())) { + throw new IllegalArgumentException("Launch binding does not match its fresh tenant owner"); + } + + lockRequest(binding.descriptor().controlPlaneRequestId()); + FreshTenantOwnerMapping mapping = requireFreshTenantMapping(tenantAssociation); + GameInstanceRow runtime = + requireLockedRuntime(tenantAssociation.legacyGameSessionTenantId(), gameInstanceId); + RealmOwnerProjection realm = requirePublicSharedRealm(binding.descriptor()); + CanonicalGameInstanceLaunchAssociation existing = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElse(null); + if (existing != null) { + requireExactRetry( + existing, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return existing; + } + + requireStartingRuntime(runtime, binding.evidence()); + String evidenceJson = serializeEvidence(binding.evidence()); + RuntimeTenantIdentityEvidence sourceEvidence = tenantAssociation.sourceEvidence(); + dsl.execute( + "INSERT INTO " + + ASSOCIATION_TABLE + + " (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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, " + + "'SHARED', TRUE, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + workloadNamespace, + binding.descriptor().controlPlaneRequestId(), + tenantAssociation.legacyGameSessionTenantId(), + sourceEvidence.canonicalTenantId(), + mapping.operationId(), + sourceEvidence.requestId(), + sourceEvidence.schemaVersion(), + sourceEvidence.targetNamespace(), + sourceEvidence.requestId(), + sourceEvidence.canonicalTenantId(), + sourceEvidence.sourceGameRowId(), + sourceEvidence.sourceGameTenantKey(), + sourceEvidence.provenanceKind(), + gameInstanceId, + runtime.gameInstanceUuid(), + realm.realmId(), + binding.descriptor().worldSlug(), + realm.playableStateNamespaceId(), + runtime.rowVersion(), + binding.descriptor().gameTemplateId(), + binding.descriptor().launchDescriptorId(), + binding.descriptor().versionId(), + binding.descriptor().releaseBundleId(), + binding.descriptor().generationConfigRevision(), + binding.descriptor().versionStateEpoch(), + evidenceJson); + + CanonicalGameInstanceLaunchAssociation inserted = + findByRequest(binding.descriptor().controlPlaneRequestId(), true) + .map(this::toAssociation) + .orElseThrow( + () -> + new IllegalStateException( + "Canonical launch association insert readback is missing")); + requireExactRetry( + inserted, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); + return inserted; + } + + /** Serializes a STARTING-row producer on the exact namespace/request key used by capture. */ + public void lockRequestForStartingGameInstance(String controlPlaneRequestId) { + requireWritableReadCommittedOwnerTransaction(); + requireRequestId(controlPlaneRequestId); + lockRequest(controlPlaneRequestId); + } + + /** + * Reads one committed immutable owner association plus the transient current GameInstance row. + */ + public Optional read(String controlPlaneRequestId) { + requireOutsideTransaction(); + requireRequestId(controlPlaneRequestId); + return findByRequest(controlPlaneRequestId, false).map(this::toAssociation); + } + + /** Locks the exact canonical launch association and its current Game Session row. */ + public CanonicalInitialAdmissionLaunchTarget lockForInitialAdmission( + String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { + return lockForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, true); + } + + /** Locks the immutable launch owner and current row for an owner-local admission transaction. */ + public CanonicalInitialAdmissionLaunchTarget lockForInitialAdmission( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID canonicalGameInstanceId, + boolean requireRunning) { + requireWritableReadCommittedOwnerTransaction(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Initial admission targetNamespace does not match this Game Session owner"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = + findForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, true); + if (row == null) { + throw new IllegalStateException( + "Exact canonical launch association and current runtime row are unavailable"); + } + CanonicalGameInstanceLaunchAssociation association = toAssociation(row); + if ((requireRunning + && association.currentGameInstanceStatus() != CurrentGameInstanceStatus.RUNNING) + || !association.targetNamespace().equals(targetNamespace) + || !association.canonicalTenantId().equals(canonicalTenantId) + || !association.gameInstanceUuid().equals(canonicalGameInstanceId)) { + throw new IllegalStateException( + "Initial admission requires the exact canonical launch target in RUNNING state"); + } + return new CanonicalInitialAdmissionLaunchTarget( + association, + row.get("canonical_realm_id", UUID.class), + row.get("current_game_instance_id", Long.class), + row.get("current_version_id", Long.class)); + } + + /** Reads the exact launch association and current runtime row after owner commit. */ + public Optional readForInitialAdmission( + String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { + requireOutsideTransaction(); + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Initial admission targetNamespace does not match this Game Session owner"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(canonicalGameInstanceId, "canonicalGameInstanceId"); + Record row = + findForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, false); + if (row == null) { + return Optional.empty(); + } + CanonicalGameInstanceLaunchAssociation association = toAssociation(row); + return Optional.of( + new CanonicalInitialAdmissionLaunchTarget( + association, + row.get("canonical_realm_id", UUID.class), + row.get("current_game_instance_id", Long.class), + row.get("current_version_id", Long.class))); + } + + private Record findForInitialAdmission( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID canonicalGameInstanceId, + boolean forUpdate) { + return dsl.fetchOne( + "SELECT association.*, current.id AS current_game_instance_id, " + + "current.status AS current_status, current.row_version AS current_row_version, " + + "current.game_instance_uuid AS current_game_instance_uuid, " + + "current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, " + + "current.release_bundle_id AS current_release_bundle_id, " + + "current.generation_config_revision AS current_generation_config_revision, " + + "current.version_state_epoch AS current_version_state_epoch, " + + "current.run_owned_start_request_id AS current_run_owned_start_request_id, " + + "current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "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.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "WHERE association.target_namespace = ? " + + "AND association.canonical_tenant_id = ? " + + "AND association.canonical_realm_id = ? " + + "AND association.game_instance_uuid = ?" + + (forUpdate ? " FOR UPDATE OF association, current" : ""), + targetNamespace, + canonicalTenantId, + realmId, + canonicalGameInstanceId); + } + + private void lockRequest(String controlPlaneRequestId) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ?, 0))", + workloadNamespace, + controlPlaneRequestId); + } + + private GameInstanceRow requireLockedRuntime(long tenantId, long gameInstanceId) { + Record row = + dsl.fetchOne( + "SELECT id, tenant_id, game_instance_uuid, 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_published_release_bundle_ref FROM game_instances " + + "WHERE tenant_id = ? AND id = ? FOR UPDATE", + tenantId, + gameInstanceId); + if (row == null) { + throw new IllegalStateException("Game Session owner instance row is missing in tenant scope"); + } + return toRuntime(row, "status", "row_version"); + } + + private RealmOwnerProjection requirePublicSharedRealm( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { + Record row = + dsl.fetchOne( + "SELECT realm_id, playable_state_namespace_id, state_scope, public_production, visible " + + "FROM game_session_canonical_realm_catalog WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND world_slug = ? AND public_production = TRUE " + + "AND visible = TRUE", + workloadNamespace, + descriptor.canonicalTenantId(), + descriptor.worldSlug()); + if (row == null + || !Boolean.TRUE.equals(row.get("public_production", Boolean.class)) + || !Boolean.TRUE.equals(row.get("visible", Boolean.class)) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("state_scope", String.class))) { + throw new IllegalStateException( + "Canonical launch association requires the owner's visible public SHARED realm"); + } + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + UUID realmId = row.get("realm_id", UUID.class); + requireNonNil(namespaceId, "playableStateNamespaceId"); + requireNonNil(realmId, "canonicalRealmId"); + return new RealmOwnerProjection(realmId, namespaceId); + } + + private FreshTenantOwnerMapping requireFreshTenantMapping( + FreshGameSessionTenantAssociation expected) { + RuntimeTenantIdentityEvidence source = expected.sourceEvidence(); + Record row = + dsl.fetchOne( + "SELECT association.association_operation_id, association.association_request_id, " + + "association.source_schema_version, association.source_target_namespace, " + + "association.source_request_id, association.source_canonical_tenant_id, " + + "association.canonical_tenant_id, association.legacy_game_session_tenant_id, " + + "association.source_game_row_id, association.source_game_tenant_key, " + + "association.provenance_kind, association.association_kind, " + + "claim.association_operation_id AS claim_operation_id, " + + "claim.association_request_id AS claim_request_id, " + + "claim.association_kind AS claim_kind, claim.reservation_kind AS claim_reservation_kind, " + + "reservation.reservation_kind " + + "FROM game_session_fresh_tenant_association association " + + "JOIN game_session_tenant_canonical_claim claim ON " + + "claim.target_namespace = association.target_namespace " + + "AND claim.canonical_tenant_id = association.canonical_tenant_id " + + "AND claim.legacy_game_session_tenant_id = association.legacy_game_session_tenant_id " + + "AND claim.association_operation_id = association.association_operation_id " + + "AND claim.association_kind = association.association_kind " + + "JOIN game_session_tenant_scope_reservation reservation ON " + + "reservation.game_session_tenant_id = association.legacy_game_session_tenant_id " + + "WHERE association.target_namespace = ? AND association.association_operation_id = ?", + workloadNamespace, + expected.associationOperationId()); + if (row == null) { + throw new IllegalStateException( + "Persisted fresh Game Session tenant association is unavailable"); + } + UUID operationId = row.get("association_operation_id", UUID.class); + long localTenantId = row.get("legacy_game_session_tenant_id", Long.class); + if (!expected.associationOperationId().equals(operationId) + || localTenantId != expected.legacyGameSessionTenantId() + || !source.requestId().equals(row.get("association_request_id", UUID.class)) + || !source.requestId().equals(row.get("source_request_id", UUID.class)) + || source.schemaVersion() != row.get("source_schema_version", Integer.class) + || !source.targetNamespace().equals(row.get("source_target_namespace", String.class)) + || !source.canonicalTenantId().equals(row.get("source_canonical_tenant_id", UUID.class)) + || !source.canonicalTenantId().equals(row.get("canonical_tenant_id", UUID.class)) + || source.sourceGameRowId() != row.get("source_game_row_id", Long.class) + || !source.sourceGameTenantKey().equals(row.get("source_game_tenant_key", String.class)) + || !source.provenanceKind().equals(row.get("provenance_kind", String.class)) + || !operationId.equals(row.get("claim_operation_id", UUID.class)) + || !source.requestId().equals(row.get("claim_request_id", UUID.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("association_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("reservation_kind", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("claim_reservation_kind", String.class))) { + throw new IllegalStateException( + "Persisted fresh tenant source identity does not match its owner"); + } + return new FreshTenantOwnerMapping(operationId); + } + + private Optional findByRequest(String controlPlaneRequestId, boolean forUpdate) { + String sql = + "SELECT association.*, current.status AS current_status, " + + "current.row_version AS current_row_version, current.game_instance_uuid AS " + + "current_game_instance_uuid, current.game_template_id AS current_game_template_id, " + + "current.launch_descriptor_id AS current_launch_descriptor_id, " + + "current.version_id AS current_version_id, current.release_bundle_id AS " + + "current_release_bundle_id, current.generation_config_revision AS " + + "current_generation_config_revision, current.version_state_epoch AS " + + "current_version_state_epoch, current.run_owned_start_request_id AS " + + "current_run_owned_start_request_id, current.run_owned_start_published_release_bundle_ref " + + "AS current_run_owned_start_published_release_bundle_ref " + + "FROM " + + ASSOCIATION_TABLE + + " association JOIN game_instances current " + + "ON current.id = association.game_instance_id " + + "AND current.tenant_id = association.game_session_tenant_id " + + "JOIN game_session_canonical_realm_catalog realm " + + "ON realm.target_namespace = association.target_namespace " + + "AND realm.realm_id = association.canonical_realm_id " + + "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.visible = TRUE AND realm.public_production = TRUE " + + "AND realm.state_scope = 'SHARED' " + + "WHERE association.target_namespace = ? AND association.control_plane_request_id = ?" + + (forUpdate ? " FOR UPDATE OF association, current" : ""); + return Optional.ofNullable(dsl.fetchOne(sql, workloadNamespace, controlPlaneRequestId)); + } + + private CanonicalGameInstanceLaunchAssociation toAssociation(Record row) { + try { + CompleteLaunchBindingEvidence evidence = + JSON.readValue( + row.get("complete_launch_binding_evidence", JSONB.class).data(), + CompleteLaunchBindingEvidence.class); + ValidatedBinding binding = validateBinding(evidence); + UUID canonicalTenantId = row.get("canonical_tenant_id", UUID.class); + UUID associationOperationId = row.get("tenant_association_operation_id", UUID.class); + UUID gameInstanceUuid = row.get("game_instance_uuid", UUID.class); + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + Boolean publicProduction = row.get("public_production", Boolean.class); + if (!workloadNamespace.equals(row.get("target_namespace", String.class)) + || !"FRESH_SOURCE_BOUND".equals(row.get("tenant_association_kind", String.class)) + || !binding.descriptor().targetNamespace().equals(workloadNamespace) + || !binding + .descriptor() + .controlPlaneRequestId() + .equals(row.get("control_plane_request_id", String.class)) + || !canonicalTenantId.equals(binding.descriptor().canonicalTenantId()) + || !row.get("world_slug", String.class).equals(binding.descriptor().worldSlug()) + || !row.get("launch_descriptor_id", String.class) + .equals(binding.descriptor().launchDescriptorId()) + || row.get("game_template_id", Long.class) != binding.descriptor().gameTemplateId() + || row.get("version_id", Long.class) != binding.descriptor().versionId() + || row.get("release_bundle_id", Long.class) != binding.descriptor().releaseBundleId() + || !row.get("generation_config_revision", String.class) + .equals(binding.descriptor().generationConfigRevision()) + || row.get("version_state_epoch", Long.class) != binding.descriptor().versionStateEpoch() + || !Boolean.TRUE.equals(publicProduction)) { + throw new IllegalStateException( + "Persisted launch association contradicts its typed binding"); + } + RuntimeTenantIdentityEvidence source = sourceFromRow(row); + FreshGameSessionTenantAssociation mapping = + new FreshGameSessionTenantAssociation( + associationOperationId, row.get("game_session_tenant_id", Long.class), source); + requireFreshTenantMapping(mapping); + GameInstanceRow current = + new GameInstanceRow( + row.get("game_instance_id", Long.class), + row.get("game_session_tenant_id", Long.class), + row.get("current_game_instance_uuid", UUID.class), + row.get("current_status", String.class), + row.get("current_row_version", Long.class), + row.get("current_game_template_id", Long.class), + row.get("current_launch_descriptor_id", String.class), + row.get("current_version_id", Long.class), + row.get("current_release_bundle_id", Long.class), + row.get("current_generation_config_revision", String.class), + row.get("current_version_state_epoch", Long.class), + row.get("current_run_owned_start_request_id", String.class), + row.get("current_run_owned_start_published_release_bundle_ref", String.class)); + requireRuntimeBinding(current, evidence); + if (!gameInstanceUuid.equals(current.gameInstanceUuid()) + || current.rowVersion() < row.get("captured_starting_row_version", Long.class) + || !RealmEntryPolicy.StateScope.SHARED + .name() + .equals(row.get("playable_state_scope", String.class))) { + throw new IllegalStateException( + "Current Game Session row contradicts its launch association"); + } + return new CanonicalGameInstanceLaunchAssociation( + workloadNamespace, + row.get("game_session_tenant_id", Long.class), + associationOperationId, + canonicalTenantId, + gameInstanceUuid, + row.get("world_slug", String.class), + namespaceId, + RealmEntryPolicy.StateScope.SHARED, + true, + binding.descriptor().controlPlaneRequestId(), + binding.descriptor().launchDescriptorId(), + row.get("captured_starting_row_version", Long.class), + evidence, + CurrentGameInstanceStatus.valueOf(current.status()), + current.rowVersion()); + } catch (RuntimeException exception) { + if (exception instanceof IllegalStateException illegalState) { + throw illegalState; + } + throw new IllegalStateException( + "Persisted canonical launch association is malformed", exception); + } + } + + private static RuntimeTenantIdentityEvidence sourceFromRow(Record row) { + return new RuntimeTenantIdentityEvidence( + row.get("tenant_source_schema_version", Integer.class), + row.get("tenant_source_target_namespace", String.class), + row.get("tenant_source_request_id", UUID.class), + row.get("tenant_source_canonical_tenant_id", UUID.class), + row.get("tenant_source_game_row_id", Long.class), + row.get("tenant_source_game_tenant_key", String.class), + row.get("tenant_source_provenance_kind", String.class)); + } + + private void requireExactRetry( + CanonicalGameInstanceLaunchAssociation stored, + FreshGameSessionTenantAssociation expectedTenant, + long expectedGameInstanceId, + GameInstanceRow current, + CompleteLaunchBindingEvidence expectedEvidence, + FreshTenantOwnerMapping mapping, + RealmOwnerProjection realm) { + if (stored.gameSessionTenantId() != expectedTenant.legacyGameSessionTenantId() + || !stored.tenantAssociationOperationId().equals(mapping.operationId()) + || !stored.canonicalTenantId().equals(expectedTenant.sourceEvidence().canonicalTenantId()) + || !stored.playableStateNamespaceId().equals(realm.playableStateNamespaceId()) + || !stored.launchBindingEvidence().equals(expectedEvidence) + || !stored.gameInstanceUuid().equals(current.gameInstanceUuid()) + || stored.currentRowVersion() > current.rowVersion() + || stored.capturedStartingRowVersion() > current.rowVersion()) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused with a changed tenant, instance, or source binding"); + } + Record row = + dsl.fetchOne( + "SELECT game_instance_id FROM " + + ASSOCIATION_TABLE + + " WHERE target_namespace = ? AND control_plane_request_id = ?", + workloadNamespace, + stored.controlPlaneRequestId()); + if (row == null || row.get("game_instance_id", Long.class) != expectedGameInstanceId) { + throw new CanonicalGameInstanceLaunchAssociationConflictException( + "Launch association request was reused for another Game Session instance"); + } + requireRuntimeBinding(current, expectedEvidence); + } + + private static void requireStartingRuntime( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + requireRuntimeBinding(runtime, evidence); + if (!"STARTING".equals(runtime.status()) + || !evidence.descriptor().controlPlaneRequestId().equals(runtime.runOwnedStartRequestId()) + || !evidence + .descriptor() + .publishedReleaseBundleRef() + .equals(runtime.runOwnedStartPublishedReleaseBundleRef())) { + throw new IllegalStateException( + "Launch association capture requires the exact persisted run-owned STARTING instance"); + } + } + + private static void requireRuntimeBinding( + GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { + var descriptor = evidence.descriptor(); + if (runtime.id() <= 0 + || runtime.tenantId() <= 0 + || runtime.gameInstanceUuid() == null + || NIL_UUID.equals(runtime.gameInstanceUuid()) + || runtime.rowVersion() < 0 + || runtime.gameTemplateId() == null + || runtime.gameTemplateId() != descriptor.gameTemplateId() + || !Objects.equals(runtime.launchDescriptorId(), descriptor.launchDescriptorId()) + || runtime.versionId() == null + || runtime.versionId() != descriptor.versionId() + || runtime.releaseBundleId() == null + || runtime.releaseBundleId() != descriptor.releaseBundleId() + || runtime.versionStateEpoch() == null + || runtime.versionStateEpoch() != descriptor.versionStateEpoch() + || !Objects.equals( + runtime.generationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals(runtime.runOwnedStartRequestId(), descriptor.controlPlaneRequestId()) + || !Objects.equals( + runtime.runOwnedStartPublishedReleaseBundleRef(), + descriptor.publishedReleaseBundleRef())) { + throw new IllegalStateException( + "Game Session instance does not match the complete launch binding"); + } + try { + CurrentGameInstanceStatus.valueOf(runtime.status()); + } catch (RuntimeException invalidStatus) { + throw new IllegalStateException("Game Session instance status is unavailable", invalidStatus); + } + } + + private static GameInstanceRow toRuntime( + Record row, String statusColumn, String rowVersionColumn) { + return toRuntime( + row, + statusColumn, + rowVersionColumn, + "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_published_release_bundle_ref"); + } + + private static GameInstanceRow toRuntime( + Record row, + String statusColumn, + String rowVersionColumn, + String uuidColumn, + String templateColumn, + String descriptorColumn, + String versionColumn, + String bundleColumn, + String configColumn, + String epochColumn, + String requestColumn, + String publishedRefColumn) { + return new GameInstanceRow( + row.get("id", Long.class), + row.get("tenant_id", Long.class), + row.get(uuidColumn, UUID.class), + row.get(statusColumn, String.class), + row.get(rowVersionColumn, Long.class), + row.get(templateColumn, Long.class), + row.get(descriptorColumn, String.class), + row.get(versionColumn, Long.class), + row.get(bundleColumn, Long.class), + row.get(configColumn, String.class), + row.get(epochColumn, Long.class), + row.get(requestColumn, String.class), + row.get(publishedRefColumn, String.class)); + } + + private static ValidatedBinding validateBinding(CompleteLaunchBindingEvidence evidence) { + Objects.requireNonNull(evidence, "launchBindingEvidence"); + var descriptor = evidence.descriptor(); + descriptor.requireValid(); + evidence.releaseAttestation().requireValid(descriptor); + requireRequestId(descriptor.controlPlaneRequestId()); + return new ValidatedBinding(evidence); + } + + private void requireFreshSourceIdentity( + FreshGameSessionTenantAssociation association, RuntimeTenantIdentityEvidence evidence) { + if (evidence.schemaVersion() != 1 + || !workloadNamespace.equals(evidence.targetNamespace()) + || evidence.requestId() == null + || NIL_UUID.equals(evidence.requestId()) + || evidence.canonicalTenantId() == null + || NIL_UUID.equals(evidence.canonicalTenantId()) + || association.legacyGameSessionTenantId() <= 0 + || !"NEW_GAME_ROW".equals(evidence.provenanceKind())) { + throw new IllegalArgumentException( + "Only exact fresh NEW_GAME_ROW owner identity is supported"); + } + } + + private static String serializeEvidence(CompleteLaunchBindingEvidence evidence) { + try { + return JSON.writeValueAsString(evidence); + } catch (JacksonException exception) { + throw new IllegalStateException( + "Failed to persist complete launch binding evidence", exception); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical launch association capture requires a writable owner transaction"); + } + Record settings = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS transaction_isolation, " + + "current_setting('transaction_read_only') AS transaction_read_only"); + if (settings == null + || !"read committed".equals(settings.get("transaction_isolation", String.class)) + || !"off".equals(settings.get("transaction_read_only", String.class))) { + throw new IllegalStateException( + "Canonical launch association capture requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical launch association read requires a committed owner read"); + } + } + + private static void requireRequestId(String value) { + Objects.requireNonNull(value, "controlPlaneRequestId"); + if (value.isBlank() || value.length() > 128) { + throw new IllegalArgumentException("controlPlaneRequestId must contain 1 to 128 characters"); + } + } + + private static void requirePositive(long value, String label) { + if (value <= 0) { + throw new IllegalArgumentException(label + " must be positive"); + } + } + + private static void requireNonNil(UUID value, String label) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private record ValidatedBinding(CompleteLaunchBindingEvidence evidence) { + private net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + descriptor() { + return evidence.descriptor(); + } + } + + private record FreshTenantOwnerMapping(UUID operationId) {} + + private record RealmOwnerProjection(UUID realmId, UUID playableStateNamespaceId) {} + + private record GameInstanceRow( + long id, + long tenantId, + UUID gameInstanceUuid, + String status, + long rowVersion, + Long gameTemplateId, + String launchDescriptorId, + Long versionId, + Long releaseBundleId, + String generationConfigRevision, + Long versionStateEpoch, + String runOwnedStartRequestId, + String runOwnedStartPublishedReleaseBundleRef) {} + + public static final class CanonicalGameInstanceLaunchAssociationConflictException + extends RuntimeException { + public CanonicalGameInstanceLaunchAssociationConflictException(String message) { + super(message); + } + } +} 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 new file mode 100644 index 0000000000..3442966f06 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -0,0 +1,1472 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.ExpectedClosedEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository.PreparedExpectedClosed; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Durable Game Session owner transaction and exact readback for one canonical first-OPEN bind. */ +public class CanonicalInitialAdmissionRepository { + private static final String COMMITTED = "COMMITTED"; + private static final String PENDING = "PENDING"; + private static final String ABORTED = "ABORTED"; + private static final String AUDIT_ACTOR = "game-session-canonical-initial-admission"; + private static final String AUDIT_REASON = "World-held initial admission"; + private static final String COMMIT_PROOF_DOMAIN = + "gs-canonical-initial-admission-commit-proof/v1"; + private static final String ABORT_PROOF_DOMAIN = "gs-canonical-initial-admission-abort-proof/v1"; + private static final String OPERATION_TABLE = "game_session_canonical_initial_admission_attempt"; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + + /** One exact current pointer row plus its validated owner result and GS-owned snapshot digest. */ + public record CurrentOpenSnapshot( + CanonicalInitialAdmissionOwnerProof ownerProof, String admissionPointerSnapshotDigest) { + private static final java.util.regex.Pattern SNAPSHOT_DIGEST = + java.util.regex.Pattern.compile("[0-9a-f]{64}"); + + public CurrentOpenSnapshot { + Objects.requireNonNull(ownerProof, "ownerProof"); + if (!ownerProof.provesCommit() + || admissionPointerSnapshotDigest == null + || !SNAPSHOT_DIGEST.matcher(admissionPointerSnapshotDigest).matches()) { + throw new IllegalArgumentException( + "Current OPEN snapshot requires committed owner proof and raw SHA-256 digest"); + } + } + } + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected owner collaborators are validated before use; construction acquires no resources.") + public CanonicalInitialAdmissionRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); + this.launchRepository = Objects.requireNonNull(launchRepository, "launchRepository"); + this.eventRepository = Objects.requireNonNull(eventRepository, "eventRepository"); + } + + /** Persists the immutable request identity before remote World verification is attempted. */ + @Transactional(isolation = Isolation.READ_COMMITTED) + 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; + } + 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"); + } + + 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"); + } + } + + /** + * Commits the first pointer, append-only audit and terminal owner result in one short + * transaction. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void commit( + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionWorldProof worldProof, + PreparedExpectedClosed preparedExpectedClosed) { + 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"); + } + } + + /** + * Records a terminal local abort only while the exact expected prior authority is still current. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public void abort( + CanonicalInitialAdmissionRequest request, + PreparedExpectedClosed preparedExpectedClosed, + String reason) { + 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"); + } + } + + /** Reads the exact durable result only after the owner transaction has committed. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + String targetNamespace, String initialAdmissionRequestId) { + requireOutsideTransaction(); + Record row = findAttemptRecord(targetNamespace, initialAdmissionRequestId, false); + if (row == null) { + return Optional.empty(); + } + Attempt attempt = toAttempt(row); + if (PENDING.equals(attempt.status())) { + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.PENDING)); + } + if (COMMITTED.equals(attempt.status())) { + verifyCommittedReadback(attempt); + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED)); + } + if (ABORTED.equals(attempt.status())) { + verifyAbortReadback(attempt); + return Optional.of(toProof(attempt, CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)); + } + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Persisted initial-admission attempt has an unsupported owner outcome"); + } + + /** + * Reads the current canonical OPEN pointer and its exact committed initial-admission proof. This + * is a point-in-time owner read, not an authorization held through a later mutation. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CanonicalInitialAdmissionOwnerProof readCurrentOpenForRealm( + String targetNamespace, UUID canonicalTenantUuid, UUID realmUuid) { + return readCurrentOpenSnapshotForRealm(targetNamespace, canonicalTenantUuid, realmUuid) + .ownerProof(); + } + + /** + * Reads the exact current canonical OPEN pointer and its committed proof as one owner snapshot. + * The digest commits to the validated current pointer projection, not the owner's commit-proof + * digest or a caller-provided echo. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( + String targetNamespace, UUID canonicalTenantUuid, UUID realmUuid) { + requireOutsideTransaction(); + requireCurrentOpenReadSelector(targetNamespace, canonicalTenantUuid, realmUuid); + + CurrentOpenPointer before = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + before.requireCanonicalOpen(targetNamespace, canonicalTenantUuid, realmUuid); + String requestId = before.initialAdmissionRequestId(); + if (requestId == null || requestId.isBlank()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer has no initial-admission request identity"); + } + + CanonicalInitialAdmissionOwnerProof proof = + read(targetNamespace, requestId) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer has no durable owner attempt")); + if (!proof.provesCommit() || !before.matches(proof)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer does not match its exact committed owner proof"); + } + + CurrentOpenPointer after = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + if (!before.equals(after)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer changed during owner readback"); + } + return new CurrentOpenSnapshot(proof, before.snapshotDigest(proof)); + } + + private CurrentOpenPointer readCurrentOpenPointer( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + List rows = + dsl.fetch( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "AND representation_version = 3 AND admission_state = 'OPEN'", + targetNamespace, + canonicalTenantId, + realmId); + if (rows.size() != 1) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical realm must have exactly one current representation-version-3 OPEN pointer"); + } + return CurrentOpenPointer.from(rows.get(0)); + } + + private static void requireCurrentOpenReadSelector( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + if (targetNamespace == null || !GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace is not a canonical owner selector"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + 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"); + } + } + + 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"); + } + 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"); + } + return pointer.get("id", Long.class); + } + + private void verifyCommittedReadback(Attempt attempt) { + CanonicalInitialAdmissionRequest request = attempt.asRequest(); + CanonicalRealmCatalogSnapshot catalog = readExactCatalog(request); + Record evidence = + dsl.fetchOne( + "SELECT pointer.*, pointer.updated_at AS pointer_updated_at, " + + "event.id AS committed_audit_event_id, event.occurred_at AS audit_at, " + + "event.actor_principal AS audit_actor, event.reason AS audit_reason, " + + "event.target_namespace AS audit_target_namespace, " + + "event.canonical_tenant_id AS audit_canonical_tenant_id, " + + "event.world_slug AS audit_world_slug, event.realm_id AS audit_realm_id, " + + "event.world_display_name AS audit_world_display_name, " + + "event.realm_slug AS audit_realm_slug, " + + "event.realm_display_name AS audit_realm_display_name, " + + "event.playable_state_namespace_id AS audit_playable_state_namespace_id, " + + "event.state_scope AS audit_state_scope, " + + "event.visible AS audit_visible, " + + "event.public_production_realm AS audit_public_production_realm, " + + "event.character_creation_policy AS audit_character_creation_policy, " + + "event.requires_character_selection AS audit_requires_character_selection, " + + "event.canonical_game_instance_id AS audit_canonical_game_instance_id, " + + "event.initial_admission_request_digest AS audit_request_digest, " + + "event.initial_admission_request_id AS audit_request_id, " + + "event.canonical_version_id AS audit_canonical_version_id, " + + "event.runtime_version_id AS audit_runtime_version_id, " + + "event.initial_admission_origin_kind AS audit_origin_kind, " + + "event.initial_admission_prior_pointer_version AS audit_prior_pointer_version, " + + "event.initial_admission_active_epoch AS audit_active_epoch, " + + "event.initial_admission_hold_id AS audit_hold_id, " + + "event.initial_admission_hold_fence AS audit_hold_fence, " + + "event.initial_admission_hold_binding_digest AS audit_hold_binding_digest, " + + "event.tenant_id AS audit_game_session_tenant_id, " + + "event.game_instance_id AS audit_game_instance_id, " + + "event.pointer_version AS audit_pointer_version, " + + "event.catalog_revision AS audit_catalog_revision, " + + "event.control_plane_request_id AS audit_control_plane_request_id, " + + "event.admission_state AS audit_admission_state " + + "FROM gameplay_admission_pointer pointer JOIN gameplay_admission_pointer_event event " + + "ON event.id = ? AND event.representation_version = 3 " + + "AND event.target_namespace = pointer.target_namespace " + + "AND event.canonical_tenant_id = pointer.canonical_tenant_id " + + "AND event.realm_id = pointer.realm_id " + + "AND event.pointer_version = pointer.pointer_version " + + "AND event.initial_admission_request_id = pointer.initial_admission_request_id " + + "WHERE pointer.id = ? AND pointer.representation_version = 3", + attempt.auditEventId(), + attempt.pointerId()); + if (evidence == null + || !attempt.targetNamespace().equals(evidence.get("target_namespace", String.class)) + || !attempt.targetNamespace().equals(evidence.get("audit_target_namespace", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("initial_admission_request_id", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("audit_request_id", String.class)) + || !attempt + .requestDigest() + .equals(evidence.get("initial_admission_request_digest", String.class)) + || !attempt.requestDigest().equals(evidence.get("audit_request_digest", String.class)) + || !attempt.canonicalTenantId().equals(evidence.get("canonical_tenant_id", UUID.class)) + || !attempt + .canonicalTenantId() + .equals(evidence.get("audit_canonical_tenant_id", UUID.class)) + || !attempt.worldSlug().equals(evidence.get("audit_world_slug", String.class)) + || !attempt.realmId().equals(evidence.get("realm_id", UUID.class)) + || !attempt.realmId().equals(evidence.get("audit_realm_id", UUID.class)) + || !catalog + .sourceIntakeReceipt() + .source() + .worldDisplayName() + .equals(evidence.get("world_display_name", String.class)) + || !catalog + .sourceIntakeReceipt() + .source() + .worldDisplayName() + .equals(evidence.get("audit_world_display_name", String.class)) + || !catalog.realmSlug().equals(evidence.get("audit_realm_slug", String.class)) + || !catalog.realmDisplayName().equals(evidence.get("realm_display_name", String.class)) + || !catalog + .realmDisplayName() + .equals(evidence.get("audit_realm_display_name", String.class)) + || !attempt + .playableStateNamespaceId() + .equals(evidence.get("playable_state_namespace_id", UUID.class)) + || !attempt + .playableStateNamespaceId() + .equals(evidence.get("audit_playable_state_namespace_id", UUID.class)) + || !attempt.playableStateScope().equals(evidence.get("state_scope", String.class)) + || !attempt.playableStateScope().equals(evidence.get("audit_state_scope", String.class)) + || !Boolean.valueOf(catalog.visible()).equals(evidence.get("visible", Boolean.class)) + || !Boolean.valueOf(catalog.visible()).equals(evidence.get("audit_visible", Boolean.class)) + || !Boolean.valueOf(catalog.publicProduction()) + .equals(evidence.get("public_production_realm", Boolean.class)) + || !Boolean.valueOf(catalog.publicProduction()) + .equals(evidence.get("audit_public_production_realm", Boolean.class)) + || !catalog + .characterCreationPolicy() + .equals(evidence.get("character_creation_policy", String.class)) + || !catalog + .characterCreationPolicy() + .equals(evidence.get("audit_character_creation_policy", String.class)) + || evidence.get("requires_character_selection", Boolean.class) != null + || evidence.get("audit_requires_character_selection", Boolean.class) != null + || !attempt + .canonicalGameInstanceId() + .equals(evidence.get("canonical_game_instance_id", UUID.class)) + || !attempt + .canonicalGameInstanceId() + .equals(evidence.get("audit_canonical_game_instance_id", UUID.class)) + || !attempt.canonicalVersionId().equals(evidence.get("canonical_version_id", UUID.class)) + || attempt.runtimeVersionId() != evidence.get("runtime_version_id", Long.class) + || !attempt + .canonicalVersionId() + .equals(evidence.get("audit_canonical_version_id", UUID.class)) + || attempt.runtimeVersionId() != evidence.get("audit_runtime_version_id", Long.class) + || attempt.gameSessionTenantId() != evidence.get("tenant_id", Long.class) + || attempt.gameSessionTenantId() != evidence.get("audit_game_session_tenant_id", Long.class) + || attempt.gameInstanceId() != evidence.get("game_instance_id", Long.class) + || attempt.gameInstanceId() != evidence.get("audit_game_instance_id", Long.class) + || attempt.pointerVersion() != evidence.get("pointer_version", Long.class) + || attempt.pointerVersion() != evidence.get("audit_pointer_version", Long.class) + || attempt.expectedCatalogRevision() != evidence.get("catalog_revision", Long.class) + || attempt.expectedCatalogRevision() != evidence.get("audit_catalog_revision", Long.class) + || !"OPEN".equals(evidence.get("admission_state", String.class)) + || !"OPEN".equals(evidence.get("audit_admission_state", String.class)) + || attempt.originKind() + != CanonicalInitialAdmissionRequest.OriginKind.valueOf( + evidence.get("initial_admission_origin_kind", String.class)) + || attempt.originKind() + != CanonicalInitialAdmissionRequest.OriginKind.valueOf( + evidence.get("audit_origin_kind", String.class)) + || !Objects.equals( + attempt.expectedPriorPointerVersion(), + evidence.get("initial_admission_prior_pointer_version", Long.class)) + || !Objects.equals( + attempt.expectedPriorPointerVersion(), + evidence.get("audit_prior_pointer_version", Long.class)) + || attempt.activeLifecycleEpoch() + != evidence.get("initial_admission_active_epoch", Long.class) + || attempt.activeLifecycleEpoch() != evidence.get("audit_active_epoch", Long.class) + || !attempt.holdId().equals(evidence.get("initial_admission_hold_id", UUID.class)) + || !attempt.holdId().equals(evidence.get("audit_hold_id", UUID.class)) + || !attempt.holdFence().equals(evidence.get("initial_admission_hold_fence", UUID.class)) + || !attempt.holdFence().equals(evidence.get("audit_hold_fence", UUID.class)) + || !attempt + .holdBindingDigest() + .equals(evidence.get("initial_admission_hold_binding_digest", String.class)) + || !AUDIT_ACTOR.equals(evidence.get("audit_actor", String.class)) + || !AUDIT_REASON.equals(evidence.get("audit_reason", String.class)) + || !attempt + .holdBindingDigest() + .equals(evidence.get("audit_hold_binding_digest", String.class)) + || !attempt + .initialAdmissionRequestId() + .equals(evidence.get("audit_control_plane_request_id", String.class)) + || !attempt + .terminalAt() + .equals(toInstant(evidence.get("pointer_updated_at", java.time.LocalDateTime.class))) + || !attempt + .terminalAt() + .equals(toInstant(evidence.get("audit_at", java.time.LocalDateTime.class))) + || !catalog.worldSlug().equals(evidence.get("world_slug", String.class)) + || !catalog.realmSlug().equals(evidence.get("realm_slug", String.class)) + || !catalog + .playableStateNamespaceId() + .equals(evidence.get("playable_state_namespace_id", UUID.class))) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Committed initial-admission pointer, audit, request and catalog readback disagree"); + } + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { + verifyOriginalClosedOrigin(attempt, false); + } + String expectedProof = + commitProofDigest( + attempt, + attempt.pointerVersion(), + attempt.auditEventId(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId()); + if (!expectedProof.equals(attempt.commitProofDigest())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Committed initial-admission proof digest does not match the durable result"); + } + } + + private void verifyAbortReadback(Attempt attempt) { + readExactCatalog(attempt.asRequest()); + if (attempt.pointerId() != null + || attempt.pointerVersion() != null + || attempt.auditEventId() != null + || attempt.abortProofDigest() == null + || attempt.commitProofDigest() != null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Durable ABORTED attempt contains contradictory pointer evidence"); + } + if (hasAttemptPointerEvidence(attempt)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "ABORTED initial-admission request unexpectedly has pointer or audit evidence"); + } + if (attempt.originKind() == CanonicalInitialAdmissionRequest.OriginKind.EXPECT_CLOSED) { + // 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); + } + String expectedProof = + abortProofDigest( + attempt, + attempt.abortReason(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId()); + if (!expectedProof.equals(attempt.abortProofDigest())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Durable ABORTED proof digest does not match the fenced result"); + } + } + + private void verifyOriginalClosedOrigin(Attempt attempt, boolean requireCurrent) { + if (attempt.priorPointerRequestId() == null + || attempt.priorPointerRequestDigest() == null + || attempt.priorPointerAuditEventId() == null + || !Long.valueOf(1L).equals(attempt.expectedPriorPointerVersion())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "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())) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + requireCurrent + ? "Original CLOSED route is no longer current owner authority" + : "Immutable original CLOSED request/event evidence is unavailable")); + if (!origin.canonicalTenantId().equals(attempt.canonicalTenantId()) + || !origin.realmId().equals(attempt.realmId()) + || !origin.requestDigest().equals(attempt.priorPointerRequestDigest()) + || origin.auditEventId() != attempt.priorPointerAuditEventId() + || origin.pointerVersion() != attempt.expectedPriorPointerVersion() + || origin.catalogRevision() != attempt.expectedCatalogRevision()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Original CLOSED request/event proof changed or no longer matches the attempt"); + } + } + + private boolean hasAttemptPointerEvidence(Attempt attempt) { + Record exists = + dsl.fetchOne( + "SELECT EXISTS (" + + "SELECT 1 FROM gameplay_admission_pointer WHERE representation_version = 3 " + + "AND target_namespace = ? AND initial_admission_request_id = ? " + + "UNION ALL SELECT 1 FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 3 AND target_namespace = ? " + + "AND initial_admission_request_id = ?) AS represented", + attempt.targetNamespace(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.initialAdmissionRequestId()); + return exists == null || !Boolean.FALSE.equals(exists.get("represented", Boolean.class)); + } + + private CanonicalRealmCatalogSnapshot readExactCatalog(CanonicalInitialAdmissionRequest request) { + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRealm(request.targetNamespace(), request.canonicalTenantId(), request.realmId()) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Exact canonical realm catalog is unavailable for owner readback")); + requireRequestMatchesCatalog(request, catalog); + return catalog; + } + + private CanonicalInitialAdmissionLaunchTarget readExactLaunchTarget( + CanonicalInitialAdmissionRequest request) { + CanonicalInitialAdmissionLaunchTarget target = + launchRepository + .readForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()) + .orElseThrow( + () -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Exact canonical launch association is unavailable for owner readback")); + requireRequestMatchesLaunch(request, target); + return target; + } + + private CanonicalRealmCatalogSnapshot lockCatalog(CanonicalInitialAdmissionRequest request) { + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockInitialAdmissionTarget( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.expectedCatalogRevision()); + requireRequestMatchesCatalog(request, catalog); + return catalog; + } + + private CanonicalInitialAdmissionLaunchTarget lockLaunchTarget( + CanonicalInitialAdmissionRequest request, boolean requireRunning) { + CanonicalInitialAdmissionLaunchTarget launchTarget = + launchRepository.lockForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId(), + requireRunning); + requireRequestMatchesLaunch(request, launchTarget); + return launchTarget; + } + + private static void requireRequestMatchesCatalog( + CanonicalInitialAdmissionRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.worldSlug().equals(catalog.worldSlug()) + || !request.realmId().equals(catalog.realmId()) + || !request.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !request.playableStateScope().equals(catalog.stateScope()) + || request.expectedCatalogRevision() != catalog.catalogRevision() + || !catalog.visible() + || !catalog.publicProduction()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical realm catalog does not match the exact initial-admission request"); + } + } + + private static void requireRequestMatchesLaunch( + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + CanonicalGameInstanceLaunchAssociation association = launchTarget.association(); + if (!request.targetNamespace().equals(association.targetNamespace()) + || !request.canonicalTenantId().equals(association.canonicalTenantId()) + || !request.worldSlug().equals(association.worldSlug()) + || !request.realmId().equals(launchTarget.realmId()) + || !request.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || !request.playableStateScope().equals(association.playableStateScope().name()) + || !request.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !request.canonicalVersionId().equals(launchTarget.canonicalVersionId()) + || !association.publicProduction()) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Canonical launch association does not match the exact initial-admission target tuple"); + } + } + + private static void requireRequestMatchesCatalogAndLaunch( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + requireRequestMatchesCatalog(request, catalog); + requireRequestMatchesLaunch(request, launchTarget); + } + + private void lockTarget(CanonicalInitialAdmissionRequest request) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ? || ':' || ?, 0))", + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString()); + } + + /** + * Existing pointer and legacy writers do not participate in this canonical target lock. Briefly + * excluding every representation table closes the otherwise-open absence-check gap; V9 numeric + * identifiers are used only to find collisions, never as canonical proof. + */ + private void lockAllAdmissionRepresentationsForNoPrior() { + dsl.execute( + "LOCK TABLE gameplay_admission_pointer, gameplay_admission_pointer_event, " + + "game_session_canonical_closed_admission_pointer_request, " + + "gameplay_initial_admission_bind_catalog, gameplay_initial_admission_bind_attempt " + + "IN SHARE ROW EXCLUSIVE MODE"); + } + + private Attempt requireAttemptForUpdate(CanonicalInitialAdmissionRequest request) { + Attempt attempt = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (attempt == null) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission request was not durably reserved before owner proof or commit"); + } + return attempt; + } + + private void requireSameRequest( + Attempt attempt, + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionLaunchTarget launchTarget) { + requireSameRequestIdentity(attempt, request); + if (attempt.runtimeVersionId() != launchTarget.runtimeVersionId() + || attempt.gameSessionTenantId() != launchTarget.association().gameSessionTenantId() + || attempt.gameInstanceId() != launchTarget.gameInstanceId()) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was reused with a changed canonical tuple or digest"); + } + } + + private void requireSameRequestIdentity( + Attempt attempt, CanonicalInitialAdmissionRequest request) { + if (!attempt.targetNamespace().equals(request.targetNamespace()) + || !attempt.initialAdmissionRequestId().equals(request.initialAdmissionRequestId()) + || !attempt.requestDigest().equals(request.requestDigest()) + || !attempt.canonicalTenantId().equals(request.canonicalTenantId()) + || !attempt.worldSlug().equals(request.worldSlug()) + || !attempt.realmId().equals(request.realmId()) + || !attempt.playableStateNamespaceId().equals(request.playableStateNamespaceId()) + || !attempt.playableStateScope().equals(request.playableStateScope()) + || !attempt.canonicalGameInstanceId().equals(request.canonicalGameInstanceId()) + || !attempt.canonicalVersionId().equals(request.canonicalVersionId()) + || !attempt.holdBindingDigest().equals(request.holdBindingDigest()) + || attempt.expectedCatalogRevision() != request.expectedCatalogRevision() + || attempt.originKind() != request.originKind() + || !Objects.equals( + attempt.expectedPriorPointerVersion(), request.expectedPriorPointerVersion()) + || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() + || !attempt.holdId().equals(request.holdId()) + || !attempt.holdFence().equals(request.holdFence())) { + throw new CanonicalInitialAdmissionConflictException( + "Initial-admission request identity was reused with a changed canonical tuple or digest"); + } + } + + private Attempt findPendingForRealm(CanonicalInitialAdmissionRequest request, boolean forUpdate) { + String sql = + "SELECT * FROM " + + OPERATION_TABLE + + " WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "AND status = 'PENDING'" + + (forUpdate ? " FOR UPDATE" : ""); + return Optional.ofNullable( + dsl.fetchOne( + sql, request.targetNamespace(), request.canonicalTenantId(), request.realmId())) + .map(CanonicalInitialAdmissionRepository::toAttempt) + .orElse(null); + } + + private Attempt findAttempt(String targetNamespace, String requestId, boolean forUpdate) { + return Optional.ofNullable(findAttemptRecord(targetNamespace, requestId, forUpdate)) + .map(CanonicalInitialAdmissionRepository::toAttempt) + .orElse(null); + } + + private Record findAttemptRecord(String targetNamespace, String requestId, boolean forUpdate) { + 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" : ""), + targetNamespace, + requestId); + } + + private static Attempt toAttempt(Record row) { + return new Attempt( + row.get("target_namespace", String.class), + row.get("initial_admission_request_id", String.class), + row.get("request_digest", String.class), + row.get("canonical_tenant_id", UUID.class), + row.get("world_slug", String.class), + row.get("realm_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("playable_state_scope", String.class), + row.get("canonical_game_instance_id", UUID.class), + row.get("canonical_version_id", UUID.class), + row.get("game_session_tenant_id", Long.class), + row.get("game_instance_id", Long.class), + row.get("runtime_version_id", Long.class), + row.get("hold_binding_digest", String.class), + row.get("expected_catalog_revision", Long.class), + CanonicalInitialAdmissionRequest.OriginKind.valueOf(row.get("origin_kind", String.class)), + row.get("expected_prior_pointer_version", Long.class), + row.get("active_lifecycle_epoch", Long.class), + row.get("hold_id", UUID.class), + row.get("hold_fence", UUID.class), + row.get("status", String.class), + row.get("pointer_id", Long.class), + row.get("pointer_version", Long.class), + row.get("audit_event_id", Long.class), + row.get("prior_pointer_request_id", UUID.class), + row.get("prior_pointer_request_digest", String.class), + row.get("prior_pointer_audit_event_id", Long.class), + row.get("commit_proof_digest", String.class), + row.get("abort_proof_digest", String.class), + row.get("abort_reason", String.class), + row.get("created_at", OffsetDateTime.class).toInstant(), + row.get("updated_at", OffsetDateTime.class).toInstant(), + row.get("terminal_at", OffsetDateTime.class) == null + ? null + : row.get("terminal_at", OffsetDateTime.class).toInstant()); + } + + private static CanonicalInitialAdmissionOwnerProof toProof( + Attempt attempt, CanonicalInitialAdmissionOwnerProof.Outcome outcome) { + return new CanonicalInitialAdmissionOwnerProof( + outcome, + attempt.initialAdmissionRequestId(), + attempt.requestDigest(), + attempt.targetNamespace(), + attempt.canonicalTenantId(), + attempt.worldSlug(), + attempt.realmId(), + attempt.playableStateNamespaceId(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId(), + attempt.canonicalVersionId(), + attempt.activeLifecycleEpoch(), + attempt.expectedCatalogRevision(), + attempt.originKind(), + attempt.expectedPriorPointerVersion(), + attempt.holdId(), + attempt.holdFence(), + attempt.holdBindingDigest(), + attempt.pointerVersion(), + attempt.auditEventId(), + COMMITTED.equals(attempt.status()) + ? attempt.commitProofDigest() + : ABORTED.equals(attempt.status()) ? attempt.abortProofDigest() : null, + ABORTED.equals(attempt.status()), + attempt.terminalAt()); + } + + private static String commitProofDigest( + Attempt attempt, + long pointerVersion, + long auditEventId, + Instant terminalAt, + UUID priorRequestId, + String priorRequestDigest, + Long priorAuditEventId) { + return digest( + List.of( + COMMIT_PROOF_DOMAIN, + attempt.requestDigest(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.canonicalTenantId().toString(), + attempt.worldSlug(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId().toString(), + attempt.canonicalVersionId().toString(), + Long.toString(attempt.runtimeVersionId()), + Long.toString(attempt.activeLifecycleEpoch()), + Long.toString(attempt.expectedCatalogRevision()), + attempt.originKind().name(), + attempt.expectedPriorPointerVersion() == null + ? "" + : attempt.expectedPriorPointerVersion().toString(), + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.holdBindingDigest(), + Long.toString(pointerVersion), + Long.toString(auditEventId), + priorRequestId == null ? "" : priorRequestId.toString(), + priorRequestDigest == null ? "" : priorRequestDigest, + priorAuditEventId == null ? "" : priorAuditEventId.toString(), + terminalAt.toString())); + } + + private static String abortProofDigest( + Attempt attempt, + String reason, + Instant terminalAt, + UUID priorRequestId, + String priorRequestDigest, + Long priorAuditEventId) { + return digest( + List.of( + ABORT_PROOF_DOMAIN, + attempt.requestDigest(), + attempt.initialAdmissionRequestId(), + attempt.targetNamespace(), + attempt.canonicalTenantId().toString(), + attempt.worldSlug(), + attempt.realmId().toString(), + attempt.playableStateNamespaceId().toString(), + attempt.playableStateScope(), + attempt.canonicalGameInstanceId().toString(), + attempt.canonicalVersionId().toString(), + Long.toString(attempt.runtimeVersionId()), + Long.toString(attempt.activeLifecycleEpoch()), + Long.toString(attempt.expectedCatalogRevision()), + attempt.originKind().name(), + attempt.expectedPriorPointerVersion() == null + ? "" + : attempt.expectedPriorPointerVersion().toString(), + attempt.holdId().toString(), + attempt.holdFence().toString(), + attempt.holdBindingDigest(), + reason, + priorRequestId == null ? "" : priorRequestId.toString(), + priorRequestDigest == null ? "" : priorRequestDigest, + priorAuditEventId == null ? "" : priorAuditEventId.toString(), + terminalAt.toString())); + } + + private static String digest(List fields) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String field : fields) { + byte[] bytes = field.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array()); + digest.update(bytes); + } + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static Instant nextTimestamp(Instant previous) { + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + if (previous != null && !now.isAfter(previous)) { + return previous.plus(1, ChronoUnit.MICROS); + } + return now; + } + + private static OffsetDateTime utc(Instant instant) { + return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires a writable transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolation = + dsl.fetchOne( + "SELECT current_setting('transaction_isolation') AS isolation, " + + "current_setting('transaction_read_only') AS read_only"); + if (isolation == null + || !"read committed".equals(isolation.get("isolation", String.class)) + || !"off".equals(isolation.get("read_only", String.class))) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires writable READ COMMITTED isolation"); + } + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical initial-admission owner proof requires a committed readback"); + } + } + + private static void requireText(String value, String label, int maxLength) { + Objects.requireNonNull(value, label); + if (value.isBlank() || value.length() > maxLength) { + throw new IllegalArgumentException(label + " must contain 1.." + maxLength + " characters"); + } + } + + /** Full persisted pointer-row identity used to detect any before/after read drift. */ + private record CurrentOpenPointer(Map fields) { + private CurrentOpenPointer { + fields = Collections.unmodifiableMap(new LinkedHashMap<>(fields)); + } + + private static CurrentOpenPointer from(Record row) { + return new CurrentOpenPointer(row.intoMap()); + } + + private String initialAdmissionRequestId() { + return value("initial_admission_request_id", String.class); + } + + private void requireCanonicalOpen( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + if (!Integer.valueOf(3).equals(value("representation_version", Integer.class)) + || !"OPEN".equals(value("admission_state", String.class)) + || !targetNamespace.equals(value("target_namespace", String.class)) + || !canonicalTenantId.equals(value("canonical_tenant_id", UUID.class)) + || !realmId.equals(value("realm_id", UUID.class)) + || !Boolean.TRUE.equals(value("visible", Boolean.class)) + || !Boolean.TRUE.equals(value("public_production_realm", Boolean.class)) + || value("requires_character_selection", Boolean.class) != null + || !"SHARED".equals(value("state_scope", String.class)) + || !AUDIT_ACTOR.equals(value("last_updated_by", String.class)) + || !AUDIT_REASON.equals(value("last_update_reason", String.class)) + || value("prepared_version_upgrade_id", String.class) != null + || !text(value("character_creation_policy", String.class)) + || !positive(value("id", Long.class)) + || !positive(value("pointer_version", Long.class)) + || !positive(value("catalog_revision", Long.class)) + || !positive(value("tenant_id", Long.class)) + || !positive(value("game_instance_id", Long.class)) + || !positive(value("runtime_version_id", Long.class)) + || !positive(value("initial_admission_active_epoch", Long.class)) + || !nonNil(value("playable_state_namespace_id", UUID.class)) + || !nonNil(value("canonical_game_instance_id", UUID.class)) + || !nonNil(value("canonical_version_id", UUID.class)) + || !nonNil(value("initial_admission_hold_id", UUID.class)) + || !nonNil(value("initial_admission_hold_fence", UUID.class)) + || !text(value("world_slug", String.class)) + || !text(value("realm_slug", String.class)) + || !text(value("initial_admission_request_id", String.class)) + || !matchesDigest(value("initial_admission_request_digest", String.class)) + || !text(value("initial_admission_origin_kind", String.class)) + || !matchesProofDigest(value("initial_admission_hold_binding_digest", String.class))) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current realm pointer is not a complete canonical OPEN representation"); + } + } + + private boolean matches(CanonicalInitialAdmissionOwnerProof proof) { + return proof.provesCommit() + && proof.targetNamespace().equals(value("target_namespace", String.class)) + && proof.canonicalTenantId().equals(value("canonical_tenant_id", UUID.class)) + && proof.worldSlug().equals(value("world_slug", String.class)) + && proof.realmId().equals(value("realm_id", UUID.class)) + && proof + .playableStateNamespaceId() + .equals(value("playable_state_namespace_id", UUID.class)) + && proof.playableStateScope().equals(value("state_scope", String.class)) + && proof.canonicalGameInstanceId().equals(value("canonical_game_instance_id", UUID.class)) + && proof.canonicalVersionId().equals(value("canonical_version_id", UUID.class)) + && proof.expectedCatalogRevision() == value("catalog_revision", Long.class) + && proof.committedPointerVersion().equals(value("pointer_version", Long.class)) + && proof + .initialAdmissionRequestId() + .equals(value("initial_admission_request_id", String.class)) + && proof.requestDigest().equals(value("initial_admission_request_digest", String.class)) + && proof.originKind().name().equals(value("initial_admission_origin_kind", String.class)) + && Objects.equals( + proof.expectedPriorPointerVersion(), + value("initial_admission_prior_pointer_version", Long.class)) + && proof.activeLifecycleEpoch() == value("initial_admission_active_epoch", Long.class) + && proof.holdId().equals(value("initial_admission_hold_id", UUID.class)) + && proof.holdFence().equals(value("initial_admission_hold_fence", UUID.class)) + && proof + .holdBindingDigest() + .equals(value("initial_admission_hold_binding_digest", String.class)) + && proof.auditEventId() != null + && proof.auditEventId() > 0L; + } + + private String snapshotDigest(CanonicalInitialAdmissionOwnerProof proof) { + return CanonicalCurrentOpenPointerSnapshotDigest.digest( + new CanonicalCurrentOpenPointerSnapshotDigest.Projection( + value("representation_version", Integer.class), + value("target_namespace", String.class), + value("canonical_tenant_id", UUID.class), + value("world_slug", String.class), + value("world_display_name", String.class), + value("realm_id", UUID.class), + value("realm_slug", String.class), + value("realm_display_name", String.class), + value("playable_state_namespace_id", UUID.class), + value("state_scope", String.class), + value("catalog_revision", Long.class), + value("pointer_version", Long.class), + value("admission_state", String.class), + value("visible", Boolean.class), + value("public_production_realm", Boolean.class), + value("requires_character_selection", Boolean.class), + value("character_creation_policy", String.class), + value("canonical_game_instance_id", UUID.class), + value("canonical_version_id", UUID.class), + value("initial_admission_request_id", String.class), + value("initial_admission_request_digest", String.class), + CanonicalInitialAdmissionRequest.OriginKind.valueOf( + value("initial_admission_origin_kind", String.class)), + value("initial_admission_prior_pointer_version", Long.class), + value("initial_admission_active_epoch", Long.class), + value("initial_admission_hold_id", UUID.class), + value("initial_admission_hold_fence", UUID.class), + value("initial_admission_hold_binding_digest", String.class), + value("last_updated_by", String.class), + value("last_update_reason", String.class), + value("prepared_version_upgrade_id", String.class), + proof.proofDigest(), + proof.auditEventId(), + proof.terminalAt())); + } + + private T value(String key, Class type) { + Object value = fields.get(key); + if (value == null) { + return null; + } + if (!type.isInstance(value)) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current realm pointer contains an invalid persisted field type: " + key); + } + return type.cast(value); + } + + private static boolean positive(Long value) { + return value != null && value > 0L; + } + + private static boolean nonNil(UUID value) { + return value != null && !new UUID(0L, 0L).equals(value); + } + + private static boolean text(String value) { + return value != null && !value.isBlank() && value.equals(value.trim()); + } + + private static boolean matchesDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private static boolean matchesProofDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + } + + private record Attempt( + String targetNamespace, + String initialAdmissionRequestId, + String requestDigest, + UUID canonicalTenantId, + String worldSlug, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + UUID canonicalGameInstanceId, + UUID canonicalVersionId, + long gameSessionTenantId, + long gameInstanceId, + long runtimeVersionId, + String holdBindingDigest, + long expectedCatalogRevision, + CanonicalInitialAdmissionRequest.OriginKind originKind, + Long expectedPriorPointerVersion, + long activeLifecycleEpoch, + UUID holdId, + UUID holdFence, + String status, + Long pointerId, + Long pointerVersion, + Long auditEventId, + UUID priorPointerRequestId, + String priorPointerRequestDigest, + Long priorPointerAuditEventId, + String commitProofDigest, + String abortProofDigest, + String abortReason, + Instant createdAt, + Instant updatedAt, + Instant terminalAt) { + private CanonicalInitialAdmissionRequest asRequest() { + return new CanonicalInitialAdmissionRequest( + targetNamespace, + canonicalTenantId, + worldSlug, + realmId, + playableStateNamespaceId, + playableStateScope, + canonicalGameInstanceId, + canonicalVersionId, + activeLifecycleEpoch, + expectedCatalogRevision, + originKind, + expectedPriorPointerVersion, + initialAdmissionRequestId, + requestDigest, + holdId, + holdFence, + holdBindingDigest); + } + } + + public static class CanonicalInitialAdmissionConflictException extends IllegalStateException { + public CanonicalInitialAdmissionConflictException(String message) { + super(message); + } + } + + public static class CanonicalInitialAdmissionReconciliationRequiredException + extends IllegalStateException { + public CanonicalInitialAdmissionReconciliationRequiredException(String message) { + super(message); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java new file mode 100644 index 0000000000..9e62010a0a --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigest.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; + +/** Versioned local source-intake digests; neither digest authenticates Game Design. */ +public final class GameSessionAuthoredWorldIntakeDigest { + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + private GameSessionAuthoredWorldIntakeDigest() {} + + public static String requestDigest(UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireIdentity(intakeRequestId, "intakeRequestId"); + Objects.requireNonNull(source, "source"); + return digest( + "game-session-authored-world-intake-request/v1", + intakeRequestId.toString(), + source.evidenceDigest()); + } + + public static String receiptDigest( + UUID localOperationId, String requestDigest, String evidenceDigest) { + requireIdentity(localOperationId, "localOperationId"); + requireDigest(requestDigest); + requireDigest(evidenceDigest); + return digest( + "game-session-authored-world-intake-receipt/v1", + localOperationId.toString(), + requestDigest, + evidenceDigest); + } + + private static String digest(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 requireIdentity(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("A canonical SHA-256 digest is required"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java new file mode 100644 index 0000000000..0133d1004b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldSourceRepository.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session's immutable, owner-local copy of authenticated Game Design authored-world source. + */ +@Repository +public class GameSessionAuthoredWorldSourceRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private static final Table TENANT_BINDING = + DSL.table(DSL.name("game_session_authored_world_tenant_source_binding")); + private static final Field BINDING_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field BINDING_CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field BINDING_TENANT_SLUG = + DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field BINDING_SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field BINDING_SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + + private static final Table INTAKE = + DSL.table(DSL.name("game_session_authored_world_source_intake")); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field OPERATION_SCHEMA_VERSION = + DSL.field(DSL.name("schema_version"), Integer.class); + private static final Field OPERATION_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field INTAKE_REQUEST_ID = + DSL.field(DSL.name("intake_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field WORLD_DISPLAY_NAME = + DSL.field(DSL.name("world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted Spring collaborator is validated before use; no resources or finalizer are acquired." + + " The repository remains non-final for transaction proxying.") + public GameSessionAuthoredWorldSourceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + } + + /** + * Persists one complete source receipt under the caller's owner transaction. + * + *

The authenticated source client is responsible for obtaining the evidence from Game Design. + * This repository validates its closed evidence and digests, then atomically stores that exact + * copy with the stable tenant and world selector claims. + */ + @Transactional(propagation = Propagation.MANDATORY) + public IntakeReceipt register(UUID intakeRequestId, AuthoredWorldSourceEvidence source) { + requireActiveOwnerTransaction(); + requireNonNil(intakeRequestId, "intakeRequestId"); + AuthoredWorldSourceEvidence validatedSource = validateSource(source); + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, validatedSource); + + Record existingRequest = + findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (existingRequest != null) { + return requireExactReplay(existingRequest, intakeRequestId, requestDigest, validatedSource); + } + + ensureTenantBinding(validatedSource); + UUID operationId = UUID.randomUUID(); + String receiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, validatedSource.evidenceDigest()); + + int inserted = + dsl.insertInto(INTAKE) + .set(OPERATION_ID, operationId) + .set(OPERATION_SCHEMA_VERSION, SCHEMA_VERSION) + .set(OPERATION_NAMESPACE, validatedSource.targetNamespace()) + .set(INTAKE_REQUEST_ID, intakeRequestId) + .set(REQUEST_DIGEST, requestDigest) + .set(SOURCE_SCHEMA_VERSION, validatedSource.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, validatedSource.registrationRequestId()) + .set(SOURCE_OPERATION_ID, validatedSource.operationId()) + .set(SOURCE_REQUEST_DIGEST, validatedSource.requestDigest()) + .set(CANONICAL_TENANT_ID, validatedSource.canonicalTenantId()) + .set(TENANT_SLUG, validatedSource.tenantSlug()) + .set(WORLD_SLUG, validatedSource.worldSlug()) + .set(WORLD_DISPLAY_NAME, validatedSource.worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, validatedSource.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, validatedSource.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, validatedSource.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, validatedSource.evidenceDigest()) + .set(RECEIPT_DIGEST, receiptDigest) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record racedRequest = findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (racedRequest != null) { + return requireExactReplay(racedRequest, intakeRequestId, requestDigest, validatedSource); + } + if (findBySourceOperation(validatedSource.targetNamespace(), validatedSource.operationId()) + != null) { + throw new RegistrationConflictException( + "Game Design source operation is already consumed by another intake request"); + } + if (findBySourceRegistrationRequest( + validatedSource.targetNamespace(), validatedSource.registrationRequestId()) + != null) { + throw new RegistrationConflictException( + "Game Design source registration request is already consumed by another intake"); + } + if (findByWorldSelector( + validatedSource.targetNamespace(), + validatedSource.canonicalTenantId(), + validatedSource.worldSlug()) + != null) { + throw new RegistrationConflictException( + "Authored-world selector is already bound to another consumed source"); + } + throw new RegistrationConflictException( + "Authored-world source intake conflicts with an existing owner claim"); + } + + Record persisted = findByIntakeRequest(validatedSource.targetNamespace(), intakeRequestId); + if (persisted == null) { + throw new IllegalStateException("Committed authored-world source intake is missing"); + } + IntakeReceipt receipt = toReceipt(persisted); + requireExactSource(receipt.source(), validatedSource); + requireTenantBinding(receipt.source()); + return receipt; + } + + /** Reads the exact committed local operation without allocating or repairing selector state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional read( + UUID localOperationId, UUID canonicalTenantId, String worldSlug, String namespace) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + requireNonNil(localOperationId, "localOperationId"); + + Record record = + dsl.selectFrom(INTAKE) + .where( + OPERATION_ID + .eq(localOperationId) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug)) + .and(OPERATION_NAMESPACE.eq(namespace))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + /** + * Resolves the one committed source for an exact canonical world selector. + * + *

This owner-local read does not infer source operation IDs or digests from retained numeric + * keys. The returned original receipt still requires exact comparison with the selected catalog + * and separately proved retained association before any launch use. + */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByWorldSelector( + String namespace, UUID canonicalTenantId, String worldSlug) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + AuthoredWorldSourceDigest.validateReadSelector(namespace, canonicalTenantId, worldSlug); + Record record = findByWorldSelector(namespace, canonicalTenantId, worldSlug); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + /** Reads an exact committed retry by its stable intake request without allocating owner state. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByIntakeRequest(String namespace, UUID intakeRequestId) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake read requires a committed-outcome owner read"); + } + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + requireNonNil(intakeRequestId, "intakeRequestId"); + + Record record = + dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + if (record == null) { + return Optional.empty(); + } + IntakeReceipt receipt = toReceipt(record); + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.source().targetNamespace().equals(namespace)) { + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source intake request binding is invalid"); + } + requireTenantBinding(receipt.source()); + return Optional.of(receipt); + } + + private void ensureTenantBinding(AuthoredWorldSourceEvidence source) { + Record existing = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (existing != null) { + requireMatchingBinding(existing, source); + return; + } + + int inserted = + dsl.insertInto(TENANT_BINDING) + .set(BINDING_NAMESPACE, source.targetNamespace()) + .set(BINDING_CANONICAL_TENANT_ID, source.canonicalTenantId()) + .set(BINDING_TENANT_SLUG, source.tenantSlug()) + .set(BINDING_SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(BINDING_SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(BINDING_PROVENANCE_KIND, source.provenanceKind()) + .onConflictDoNothing() + .execute(); + if (inserted == 1) { + return; + } + + Record tenantBinding = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (tenantBinding != null) { + requireMatchingBinding(tenantBinding, source); + return; + } + if (findTenantSlugBinding(source.targetNamespace(), source.tenantSlug()) != null) { + throw new RegistrationConflictException( + "Tenant selector is already owned by another canonical tenant"); + } + if (findSourceRowBinding(source.targetNamespace(), source.sourceGameRowId()) != null) { + throw new RegistrationConflictException( + "Game Design source row is already bound to another canonical tenant"); + } + throw new RegistrationConflictException("Tenant source binding conflicts with an owner claim"); + } + + private void requireTenantBinding(AuthoredWorldSourceEvidence source) { + Record binding = findTenantBinding(source.targetNamespace(), source.canonicalTenantId()); + if (binding == null) { + throw new InvalidIntakeEvidenceException("Tenant source selector binding is missing"); + } + requireMatchingBinding(binding, source); + } + + private void requireMatchingBinding(Record binding, AuthoredWorldSourceEvidence source) { + if (!Objects.equals(binding.get(BINDING_NAMESPACE), source.targetNamespace()) + || !Objects.equals(binding.get(BINDING_CANONICAL_TENANT_ID), source.canonicalTenantId()) + || !Objects.equals(binding.get(BINDING_TENANT_SLUG), source.tenantSlug()) + || !Objects.equals(binding.get(BINDING_SOURCE_GAME_ROW_ID), source.sourceGameRowId()) + || !Objects.equals( + binding.get(BINDING_SOURCE_GAME_TENANT_KEY), source.sourceGameTenantKey()) + || !Objects.equals(binding.get(BINDING_PROVENANCE_KIND), source.provenanceKind())) { + throw new RegistrationConflictException( + "Canonical tenant source or stable tenant selector conflicts with its prior claim"); + } + } + + private IntakeReceipt requireExactReplay( + Record record, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source) { + IntakeReceipt receipt = toReceipt(record); + if (!receipt.intakeRequestId().equals(intakeRequestId) + || !receipt.requestDigest().equals(requestDigest) + || !receipt.source().equals(source)) { + throw new RegistrationConflictException( + "Authored-world intake identity was reused with changed source evidence"); + } + requireTenantBinding(receipt.source()); + return receipt; + } + + private void requireExactSource( + AuthoredWorldSourceEvidence actual, AuthoredWorldSourceEvidence expected) { + if (!actual.equals(expected)) { + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source differs from its authenticated input"); + } + } + + private AuthoredWorldSourceEvidence validateSource(AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(source, "source"); + try { + return new AuthoredWorldSourceEvidence( + 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()); + } catch (IllegalArgumentException exception) { + throw new InvalidIntakeEvidenceException( + "Game Design authored-world source evidence is invalid", exception); + } + } + + private void requireActiveOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Authored-world source intake registration requires an active owner transaction"); + } + } + + private static void requireNonNil(UUID value, String label) { + Objects.requireNonNull(value, label); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(label + " must be a non-nil UUID"); + } + } + + private Record findByIntakeRequest(String namespace, UUID intakeRequestId) { + return dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(INTAKE_REQUEST_ID.eq(intakeRequestId))) + .fetchOne(); + } + + private Record findBySourceOperation(String namespace, UUID sourceOperationId) { + return dsl.selectFrom(INTAKE) + .where(OPERATION_NAMESPACE.eq(namespace).and(SOURCE_OPERATION_ID.eq(sourceOperationId))) + .fetchOne(); + } + + private Record findBySourceRegistrationRequest(String namespace, UUID sourceRequestId) { + return dsl.selectFrom(INTAKE) + .where( + OPERATION_NAMESPACE + .eq(namespace) + .and(SOURCE_REGISTRATION_REQUEST_ID.eq(sourceRequestId))) + .fetchOne(); + } + + private Record findByWorldSelector(String namespace, UUID canonicalTenantId, String worldSlug) { + return dsl.selectFrom(INTAKE) + .where( + OPERATION_NAMESPACE + .eq(namespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(WORLD_SLUG.eq(worldSlug))) + .fetchOne(); + } + + private Record findTenantBinding(String namespace, UUID canonicalTenantId) { + return dsl.selectFrom(TENANT_BINDING) + .where( + BINDING_NAMESPACE.eq(namespace).and(BINDING_CANONICAL_TENANT_ID.eq(canonicalTenantId))) + .fetchOne(); + } + + private Record findTenantSlugBinding(String namespace, String tenantSlug) { + return dsl.selectFrom(TENANT_BINDING) + .where(BINDING_NAMESPACE.eq(namespace).and(BINDING_TENANT_SLUG.eq(tenantSlug))) + .fetchOne(); + } + + private Record findSourceRowBinding(String namespace, long sourceGameRowId) { + return dsl.selectFrom(TENANT_BINDING) + .where(BINDING_NAMESPACE.eq(namespace).and(BINDING_SOURCE_GAME_ROW_ID.eq(sourceGameRowId))) + .fetchOne(); + } + + private IntakeReceipt toReceipt(Record record) { + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + Objects.requireNonNull(record.get(SOURCE_SCHEMA_VERSION)), + Objects.requireNonNull(record.get(OPERATION_NAMESPACE)), + Objects.requireNonNull(record.get(SOURCE_REGISTRATION_REQUEST_ID)), + Objects.requireNonNull(record.get(SOURCE_OPERATION_ID)), + Objects.requireNonNull(record.get(SOURCE_REQUEST_DIGEST)), + Objects.requireNonNull(record.get(CANONICAL_TENANT_ID)), + Objects.requireNonNull(record.get(TENANT_SLUG)), + Objects.requireNonNull(record.get(WORLD_SLUG)), + Objects.requireNonNull(record.get(WORLD_DISPLAY_NAME)), + Objects.requireNonNull(record.get(SOURCE_GAME_ROW_ID)), + Objects.requireNonNull(record.get(SOURCE_GAME_TENANT_KEY)), + Objects.requireNonNull(record.get(SOURCE_PROVENANCE_KIND)), + Objects.requireNonNull(record.get(SOURCE_EVIDENCE_DIGEST))); + if (!Integer.valueOf(SCHEMA_VERSION).equals(record.get(OPERATION_SCHEMA_VERSION))) { + throw new IllegalArgumentException("Unsupported local intake schema version"); + } + return new IntakeReceipt( + Objects.requireNonNull(record.get(OPERATION_ID)), + Objects.requireNonNull(record.get(INTAKE_REQUEST_ID)), + Objects.requireNonNull(record.get(REQUEST_DIGEST)), + source, + Objects.requireNonNull(record.get(RECEIPT_DIGEST))); + } catch (RuntimeException exception) { + if (exception instanceof InvalidIntakeEvidenceException) { + throw exception; + } + throw new InvalidIntakeEvidenceException( + "Persisted authored-world source intake evidence is invalid", exception); + } + } + + /** Immutable local receipt retaining the exact authenticated Game Design source record. */ + public record IntakeReceipt( + UUID operationId, + UUID intakeRequestId, + String requestDigest, + AuthoredWorldSourceEvidence source, + String receiptDigest) { + public IntakeReceipt { + requireNonNil(operationId, "operationId"); + requireNonNil(intakeRequestId, "intakeRequestId"); + Objects.requireNonNull(requestDigest, "requestDigest"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(receiptDigest, "receiptDigest"); + AuthoredWorldSourceEvidence validated = + new AuthoredWorldSourceEvidence( + 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()); + if (!validated.equals(source) + || !requestDigest.equals( + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source)) + || !receiptDigest.equals( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest()))) { + throw new IllegalArgumentException( + "Game Session authored-world receipt digests do not match"); + } + } + } + + public static final class RegistrationConflictException extends IllegalStateException { + public RegistrationConflictException(String message) { + super(message); + } + } + + public static final class InvalidIntakeEvidenceException extends IllegalStateException { + public InvalidIntakeEvidenceException(String message) { + super(message); + } + + public InvalidIntakeEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java new file mode 100644 index 0000000000..0d8abbfb81 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java @@ -0,0 +1,1076 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner-local persistence for one initial canonical CLOSED admission pointer per realm. */ +@Repository +public class GameSessionCanonicalAdmissionPointerRepository { + private static final int SCHEMA_VERSION = 1; + private static final int CANONICAL_REPRESENTATION_VERSION = 2; + private static final long INITIAL_POINTER_VERSION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String CLOSED = "CLOSED"; + private static final String ABSENT = "ABSENT"; + private static final String REQUEST_DOMAIN = "game-session-canonical-closed-pointer-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-closed-pointer-receipt/v1"; + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories and DSLContext are internal Spring collaborators.") + public GameSessionCanonicalAdmissionPointerRepository( + DSLContext dsl, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameplayAdmissionPointerEventRepository eventRepository) { + this.dsl = dsl; + this.catalogRepository = catalogRepository; + this.eventRepository = eventRepository; + } + + /** + * Prepares from a committed catalog read without retaining an ambient owner transaction. The + * returned value is privately constructed and must be revalidated under the catalog row lock. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedInitialClosed prepareInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request) { + Objects.requireNonNull(request, "request"); + requireCommittedRead(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(request.targetNamespace(), request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact committed initial catalog request is missing")); + requireExactInitialCatalog(request, catalog); + return new PreparedInitialClosed(request, catalog, requestDigest(request, catalog)); + } + + /** + * Commits the CLOSED route, one append-only event, and its immutable request outcome atomically. + * The caller must perform a separate committed {@link #readByRequest} before returning evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void createInitialClosed(PreparedInitialClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CreateCanonicalClosedAdmissionPointerRequest request = prepared.request(); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + requireExactInitialCatalog(request, catalog); + if (!prepared.catalogSnapshot().equals(catalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Locked catalog snapshot changed after canonical CLOSED pointer preparation"); + } + + String requestDigest = requestDigest(request, catalog); + if (!prepared.requestDigest().equals(requestDigest)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Prepared canonical CLOSED pointer digest does not match its exact inputs"); + } + + Record priorRequest = findRequest(request.targetNamespace(), request.requestId()); + if (priorRequest != null) { + requireSameRequest(priorRequest, request, catalog, requestDigest); + return; + } + if (pointerExistsForRealm(request.realmId())) { + throw new CanonicalClosedPointerConflictException( + "Canonical realm already has an admission-pointer representation"); + } + + Instant updatedAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Long pointerId; + long auditEventId; + String receiptDigest; + try { + Record insertedPointer = + 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) " + + "VALUES (?, ?, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, NULL, NULL, " + + "?, ?, NULL, ?, ?, NULL, 2, ?, ?, 'CLOSED') RETURNING id", + catalog.worldSlug(), + catalog.realmSlug(), + toLocalDateTime(updatedAt), + toLocalDateTime(updatedAt), + catalog.catalogRevision(), + catalog.realmId(), + catalog.targetNamespace(), + catalog.tenantId()); + if (insertedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer insert returned no owner row"); + } + pointerId = insertedPointer.get("id", Long.class); + if (pointerId == null || pointerId <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row id is invalid"); + } + + auditEventId = + eventRepository.appendCanonicalClosed( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + catalog.catalogRevision(), + request.actorPrincipal(), + request.reason(), + request.requestId(), + updatedAt); + receiptDigest = receiptDigest(request, catalog, requestDigest, auditEventId, updatedAt); + dsl.execute( + "INSERT INTO game_session_canonical_closed_admission_pointer_request (" + + "target_namespace, request_id, request_digest, canonical_tenant_id, realm_id, " + + "catalog_creation_request_id, catalog_revision, catalog_request_digest, " + + "catalog_receipt_digest, actor_principal, reason, admission_state, pointer_version, " + + "audit_event_id, receipt_digest, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'CLOSED', 1, ?, ?, CAST(? AS TIMESTAMPTZ))", + request.targetNamespace(), + request.requestId(), + requestDigest, + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision(), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + auditEventId, + receiptDigest, + OffsetDateTime.ofInstant(updatedAt, ZoneOffset.UTC)); + } catch (org.jooq.exception.IntegrityConstraintViolationException exception) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer creation conflicts with committed realm or request authority", + exception); + } + } + + /** + * Prepares an explicit expected-closed check from the exact original committed CLOSED request. + * Missing request, pointer, event, or catalog history is invalid evidence and never establishes a + * never-open origin. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedExpectedClosed prepareExpectedClosed( + String targetNamespace, + UUID originalRequestId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, originalRequestId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireCommittedRead(); + + CanonicalClosedAdmissionPointerSnapshot origin = + readByRequest(targetNamespace, originalRequestId) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact original committed canonical CLOSED origin is missing")); + requireExpectedVersions(origin, expectedPointerVersion, expectedCatalogRevision); + return new PreparedExpectedClosed(origin, expectedPointerVersion, expectedCatalogRevision); + } + + /** + * Prepares the exact original CLOSED origin for a realm without accepting a caller-supplied + * origin request identity. The canonical CLOSED owner table is the source of that identity. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public PreparedExpectedClosed prepareExpectedClosedForRealm( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + long expectedPointerVersion, + long expectedCatalogRevision) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireReadSelector(targetNamespace, realmId); + requirePositive(expectedPointerVersion, "expectedPointerVersion"); + requirePositive(expectedCatalogRevision, "expectedCatalogRevision"); + requireCommittedRead(); + var outcomes = + dsl.fetch( + "SELECT request_id FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "ORDER BY request_id LIMIT 2", + targetNamespace, + canonicalTenantId, + realmId); + if (outcomes.size() != 1) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Realm does not have one exact original canonical CLOSED request outcome"); + } + UUID originalRequestId = required(outcomes.getFirst(), "request_id", UUID.class); + return prepareExpectedClosed( + targetNamespace, originalRequestId, expectedPointerVersion, expectedCatalogRevision); + } + + /** + * Reads the immutable original CLOSED request/event after the current pointer has opened. This is + * historical origin evidence only; it does not claim that CLOSED remains the current route. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readOriginalClosedOrigin( + String targetNamespace, UUID originalRequestId) { + requireReadSelector(targetNamespace, originalRequestId); + requireCommittedRead(); + Record outcome = findRequest(targetNamespace, originalRequestId); + if (outcome == null) { + return Optional.empty(); + } + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(targetNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED origin lost its exact catalog evidence")); + return Optional.of( + verifyOrigin(targetNamespace, originalRequestId, outcome, catalog, null, false)); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted original canonical CLOSED evidence is invalid", exception); + } + } + + /** + * Requires absence across every persisted pointer/audit representation that can name this + * canonical realm or its exactly associated legacy runtime selector. The caller must hold the + * catalog/target serialization locks in its writable READ COMMITTED transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public void requireNoAdmissionPointerRepresentations( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long gameSessionTenantId, + long gameInstanceId) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireReadSelector(targetNamespace, realmId); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + requirePositive(gameSessionTenantId, "gameSessionTenantId"); + requirePositive(gameInstanceId, "gameInstanceId"); + Record exists = + dsl.fetchOne( + "SELECT EXISTS (" + + "SELECT 1 FROM gameplay_admission_pointer WHERE realm_id = ? " + + "OR (target_namespace = ? AND canonical_tenant_id = ?) " + + "OR (world_slug = ? AND realm_slug = ?) " + + "OR (tenant_id = ? AND game_instance_id = ?) " + + "UNION ALL SELECT 1 FROM gameplay_admission_pointer_event WHERE realm_id = ? " + + "OR (target_namespace = ? AND canonical_tenant_id = ?) " + + "OR (world_slug = ? AND realm_slug = ?) " + + "OR (tenant_id = ? AND game_instance_id = ?) " + + "UNION ALL SELECT 1 FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "UNION ALL SELECT 1 FROM gameplay_initial_admission_bind_catalog " + + "WHERE tenant_id = ? AND (realm_id = ? OR (world_slug = ? AND realm_slug = ?)) " + + "UNION ALL SELECT 1 FROM gameplay_initial_admission_bind_attempt " + + "WHERE tenant_id = ? AND (realm_id = ? OR game_instance_id = ?)" + + ") AS represented", + realmId, + targetNamespace, + canonicalTenantId, + worldSlug, + realmSlug, + gameSessionTenantId, + gameInstanceId, + realmId, + targetNamespace, + canonicalTenantId, + worldSlug, + realmSlug, + gameSessionTenantId, + gameInstanceId, + targetNamespace, + canonicalTenantId, + realmId, + gameSessionTenantId, + realmId, + worldSlug, + realmSlug, + gameSessionTenantId, + realmId, + gameInstanceId); + if (exists == null || !Boolean.FALSE.equals(exists.get("represented", Boolean.class))) { + throw new CanonicalClosedPointerConflictException( + "A pointer, audit, or prior initial-admission representation already names this target"); + } + } + + /** + * Locks and revalidates one prepared original CLOSED origin in the caller's read-write READ + * COMMITTED owner transaction. The returned token is local repository evidence only; it is not + * World hold/readback, caller authentication, or authorization to transition the pointer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ExpectedClosedEvidence lockExpectedClosed(PreparedExpectedClosed prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireWritableOwnerTransaction(); + CanonicalClosedAdmissionPointerSnapshot committedOrigin = prepared.committedOrigin(); + CreateCanonicalClosedAdmissionPointerRequest originRequest = + requestFromSnapshot(committedOrigin); + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + originRequest.targetNamespace(), + originRequest.canonicalTenantId(), + originRequest.realmId(), + originRequest.catalogCreationRequestId(), + prepared.expectedCatalogRevision()); + if (!committedOrigin.catalogSnapshot().equals(lockedCatalog)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact catalog origin changed after expected-CLOSED preparation"); + } + + Record lockedPointer = lockCanonicalPointer(originRequest); + if (lockedPointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED pointer row is missing"); + } + Record outcome = findRequest(originRequest.targetNamespace(), originRequest.requestId()); + if (outcome == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED request outcome is missing"); + } + + CanonicalClosedAdmissionPointerSnapshot lockedOrigin = + verifyOrigin( + originRequest.targetNamespace(), + originRequest.requestId(), + outcome, + lockedCatalog, + lockedPointer); + requireExpectedVersions( + lockedOrigin, prepared.expectedPointerVersion(), prepared.expectedCatalogRevision()); + if (!committedOrigin.equals(lockedOrigin)) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Exact original canonical CLOSED origin changed after preparation"); + } + return new ExpectedClosedEvidence(lockedOrigin); + } + + /** Reads and verifies the immutable request outcome from committed owner rows. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record outcome = findRequest(targetNamespace, requestId); + if (outcome == null) { + return Optional.empty(); + } + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(targetNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome lost its catalog reference")); + Record pointer = findCanonicalPointer(request); + return Optional.of(verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer)); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private Record findRequest(String targetNamespace, UUID requestId) { + return dsl.fetchOne( + "SELECT * FROM game_session_canonical_closed_admission_pointer_request " + + "WHERE target_namespace = ? AND request_id = ?", + targetNamespace, + requestId); + } + + private Record lockCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private CanonicalClosedAdmissionPointerSnapshot verifyOrigin( + String targetNamespace, + UUID requestId, + Record outcome, + CanonicalRealmCatalogSnapshot catalog, + Record pointer) { + return verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer, true); + } + + private CanonicalClosedAdmissionPointerSnapshot verifyOrigin( + String targetNamespace, + UUID requestId, + Record outcome, + CanonicalRealmCatalogSnapshot catalog, + Record pointer, + boolean requireCurrentPointer) { + try { + CreateCanonicalClosedAdmissionPointerRequest request = requestFromOutcome(outcome); + if (!targetNamespace.equals(request.targetNamespace()) + || !requestId.equals(request.requestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its read selector"); + } + requireExactInitialCatalog(request, catalog); + String computedRequestDigest = requestDigest(request, catalog); + if (!computedRequestDigest.equals(required(outcome, "request_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request digest does not match committed request inputs"); + } + if (!catalog.requestDigest().equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome does not match its exact catalog digests"); + } + + long eventId = required(outcome, "audit_event_id", Long.class); + Instant updatedAt = outcomeTimestamp(outcome); + String computedReceiptDigest = + receiptDigest(request, catalog, computedRequestDigest, eventId, updatedAt); + if (!computedReceiptDigest.equals(required(outcome, "receipt_digest", String.class))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer receipt digest does not match its committed result"); + } + requireOutcomeMatches( + outcome, + request, + catalog, + computedRequestDigest, + computedReceiptDigest, + eventId, + updatedAt); + + if (requireCurrentPointer && pointer == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed routing row"); + } + if (requireCurrentPointer) { + requirePointerMatches(pointer, request, catalog, updatedAt); + } + + Record event = findCanonicalEvent(eventId); + if (event == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome has no committed audit event"); + } + requireEventMatches(event, request, catalog, eventId, updatedAt); + + return new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + INITIAL_POINTER_VERSION, + catalog.catalogRevision(), + CLOSED, + null, + request.requestId(), + computedRequestDigest, + computedReceiptDigest, + request.actorPrincipal(), + request.reason(), + eventId, + updatedAt, + catalog); + } catch (InvalidCanonicalClosedPointerEvidenceException + | GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException + | GameSessionCanonicalRealmCatalogRepository.CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer evidence is invalid", exception); + } + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromSnapshot( + CanonicalClosedAdmissionPointerSnapshot snapshot) { + return new CreateCanonicalClosedAdmissionPointerRequest( + snapshot.requestId(), + snapshot.targetNamespace(), + snapshot.canonicalTenantId(), + snapshot.realmId(), + snapshot.catalogSnapshot().creationRequestId(), + snapshot.catalogRevision(), + snapshot.actorPrincipal(), + snapshot.reason()); + } + + static void requireExpectedVersions( + CanonicalClosedAdmissionPointerSnapshot origin, + long expectedPointerVersion, + long expectedCatalogRevision) { + if (origin.pointerVersion() != expectedPointerVersion + || origin.catalogRevision() != expectedCatalogRevision) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Expected pointer and catalog versions do not match the exact original CLOSED origin"); + } + } + + private boolean pointerExistsForRealm(UUID realmId) { + return dsl.fetchExists( + dsl.selectOne() + .from(org.jooq.impl.DSL.table("gameplay_admission_pointer")) + .where(org.jooq.impl.DSL.field("realm_id", UUID.class).eq(realmId))); + } + + private Record findCanonicalPointer(CreateCanonicalClosedAdmissionPointerRequest request) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer " + + "WHERE representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ?", + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId()); + } + + private Record findCanonicalEvent(long eventId) { + return dsl.fetchOne( + "SELECT * FROM gameplay_admission_pointer_event " + + "WHERE representation_version = 2 AND id = ?", + eventId); + } + + private static CreateCanonicalClosedAdmissionPointerRequest requestFromOutcome(Record outcome) { + return new CreateCanonicalClosedAdmissionPointerRequest( + required(outcome, "request_id", UUID.class), + required(outcome, "target_namespace", String.class), + required(outcome, "canonical_tenant_id", UUID.class), + required(outcome, "realm_id", UUID.class), + required(outcome, "catalog_creation_request_id", UUID.class), + required(outcome, "catalog_revision", Long.class), + required(outcome, "actor_principal", String.class), + required(outcome, "reason", String.class)); + } + + private static void requireSameRequest( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest) { + if (!request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class))) { + throw new CanonicalClosedPointerConflictException( + "Canonical CLOSED pointer request identity was reused with changed input"); + } + } + + private static void requireExactInitialCatalog( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!catalog.visible() + || !catalog.publicProduction() + || catalog.catalogRevision() != request.catalogRevision() + || catalog.catalogRevision() != INITIAL_POINTER_VERSION + || !request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId())) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer request does not identify the exact initial public catalog"); + } + } + + private static void requireOutcomeMatches( + Record outcome, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + String receiptDigest, + long eventId, + Instant updatedAt) { + if (!CLOSED.equals(required(outcome, "admission_state", String.class)) + || required(outcome, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(outcome, "audit_event_id", Long.class) != eventId + || !request.requestId().equals(required(outcome, "request_id", UUID.class)) + || !request.targetNamespace().equals(required(outcome, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(outcome, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(outcome, "realm_id", UUID.class)) + || !request + .catalogCreationRequestId() + .equals(required(outcome, "catalog_creation_request_id", UUID.class)) + || request.catalogRevision() != required(outcome, "catalog_revision", Long.class) + || !requestDigest.equals(required(outcome, "request_digest", String.class)) + || !receiptDigest.equals(required(outcome, "receipt_digest", String.class)) + || !catalog + .requestDigest() + .equals(required(outcome, "catalog_request_digest", String.class)) + || !catalog + .receiptDigest() + .equals(required(outcome, "catalog_receipt_digest", String.class)) + || !request.actorPrincipal().equals(required(outcome, "actor_principal", String.class)) + || !request.reason().equals(required(outcome, "reason", String.class)) + || !updatedAt.equals(outcomeTimestamp(outcome))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome conflicts with its request or catalog authority"); + } + } + + private static void requirePointerMatches( + Record pointer, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + Instant updatedAt) { + if (required(pointer, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(pointer, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(pointer, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(pointer, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(pointer, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(pointer, "realm_slug", String.class)) + || required(pointer, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(pointer, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(pointer, "admission_state", String.class)) + || pointer.get("tenant_id", Long.class) != null + || pointer.get("game_instance_id", Long.class) != null + || pointer.get("playable_state_namespace_id", UUID.class) != null + || hasLegacyPointerCatalogCopy(pointer) + || !updatedAt.equals(toInstant(pointer.get("created_at", java.time.LocalDateTime.class))) + || !updatedAt.equals(toInstant(pointer.get("updated_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer row is aliased, policy-copied or inconsistent with its catalog"); + } + } + + private static boolean hasLegacyPointerCatalogCopy(Record pointer) { + return pointer.get("world_display_name", String.class) != null + || pointer.get("realm_display_name", String.class) != null + || pointer.get("visible", Boolean.class) != null + || pointer.get("public_production_realm", Boolean.class) != null + || pointer.get("requires_character_selection", Boolean.class) != null + || pointer.get("state_scope", String.class) != null + || pointer.get("character_creation_policy", String.class) != null + || pointer.get("last_updated_by", String.class) != null + || pointer.get("last_update_reason", String.class) != null; + } + + private static void requireEventMatches( + Record event, + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + long eventId, + Instant updatedAt) { + if (required(event, "id", Long.class) != eventId + || required(event, "representation_version", Integer.class) + != CANONICAL_REPRESENTATION_VERSION + || !request.targetNamespace().equals(required(event, "target_namespace", String.class)) + || !request.canonicalTenantId().equals(required(event, "canonical_tenant_id", UUID.class)) + || !request.realmId().equals(required(event, "realm_id", UUID.class)) + || !catalog.worldSlug().equals(required(event, "world_slug", String.class)) + || !catalog.realmSlug().equals(required(event, "realm_slug", String.class)) + || required(event, "pointer_version", Long.class) != INITIAL_POINTER_VERSION + || required(event, "catalog_revision", Long.class) != request.catalogRevision() + || !CLOSED.equals(required(event, "admission_state", String.class)) + || !request + .requestId() + .toString() + .equals(required(event, "control_plane_request_id", String.class)) + || !request.actorPrincipal().equals(required(event, "actor_principal", String.class)) + || !request.reason().equals(required(event, "reason", String.class)) + || event.get("tenant_id", Long.class) != null + || event.get("game_instance_id", Long.class) != null + || event.get("prepared_version_upgrade_id", String.class) != null + || hasLegacyEventCatalogCopy(event) + || !updatedAt.equals(toInstant(event.get("occurred_at", java.time.LocalDateTime.class)))) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer audit event conflicts with its pointer or catalog authority"); + } + } + + private static boolean hasLegacyEventCatalogCopy(Record event) { + return event.get("world_display_name", String.class) != null + || event.get("realm_display_name", String.class) != null + || event.get("visible", Boolean.class) != null + || event.get("public_production_realm", Boolean.class) != null + || event.get("requires_character_selection", Boolean.class) != null + || event.get("state_scope", String.class) != null + || event.get("character_creation_policy", String.class) != null; + } + + private static Instant outcomeTimestamp(Record outcome) { + OffsetDateTime updatedAt = required(outcome, "updated_at", OffsetDateTime.class); + return updatedAt.toInstant(); + } + + static String requestDigest( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return digest(requestDigestFields(request, catalog)); + } + + private static List requestDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, CanonicalRealmCatalogSnapshot catalog) { + return List.of( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + request.actorPrincipal(), + request.reason(), + CLOSED, + ABSENT); + } + + static String receiptDigest( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + return digest(receiptDigestFields(request, catalog, requestDigest, auditEventId, updatedAt)); + } + + private static List receiptDigestFields( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalog, + String requestDigest, + long auditEventId, + Instant updatedAt) { + requirePositive(auditEventId, "auditEventId"); + return List.of( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.requestId().toString(), + requestDigest, + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + catalog.worldSlug(), + catalog.realmSlug(), + Long.toString(INITIAL_POINTER_VERSION), + Long.toString(request.catalogRevision()), + Long.toString(auditEventId), + Objects.requireNonNull(updatedAt, "updatedAt").toString(), + CLOSED, + ABSENT); + } + + private static String digest(List fields) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : fields) { + byte[] bytes = strictUtf8(value); + 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 byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8 text", exception); + } + } + + private static void requireReadSelector(String targetNamespace, UUID requestId) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(requestId, "requestId"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requirePositive(long value, String name) { + if (value <= 0L) { + throw new InvalidCanonicalClosedPointerEvidenceException(name + " must be positive"); + } + } + + private static T required(Record record, String fieldName, Class type) { + T value = record.get(fieldName, type); + if (value == null) { + throw new InvalidCanonicalClosedPointerEvidenceException( + "Persisted canonical CLOSED pointer " + fieldName + " is missing"); + } + return value; + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical CLOSED pointer DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical CLOSED pointer operation requires a committed-outcome owner read"); + } + } + + /** + * Opaque preflight result; callers cannot construct a preparation or change its catalog proof. + */ + public static final class PreparedInitialClosed { + private final CreateCanonicalClosedAdmissionPointerRequest request; + private final CanonicalRealmCatalogSnapshot catalogSnapshot; + private final String requestDigest; + + private PreparedInitialClosed( + CreateCanonicalClosedAdmissionPointerRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + String requestDigest) { + this.request = Objects.requireNonNull(request, "request"); + this.catalogSnapshot = Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + this.requestDigest = Objects.requireNonNull(requestDigest, "requestDigest"); + } + + private CreateCanonicalClosedAdmissionPointerRequest request() { + return request; + } + + private CanonicalRealmCatalogSnapshot catalogSnapshot() { + return catalogSnapshot; + } + + private String requestDigest() { + return requestDigest; + } + } + + /** Opaque committed-origin preflight; callers cannot construct it or replace its exact origin. */ + public static final class PreparedExpectedClosed { + private final CanonicalClosedAdmissionPointerSnapshot committedOrigin; + private final long expectedPointerVersion; + private final long expectedCatalogRevision; + + private PreparedExpectedClosed( + CanonicalClosedAdmissionPointerSnapshot committedOrigin, + long expectedPointerVersion, + long expectedCatalogRevision) { + this.committedOrigin = Objects.requireNonNull(committedOrigin, "committedOrigin"); + this.expectedPointerVersion = expectedPointerVersion; + this.expectedCatalogRevision = expectedCatalogRevision; + } + + private CanonicalClosedAdmissionPointerSnapshot committedOrigin() { + return committedOrigin; + } + + private long expectedPointerVersion() { + return expectedPointerVersion; + } + + private long expectedCatalogRevision() { + return expectedCatalogRevision; + } + } + + /** + * Opaque local evidence that the exact original canonical CLOSED v1 pointer, its creation event, + * immutable request outcome, and initial catalog were positively verified under owner locks. This + * evidence is not caller authentication, World lifecycle or hold evidence, or OPEN authority. + */ + public static final class ExpectedClosedEvidence { + private final CanonicalClosedAdmissionPointerSnapshot verifiedOrigin; + + private ExpectedClosedEvidence(CanonicalClosedAdmissionPointerSnapshot verifiedOrigin) { + this.verifiedOrigin = Objects.requireNonNull(verifiedOrigin, "verifiedOrigin"); + } + + public String targetNamespace() { + return verifiedOrigin.targetNamespace(); + } + + public UUID originalRequestId() { + return verifiedOrigin.requestId(); + } + + public UUID canonicalTenantId() { + return verifiedOrigin.canonicalTenantId(); + } + + public UUID realmId() { + return verifiedOrigin.realmId(); + } + + public long pointerVersion() { + return verifiedOrigin.pointerVersion(); + } + + public long catalogRevision() { + return verifiedOrigin.catalogRevision(); + } + + public String requestDigest() { + return verifiedOrigin.requestDigest(); + } + + public String receiptDigest() { + return verifiedOrigin.receiptDigest(); + } + + public long auditEventId() { + return verifiedOrigin.auditEventId(); + } + + public boolean isNeverOpenOrigin() { + return CLOSED.equals(verifiedOrigin.admissionState()) + && verifiedOrigin.pointerVersion() == INITIAL_POINTER_VERSION + && verifiedOrigin.admissibleGameInstanceId() == null; + } + } + + public static class CanonicalClosedPointerConflictException extends IllegalStateException { + public CanonicalClosedPointerConflictException(String message) { + super(message); + } + + public CanonicalClosedPointerConflictException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class InvalidCanonicalClosedPointerEvidenceException extends IllegalStateException { + public InvalidCanonicalClosedPointerEvidenceException(String message) { + super(message); + } + + public InvalidCanonicalClosedPointerEvidenceException(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 new file mode 100644 index 0000000000..1115835f64 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -0,0 +1,1148 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +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.jooq.Field; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Game Session-owned immutable initial realm catalog creation and exact readback. + * + *

This is an unwired catalog source. It never creates or opens an admission pointer and does not + * establish World lifecycle, membership, entitlement, or creator authorization. + */ +@Repository +public class GameSessionCanonicalRealmCatalogRepository { + private static final int SCHEMA_VERSION = 1; + private static final long INITIAL_CATALOG_REVISION = 1L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String REQUEST_DOMAIN = "game-session-canonical-realm-catalog-request/v1"; + private static final String RECEIPT_DOMAIN = "game-session-canonical-realm-catalog-receipt/v1"; + + private static final Table CATALOG = + DSL.table(DSL.name("game_session_canonical_realm_catalog")); + private static final Table SHARED_NAMESPACES = + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")); + + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field TENANT_SLUG = DSL.field(DSL.name("tenant_slug"), String.class); + private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field REALM_SLUG = DSL.field(DSL.name("realm_slug"), String.class); + private static final Field REALM_DISPLAY_NAME = + DSL.field(DSL.name("realm_display_name"), String.class); + private static final Field VISIBLE = DSL.field(DSL.name("visible"), Boolean.class); + private static final Field PUBLIC_PRODUCTION = + DSL.field(DSL.name("public_production"), Boolean.class); + private static final Field STATE_SCOPE = DSL.field(DSL.name("state_scope"), String.class); + private static final Field PLAYABLE_STATE_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + private static final Field CHARACTER_CREATION_POLICY = + DSL.field(DSL.name("character_creation_policy"), String.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.class); + private static final Field CREATION_REQUEST_ID = + DSL.field(DSL.name("creation_request_id"), UUID.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + private static final Field SOURCE_INTAKE_OPERATION_ID = + DSL.field(DSL.name("source_intake_operation_id"), UUID.class); + private static final Field SOURCE_INTAKE_SCHEMA_VERSION = + DSL.field(DSL.name("source_intake_schema_version"), Integer.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.class); + private static final Field SOURCE_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("source_intake_request_digest"), String.class); + private static final Field SOURCE_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("source_intake_receipt_digest"), String.class); + private static final Field SOURCE_SCHEMA_VERSION = + DSL.field(DSL.name("source_schema_version"), Integer.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field SOURCE_REQUEST_DIGEST = + DSL.field(DSL.name("source_request_digest"), String.class); + private static final Field SOURCE_WORLD_DISPLAY_NAME = + DSL.field(DSL.name("source_world_display_name"), String.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("source_provenance_kind"), String.class); + private static final Field BINDING_PROVENANCE_KIND = + DSL.field(DSL.name("provenance_kind"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + + private static final Field LEGACY_TENANT_ID = DSL.field(DSL.name("tenant_id"), Long.class); + private static final Field SHARED_NAMESPACE_ID = + DSL.field(DSL.name("playable_state_namespace_id"), UUID.class); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "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"); + } + + /** + * Resolves exact committed authored-world evidence before the catalog write transaction begins. + * 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(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from committed Game Session owner storage"); + } + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt committedSource = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, committedSource.source()); + requireRequestMatchesSource(request, committedSource); + requireFreshSource(committedSource.source()); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + return new PreparedInitialPublicProduction(request, committedSource); + } + + /** + * Creates one public-production catalog snapshot under the caller's read-write owner transaction. + * Exact retries read back the original immutable result; changed intent conflicts. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot createInitialPublicProduction( + PreparedInitialPublicProduction prepared) { + Objects.requireNonNull(prepared, "prepared"); + CreateCanonicalRealmCatalogRequest request = prepared.request(); + requireWritableOwnerTransaction(); + + IntakeReceipt sourceReceipt = lockAndReadFreshSource(request); + if (!prepared.committedSource().equals(sourceReceipt)) { + throw new InvalidCatalogEvidenceException( + "Committed authored-world evidence changed before canonical catalog creation"); + } + // Retained association capture locks the V6 namespace family before committing an association. + // Taking the same relation lock before this check serializes both SHARED and ISOLATED creation + // against that owner transaction without deriving a link to any retained numeric tenant. + dsl.execute("LOCK TABLE gameplay_tenant_shared_playable_state_namespace IN ROW EXCLUSIVE MODE"); + requireNoRetainedTenantAssociation(request.targetNamespace(), request.canonicalTenantId()); + + String requestDigest = requestDigest(request, sourceReceipt); + Record existing = findByRequest(request.targetNamespace(), request.requestId()); + if (existing != null) { + return requireExactRetry(existing, request, sourceReceipt, requestDigest); + } + if (findPublicForTenant(request.targetNamespace(), request.canonicalTenantId()) != null) { + throw new CatalogConflictException( + "Canonical tenant already has a public-production realm catalog result"); + } + if (findByRealmSlug(request.targetNamespace(), request.canonicalTenantId(), request.realmSlug()) + != null) { + throw new CatalogConflictException("Realm selector is already owned by this tenant"); + } + + UUID realmId = UUID.randomUUID(); + requireNonNil(realmId, "allocated realmId"); + UUID namespaceId = + "SHARED".equals(request.stateScope()) + ? getOrCreateSharedNamespace(request.targetNamespace(), sourceReceipt) + : allocateIsolatedNamespace(); + UUID namespace = namespaceId; + String receiptDigest = + receiptDigest( + request, sourceReceipt, realmId, namespace, INITIAL_CATALOG_REVISION, requestDigest); + + int inserted = + dsl.insertInto(CATALOG) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(TENANT_SLUG, sourceReceipt.source().tenantSlug()) + .set(WORLD_SLUG, sourceReceipt.source().worldSlug()) + .set(REALM_ID, realmId) + .set(REALM_SLUG, request.realmSlug()) + .set(REALM_DISPLAY_NAME, request.realmDisplayName()) + .set(VISIBLE, request.visible()) + .set(PUBLIC_PRODUCTION, request.publicProduction()) + .set(STATE_SCOPE, request.stateScope()) + .set(PLAYABLE_STATE_NAMESPACE_ID, namespace) + .set(CHARACTER_CREATION_POLICY, request.characterCreationPolicy()) + .set(CATALOG_REVISION, INITIAL_CATALOG_REVISION) + .set(CREATION_REQUEST_ID, request.requestId()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, sourceReceipt.source().schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, sourceReceipt.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, sourceReceipt.source().operationId()) + .set(SOURCE_REQUEST_DIGEST, sourceReceipt.source().requestDigest()) + .set(SOURCE_WORLD_DISPLAY_NAME, sourceReceipt.source().worldDisplayName()) + .set(SOURCE_GAME_ROW_ID, sourceReceipt.source().sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, sourceReceipt.source().sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, sourceReceipt.source().provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, sourceReceipt.source().evidenceDigest()) + .onConflictDoNothing() + .execute(); + + Record persisted = findByRequest(request.targetNamespace(), request.requestId()); + if (persisted == null) { + if (inserted == 0) { + throw new CatalogConflictException( + "Canonical realm selector or public-production claim conflicts with existing authority"); + } + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog creation did not read back its persisted request"); + } + return requireExactRetry(persisted, request, sourceReceipt, requestDigest); + } + + /** Reads one exact immutable result by its stable creation request identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRequest( + String targetNamespace, UUID requestId) { + requireReadSelector(targetNamespace, requestId); + requireCommittedRead(); + Record record = findByRequest(targetNamespace, requestId); + return record == null ? Optional.empty() : Optional.of(toSnapshot(record)); + } + + /** Reads one exact canonical realm catalog row by its full owner identity. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readByRealm( + String targetNamespace, UUID canonicalTenantId, UUID realmId) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + requireCommittedRead(); + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId))) + .fetchOne(); + return record == null ? Optional.empty() : Optional.of(toSnapshot(record)); + } + + /** + * Locks and fully verifies one exact initial public-production catalog row in the caller's owner + * transaction. The returned snapshot is produced by the same validation used for committed + * catalog reads; callers must compare it with their committed preflight snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot lockExactInitialPublicProduction( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID creationRequestId, + long catalogRevision) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + requireNonNil(creationRequestId, "creationRequestId"); + if (catalogRevision != INITIAL_CATALOG_REVISION) { + throw new CatalogConflictException( + "Initial public-production catalog revision must be exactly one"); + } + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId)) + .and(CREATION_REQUEST_ID.eq(creationRequestId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .forUpdate() + .fetchOne(); + if (record == null) { + throw new InvalidCatalogEvidenceException( + "Exact initial public-production catalog row is missing from Game Session owner storage"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(record); + if (!snapshot.visible() + || !snapshot.publicProduction() + || snapshot.catalogRevision() != INITIAL_CATALOG_REVISION + || !snapshot.targetNamespace().equals(targetNamespace) + || !snapshot.tenantId().equals(canonicalTenantId) + || !snapshot.realmId().equals(realmId) + || !snapshot.creationRequestId().equals(creationRequestId)) { + throw new InvalidCatalogEvidenceException( + "Locked catalog row is not the exact initial public-production authority"); + } + return snapshot; + } + + /** Locks one exact catalog target by its canonical identity in the caller's owner transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalRealmCatalogSnapshot lockInitialAdmissionTarget( + String targetNamespace, UUID canonicalTenantId, UUID realmId, long catalogRevision) { + requireWritableOwnerTransaction(); + requireReadSelector(targetNamespace, canonicalTenantId); + requireNonNil(realmId, "realmId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + Record record = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(REALM_ID.eq(realmId)) + .and(CATALOG_REVISION.eq(catalogRevision))) + .forUpdate() + .fetchOne(); + if (record == null) { + throw new InvalidCatalogEvidenceException( + "Exact canonical initial-admission catalog row is missing or stale"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(record); + if (!snapshot.visible() + || !snapshot.publicProduction() + || !snapshot.targetNamespace().equals(targetNamespace) + || !snapshot.tenantId().equals(canonicalTenantId) + || !snapshot.realmId().equals(realmId) + || snapshot.catalogRevision() != catalogRevision) { + throw new InvalidCatalogEvidenceException( + "Locked catalog row is not the exact visible public-production realm target"); + } + return snapshot; + } + + /** + * Returns the unique visible public-production catalog snapshot, or no authority when absent. + * Multiple or internally conflicting results fail closed rather than selecting by order. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public Optional readUniqueVisiblePublicProduction( + String targetNamespace, UUID canonicalTenantId) { + requireReadSelector(targetNamespace, canonicalTenantId); + requireCommittedRead(); + var rows = + dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(canonicalTenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .orderBy(CREATION_REQUEST_ID.asc()) + .limit(2) + .fetch(); + if (rows.isEmpty()) { + return Optional.empty(); + } + if (rows.size() != 1) { + throw new CatalogConflictException( + "Public-production catalog authority is ambiguous for this canonical tenant"); + } + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(rows.getFirst()); + if (!snapshot.visible() || !snapshot.publicProduction()) { + throw new InvalidCatalogEvidenceException( + "Public-production catalog readback is not visible player-addressable authority"); + } + return Optional.of(snapshot); + } + + /** + * Reads every persisted public-production catalog candidate for player discovery. The caller + * composes each row with the current canonical OPEN pointer and its exact terminal proof; this + * method is only the catalog half of that read and never manufactures routing authority. + */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public List readVisiblePublicProductionSnapshots( + String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireCommittedRead(); + return dsl.selectFrom(CATALOG) + .where(TARGET_NAMESPACE.eq(targetNamespace).and(PUBLIC_PRODUCTION.isTrue())) + .orderBy(CANONICAL_TENANT_ID.asc(), REALM_ID.asc()) + .fetch() + .map(this::toSnapshot); + } + + private IntakeReceipt lockAndReadFreshSource(CreateCanonicalRealmCatalogRequest request) { + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? FOR UPDATE", + request.targetNamespace(), + request.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException( + "Canonical tenant source binding is missing from Game Session owner storage"); + } + + // Lock order is stable: tenant source-binding row, then exact authored-world intake row, + // followed by the shared-namespace family serialization lock in createInitialPublicProduction. + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + request.targetNamespace(), + request.sourceIntakeOperationId()); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Exact committed authored-world source intake is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + requireTenantBindingMatches(binding, receipt.source()); + requireRequestMatchesSource(request, receipt); + requireFreshSource(receipt.source()); + return receipt; + } + + private void requireRequestMatchesSource( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt receipt) { + if (!request.targetNamespace().equals(receipt.source().targetNamespace()) + || !request.canonicalTenantId().equals(receipt.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(receipt.operationId())) { + throw new InvalidCatalogEvidenceException( + "Authored-world source intake does not match the exact requested tenant scope"); + } + } + + private UUID getOrCreateSharedNamespace(String targetNamespace, IntakeReceipt sourceReceipt) { + UUID tenantId = sourceReceipt.source().canonicalTenantId(); + Record current = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (current != null) { + UUID currentId = required(current, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + validateSharedNamespaceSource(current); + if (!targetNamespace.equals(required(current, TARGET_NAMESPACE, "shared namespace target"))) { + throw new CatalogConflictException( + "Canonical tenant shared namespace belongs to a different Game Session namespace"); + } + if (current.get(LEGACY_TENANT_ID) != null) { + throw new InvalidCatalogEvidenceException( + "Canonical shared namespace conflicts with an existing numeric namespace row"); + } + return currentId; + } + + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated shared namespace"); + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + int inserted = + dsl.insertInto(SHARED_NAMESPACES) + .set(LEGACY_TENANT_ID, (Long) null) + .set(SHARED_NAMESPACE_ID, namespaceId) + .set(CANONICAL_TENANT_ID, tenantId) + .set(TARGET_NAMESPACE, targetNamespace) + .set(SOURCE_INTAKE_OPERATION_ID, sourceReceipt.operationId()) + .set(SOURCE_INTAKE_SCHEMA_VERSION, SCHEMA_VERSION) + .set(SOURCE_INTAKE_REQUEST_ID, sourceReceipt.intakeRequestId()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, sourceReceipt.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, sourceReceipt.receiptDigest()) + .set(SOURCE_SCHEMA_VERSION, source.schemaVersion()) + .set(SOURCE_REGISTRATION_REQUEST_ID, source.registrationRequestId()) + .set(SOURCE_OPERATION_ID, source.operationId()) + .set(SOURCE_REQUEST_DIGEST, source.requestDigest()) + .set(SOURCE_GAME_ROW_ID, source.sourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, source.sourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, source.provenanceKind()) + .set(SOURCE_EVIDENCE_DIGEST, source.evidenceDigest()) + .onConflictDoNothing() + .execute(); + if (inserted == 0) { + Record raced = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ? FOR UPDATE", + tenantId); + if (raced != null) { + validateSharedNamespaceSource(raced); + if (raced.get(LEGACY_TENANT_ID) == null + && targetNamespace.equals( + required(raced, TARGET_NAMESPACE, "shared namespace target"))) { + return required(raced, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + } + throw new CatalogConflictException("Canonical shared namespace allocation conflicts"); + } + Record persisted = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenantId); + if (persisted == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace allocation did not read back from Game Session storage"); + } + validateSharedNamespaceSource(persisted); + return required(persisted, SHARED_NAMESPACE_ID, "shared playable-state namespace"); + } + + private UUID allocateIsolatedNamespace() { + UUID namespaceId = UUID.randomUUID(); + requireNonNil(namespaceId, "allocated isolated namespace"); + if (dsl.fetchOne( + "SELECT playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new CatalogConflictException( + "Allocated isolated namespace collides with shared identity"); + } + return namespaceId; + } + + private void validateSharedNamespaceSource(Record namespace) { + UUID tenantId = required(namespace, CANONICAL_TENANT_ID, "canonical shared tenant id"); + String targetNamespace = required(namespace, TARGET_NAMESPACE, "shared namespace target"); + UUID intakeOperation = + required(namespace, SOURCE_INTAKE_OPERATION_ID, "shared namespace source operation"); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + targetNamespace, + intakeOperation); + if (intake == null) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace source intake readback is missing"); + } + IntakeReceipt receipt = toIntakeReceipt(intake); + AuthoredWorldSourceEvidence source = receipt.source(); + if (!tenantId.equals(source.canonicalTenantId()) + || !targetNamespace.equals(source.targetNamespace()) + || !receipt + .intakeRequestId() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_ID, "shared namespace intake request")) + || !receipt + .requestDigest() + .equals( + required(namespace, SOURCE_INTAKE_REQUEST_DIGEST, "shared namespace intake digest")) + || !receipt + .receiptDigest() + .equals( + required( + namespace, SOURCE_INTAKE_RECEIPT_DIGEST, "shared namespace receipt digest")) + || !source + .registrationRequestId() + .equals( + required( + namespace, SOURCE_REGISTRATION_REQUEST_ID, "shared namespace registration")) + || !source + .operationId() + .equals(required(namespace, SOURCE_OPERATION_ID, "shared namespace source operation")) + || !source + .requestDigest() + .equals( + required( + namespace, SOURCE_REQUEST_DIGEST, "shared namespace source request digest")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(namespace, SOURCE_GAME_ROW_ID, "shared namespace source row")) + || !source + .sourceGameTenantKey() + .equals( + required(namespace, SOURCE_GAME_TENANT_KEY, "shared namespace source tenant key")) + || !source + .provenanceKind() + .equals(required(namespace, SOURCE_PROVENANCE_KIND, "shared namespace provenance")) + || !source + .evidenceDigest() + .equals( + required(namespace, SOURCE_EVIDENCE_DIGEST, "shared namespace evidence digest"))) { + throw new InvalidCatalogEvidenceException( + "Fresh shared namespace differs from its immutable authored-world source receipt"); + } + requireFreshSource(source); + requireNoRetainedTenantAssociation(targetNamespace, tenantId); + } + + private CanonicalRealmCatalogSnapshot requireExactRetry( + Record existing, + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + String expectedRequestDigest) { + CanonicalRealmCatalogSnapshot snapshot = toSnapshot(existing); + if (!request.requestId().equals(snapshot.creationRequestId()) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !sourceReceipt.equals(snapshot.sourceIntakeReceipt())) { + throw new CatalogConflictException( + "Canonical realm creation request identity was reused with changed input or source evidence"); + } + return snapshot; + } + + private CanonicalRealmCatalogSnapshot toSnapshot(Record record) { + try { + IntakeReceipt sourceReceipt = toCatalogSourceReceipt(record); + UUID requestId = required(record, CREATION_REQUEST_ID, "catalog request id"); + String targetNamespace = required(record, TARGET_NAMESPACE, "catalog target namespace"); + UUID canonicalTenantId = required(record, CANONICAL_TENANT_ID, "catalog tenant id"); + UUID sourceIntakeOperationId = + required(record, SOURCE_INTAKE_OPERATION_ID, "catalog source intake operation"); + String realmSlug = required(record, REALM_SLUG, "catalog realm slug"); + String realmDisplayName = required(record, REALM_DISPLAY_NAME, "catalog realm display name"); + boolean visible = Boolean.TRUE.equals(record.get(VISIBLE)); + boolean publicProduction = Boolean.TRUE.equals(record.get(PUBLIC_PRODUCTION)); + String stateScope = required(record, STATE_SCOPE, "catalog state scope"); + String characterCreationPolicy = + required(record, CHARACTER_CREATION_POLICY, "catalog character-creation policy"); + String expectedRequestDigest = + requestDigest( + requestId, + targetNamespace, + canonicalTenantId, + sourceIntakeOperationId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + characterCreationPolicy, + sourceReceipt); + String persistedRequestDigest = required(record, REQUEST_DIGEST, "catalog request digest"); + UUID realmId = required(record, REALM_ID, "catalog realm id"); + UUID namespaceId = + required(record, PLAYABLE_STATE_NAMESPACE_ID, "catalog playable-state namespace"); + long revision = required(record, CATALOG_REVISION, "catalog revision"); + String expectedReceiptDigest = + receiptDigest( + targetNamespace, + canonicalTenantId, + requestId, + sourceReceipt, + realmId, + namespaceId, + revision, + persistedRequestDigest); + if (!expectedRequestDigest.equals(persistedRequestDigest) + || !expectedReceiptDigest.equals( + required(record, RECEIPT_DIGEST, "catalog receipt digest"))) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog request or receipt digest does not match its contents"); + } + + verifyPersistedSourceReceipt(sourceReceipt); + verifyNamespaceSelection( + targetNamespace, canonicalTenantId, stateScope, realmId, namespaceId); + return new CanonicalRealmCatalogSnapshot( + targetNamespace, + canonicalTenantId, + required(record, TENANT_SLUG, "catalog tenant slug"), + required(record, WORLD_SLUG, "catalog world slug"), + realmId, + realmSlug, + realmDisplayName, + visible, + publicProduction, + stateScope, + namespaceId, + characterCreationPolicy, + revision, + requestId, + persistedRequestDigest, + required(record, RECEIPT_DIGEST, "catalog receipt digest"), + sourceReceipt); + } catch (InvalidCatalogEvidenceException | CatalogConflictException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidCatalogEvidenceException( + "Persisted canonical realm catalog evidence is invalid", exception); + } + } + + private void verifyNamespaceSelection( + String targetNamespace, + UUID canonicalTenantId, + String stateScope, + UUID realmId, + UUID namespaceId) { + if ("SHARED".equals(stateScope)) { + Record shared = + dsl.fetchOne( + "SELECT * FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + canonicalTenantId); + if (shared == null + || shared.get(LEGACY_TENANT_ID) != null + || !namespaceId.equals(required(shared, SHARED_NAMESPACE_ID, "shared namespace id"))) { + throw new InvalidCatalogEvidenceException( + "SHARED realm catalog does not resolve to its canonical tenant namespace row"); + } + validateSharedNamespaceSource(shared); + } else { + if (dsl.fetchOne( + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE playable_state_namespace_id = ?", + namespaceId) + != null) { + throw new InvalidCatalogEvidenceException( + "ISOLATED realm namespace conflicts with the canonical tenant SHARED namespace"); + } + List sameNamespace = + dsl.select(REALM_ID) + .from(CATALOG) + .where(PLAYABLE_STATE_NAMESPACE_ID.eq(namespaceId).and(STATE_SCOPE.eq("ISOLATED"))) + .limit(2) + .fetch(); + if (sameNamespace.size() > 1 + || (sameNamespace.size() == 1 + && !realmId.equals(sameNamespace.getFirst().get(REALM_ID)))) { + throw new InvalidCatalogEvidenceException( + "ISOLATED playable-state namespace is already owned by another realm"); + } + } + requireNoRetainedTenantAssociation(targetNamespace, canonicalTenantId); + } + + private void verifyPersistedSourceReceipt(IntakeReceipt expected) { + AuthoredWorldSourceEvidence source = expected.source(); + Record binding = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_tenant_source_binding " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + source.targetNamespace(), + source.canonicalTenantId()); + if (binding == null) { + throw new InvalidCatalogEvidenceException("Persisted tenant source binding is missing"); + } + requireTenantBindingMatches(binding, source); + Record intake = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ?", + source.targetNamespace(), + expected.operationId()); + if (intake == null || !expected.equals(toIntakeReceipt(intake))) { + throw new InvalidCatalogEvidenceException( + "Canonical realm catalog does not match exact immutable source-intake readback"); + } + requireFreshSource(source); + } + + private IntakeReceipt toCatalogSourceReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(record, SOURCE_SCHEMA_VERSION, "source schema version"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required(record, SOURCE_WORLD_DISPLAY_NAME, "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required(record, SOURCE_PROVENANCE_KIND, "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + if (!Integer.valueOf(SCHEMA_VERSION) + .equals(required(record, SOURCE_INTAKE_SCHEMA_VERSION, "source intake schema version"))) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, SOURCE_INTAKE_OPERATION_ID, "source intake operation"), + required(record, SOURCE_INTAKE_REQUEST_ID, "source intake request"), + required(record, SOURCE_INTAKE_REQUEST_DIGEST, "source intake request digest"), + source, + required(record, SOURCE_INTAKE_RECEIPT_DIGEST, "source intake receipt digest")); + } + + private IntakeReceipt toIntakeReceipt(Record record) { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required( + record, + DSL.field(DSL.name("source_schema_version"), Integer.class), + "source schema"), + required(record, TARGET_NAMESPACE, "source target namespace"), + required(record, SOURCE_REGISTRATION_REQUEST_ID, "source registration request"), + required(record, SOURCE_OPERATION_ID, "source operation"), + required(record, SOURCE_REQUEST_DIGEST, "source request digest"), + required(record, CANONICAL_TENANT_ID, "source canonical tenant"), + required(record, TENANT_SLUG, "source tenant slug"), + required(record, WORLD_SLUG, "source world slug"), + required( + record, + DSL.field(DSL.name("world_display_name"), String.class), + "source world display name"), + required(record, SOURCE_GAME_ROW_ID, "source game row"), + required(record, SOURCE_GAME_TENANT_KEY, "source game tenant key"), + required( + record, + DSL.field(DSL.name("source_provenance_kind"), String.class), + "source provenance"), + required(record, SOURCE_EVIDENCE_DIGEST, "source evidence digest")); + Integer intakeSchema = + required(record, DSL.field(DSL.name("schema_version"), Integer.class), "intake schema"); + if (!Integer.valueOf(SCHEMA_VERSION).equals(intakeSchema)) { + throw new InvalidCatalogEvidenceException( + "Unsupported persisted source-intake schema version"); + } + return new IntakeReceipt( + required(record, DSL.field(DSL.name("operation_id"), UUID.class), "intake operation"), + required(record, DSL.field(DSL.name("intake_request_id"), UUID.class), "intake request"), + required( + record, DSL.field(DSL.name("request_digest"), String.class), "intake request digest"), + source, + required( + record, DSL.field(DSL.name("receipt_digest"), String.class), "intake receipt digest")); + } + + private void requireTenantBindingMatches(Record binding, AuthoredWorldSourceEvidence source) { + if (!source + .targetNamespace() + .equals(required(binding, TARGET_NAMESPACE, "tenant binding namespace")) + || !source + .canonicalTenantId() + .equals(required(binding, CANONICAL_TENANT_ID, "tenant binding canonical id")) + || !source.tenantSlug().equals(required(binding, TENANT_SLUG, "tenant binding slug")) + || !Long.valueOf(source.sourceGameRowId()) + .equals(required(binding, SOURCE_GAME_ROW_ID, "tenant binding source row")) + || !source + .sourceGameTenantKey() + .equals(required(binding, SOURCE_GAME_TENANT_KEY, "tenant binding source key")) + || !source + .provenanceKind() + .equals(required(binding, BINDING_PROVENANCE_KIND, "tenant binding provenance"))) { + throw new InvalidCatalogEvidenceException( + "Authored-world receipt conflicts with the immutable canonical tenant source binding"); + } + } + + private void requireFreshSource(AuthoredWorldSourceEvidence source) { + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidCatalogEvidenceException( + "Initial canonical catalog creation requires fresh Game Design tenant source provenance"); + } + } + + private void requireNoRetainedTenantAssociation(String targetNamespace, UUID canonicalTenantId) { + if (dsl.fetchOne( + "SELECT operation_id FROM game_session_retained_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + targetNamespace, + canonicalTenantId) + != null) { + throw new CatalogConflictException( + "Canonical tenant already has retained numeric Game Session identity evidence"); + } + } + + private Record findByRequest(String targetNamespace, UUID requestId) { + return dsl.selectFrom(CATALOG) + .where(TARGET_NAMESPACE.eq(targetNamespace).and(CREATION_REQUEST_ID.eq(requestId))) + .fetchOne(); + } + + private Record findPublicForTenant(String targetNamespace, UUID tenantId) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(PUBLIC_PRODUCTION.isTrue())) + .fetchOne(); + } + + private Record findByRealmSlug(String targetNamespace, UUID tenantId, String realmSlug) { + return dsl.selectFrom(CATALOG) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CANONICAL_TENANT_ID.eq(tenantId)) + .and(REALM_SLUG.eq(realmSlug))) + .fetchOne(); + } + + static String requestDigest( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt sourceReceipt) { + return requestDigest( + request.requestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.sourceIntakeOperationId(), + request.realmSlug(), + request.realmDisplayName(), + request.visible(), + request.publicProduction(), + request.stateScope(), + request.characterCreationPolicy(), + sourceReceipt); + } + + private static String requestDigest( + UUID requestId, + String targetNamespace, + UUID canonicalTenantId, + UUID sourceIntakeOperationId, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope, + String characterCreationPolicy, + IntakeReceipt sourceReceipt) { + AuthoredWorldSourceEvidence source = sourceReceipt.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + requestId.toString(), + targetNamespace, + canonicalTenantId.toString(), + 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(), + realmSlug, + realmDisplayName, + Boolean.toString(visible), + Boolean.toString(publicProduction), + stateScope, + characterCreationPolicy, + "ABSENT", + "ABSENT"); + } + + private static String receiptDigest( + CreateCanonicalRealmCatalogRequest request, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return receiptDigest( + request.targetNamespace(), + request.canonicalTenantId(), + request.requestId(), + sourceReceipt, + realmId, + namespaceId, + revision, + requestDigest); + } + + private static String receiptDigest( + String targetNamespace, + UUID canonicalTenantId, + UUID requestId, + IntakeReceipt sourceReceipt, + UUID realmId, + UUID namespaceId, + long revision, + String requestDigest) { + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + targetNamespace, + canonicalTenantId.toString(), + requestId.toString(), + requestDigest, + realmId.toString(), + namespaceId.toString(), + Long.toString(revision), + sourceReceipt.operationId().toString(), + sourceReceipt.receiptDigest()); + } + + private static String digest(String... values) { + try { + MessageDigest hash = MessageDigest.getInstance("SHA-256"); + for (String value : values) { + byte[] bytes = strictUtf8(value); + 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 byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8 text", exception); + } + } + + private void requireWritableOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires an active owner transaction"); + } + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical realm catalog DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + return null; + }); + Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); + if (isolationRow == null + || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + Record readOnlyRow = dsl.fetchOne("SHOW transaction_read_only"); + if (readOnlyRow == null || !"off".equalsIgnoreCase(readOnlyRow.get(0, String.class).trim())) { + throw new IllegalStateException( + "Canonical realm catalog creation requires a read-write transaction"); + } + } + + private void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Canonical realm catalog read requires a committed-outcome owner read"); + } + } + + private static void requireReadSelector(String targetNamespace, UUID identity) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(identity, "identity"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static T required(Record record, Field field, String label) { + T value = record.get(field); + if (value == null) { + throw new InvalidCatalogEvidenceException("Persisted " + label + " is missing"); + } + return value; + } + + /** Opaque source preflight result; callers cannot manufacture a committed owner receipt. */ + public static final class PreparedInitialPublicProduction { + private final CreateCanonicalRealmCatalogRequest request; + private final IntakeReceipt committedSource; + + private PreparedInitialPublicProduction( + CreateCanonicalRealmCatalogRequest request, IntakeReceipt committedSource) { + this.request = Objects.requireNonNull(request, "request"); + this.committedSource = Objects.requireNonNull(committedSource, "committedSource"); + } + + private CreateCanonicalRealmCatalogRequest request() { + return request; + } + + private IntakeReceipt committedSource() { + return committedSource; + } + } + + public static final class CatalogConflictException extends IllegalStateException { + public CatalogConflictException(String message) { + super(message); + } + } + + public static final class InvalidCatalogEvidenceException extends IllegalStateException { + public InvalidCatalogEvidenceException(String message) { + super(message); + } + + public InvalidCatalogEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 7210542b41..d536834367 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -5,11 +5,17 @@ import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointerEvent.GAMEPLAY_ADMISSION_POINTER_EVENT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerEventRecord; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; @@ -18,6 +24,9 @@ import org.jooq.Record; import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( @@ -161,6 +170,135 @@ public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) return findById(entity.getId()); } + /** Appends the exact canonical first-OPEN event inside the pointer/attempt owner transaction. */ + public long appendCanonicalInitialAdmissionOpen( + CanonicalInitialAdmissionRequest request, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget, + long pointerVersion, + long auditCatalogRevision, + Instant occurredAt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(launchTarget, "launchTarget"); + Objects.requireNonNull(occurredAt, "occurredAt"); + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Canonical initial admission audit requires the writable owner transaction"); + } + var association = launchTarget.association(); + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer_event (" + + "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, " + + "control_plane_request_id, occurred_at, prepared_version_upgrade_id, " + + "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', ?, ?, NULL, ?, ?, ?, ?, 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(), + request.initialAdmissionRequestId(), + toLocalDateTime(occurredAt), + catalog.publicProduction(), + auditCatalogRevision, + 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 IllegalStateException("Canonical initial admission audit insert returned no event"); + } + return inserted.get("id", Long.class); + } + + /** Appends the single canonical CLOSED audit event inside its pointer owner transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public long appendCanonicalClosed( + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + String worldSlug, + String realmSlug, + long catalogRevision, + String actorPrincipal, + String reason, + UUID requestId, + Instant occurredAt) { + Objects.requireNonNull(targetNamespace, "targetNamespace"); + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(actorPrincipal, "actorPrincipal"); + Objects.requireNonNull(reason, "reason"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(occurredAt, "occurredAt"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + Record inserted = + dsl.fetchOne( + "INSERT INTO gameplay_admission_pointer_event (" + + "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, " + + "control_plane_request_id, occurred_at, prepared_version_upgrade_id, " + + "public_production_realm, representation_version, target_namespace, " + + "canonical_tenant_id, realm_id, catalog_revision, admission_state) " + + "VALUES (?, ?, NULL, NULL, NULL, NULL, 1, NULL, NULL, NULL, NULL, ?, ?, ?, ?, " + + "NULL, NULL, 2, ?, ?, ?, ?, 'CLOSED') RETURNING id", + worldSlug, + realmSlug, + actorPrincipal, + reason, + requestId.toString(), + toLocalDateTime(occurredAt), + targetNamespace, + canonicalTenantId, + realmId, + catalogRevision); + if (inserted == null) { + throw new IllegalStateException( + "Canonical CLOSED admission-pointer audit insert returned no id"); + } + Long eventId = inserted.get("id", Long.class); + if (eventId == null || eventId <= 0L) { + throw new IllegalStateException("Canonical CLOSED admission-pointer event id is invalid"); + } + return eventId; + } + public void deleteAllInBatch() { dsl.deleteFrom(GAMEPLAY_ADMISSION_POINTER_EVENT).execute(); } 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 new file mode 100644 index 0000000000..398ca8e8a4 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/security/ProtectedGameSessionLoginGrpcInterceptor.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.gamesession.security; + +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Set; + +/** Allows only health and exact owner-read methods in the protected LOGIN composition. */ +public final class ProtectedGameSessionLoginGrpcInterceptor implements ServerInterceptor { + // Do not derive this from AuthTokenInterceptor's public-method configuration: each owner-read + // entry below is also guarded by its existing exact workload/method handler check. + private static final Set ALLOWED_METHODS = + Set.of( + "game_session.v1.GameSessionService/Ping", + "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", + "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", + "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof", + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead"); + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (ALLOWED_METHODS.contains(call.getMethodDescriptor().getFullMethodName())) { + return next.startCall(call, headers); + } + call.close( + Status.PERMISSION_DENIED.withDescription( + "Game Session LOGIN-only composition denies this gRPC method"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java new file mode 100644 index 0000000000..f80c5e7ad6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadRequest.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; + +/** Exact independent World read selector for one committed Game Session launch association. */ +public record CanonicalGameInstanceLaunchAssociationReadRequest( + UUID readRequestId, + String targetNamespace, + UUID canonicalTenantId, + String worldSlug, + UUID gameInstanceUuid, + String controlPlaneRequestId, + String launchDescriptorId, + String expectedDescriptorRequestDigest, + String expectedDescriptorResultDigest, + String expectedReleaseAttestationEvidenceDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalGameInstanceLaunchAssociationReadRequest { + requireNonNil(readRequestId, "readRequestId"); + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(gameInstanceUuid, "gameInstanceUuid"); + AuthoredWorldSourceDigest.validateReadSelector(targetNamespace, canonicalTenantId, worldSlug); + requireText(controlPlaneRequestId, "controlPlaneRequestId"); + requireText(launchDescriptorId, "launchDescriptorId"); + requireDigest(expectedDescriptorRequestDigest, "expectedDescriptorRequestDigest"); + requireDigest(expectedDescriptorResultDigest, "expectedDescriptorResultDigest"); + requireDigest( + expectedReleaseAttestationEvidenceDigest, "expectedReleaseAttestationEvidenceDigest"); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireText(String value, String name) { + Objects.requireNonNull(value, name); + if (value.isBlank() || value.length() > 256) { + throw new IllegalArgumentException(name + " must be non-blank and bounded"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java new file mode 100644 index 0000000000..36847fbe6d --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameInstanceLaunchAssociationReadService.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; + +/** Reads and qualifies exact durable Game Session owner evidence without changing it. */ +public final class CanonicalGameInstanceLaunchAssociationReadService { + private final CanonicalGameInstanceLaunchAssociationRepository repository; + private final String configuredNamespace; + + public CanonicalGameInstanceLaunchAssociationReadService( + CanonicalGameInstanceLaunchAssociationRepository repository, String configuredNamespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.configuredNamespace = Objects.requireNonNull(configuredNamespace, "configuredNamespace"); + } + + public CanonicalGameInstanceLaunchAssociation read( + CanonicalGameInstanceLaunchAssociationReadRequest request) { + Objects.requireNonNull(request, "request"); + if (!configuredNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException("Read namespace does not match this Game Session owner"); + } + CanonicalGameInstanceLaunchAssociation association = + repository + .read(request.controlPlaneRequestId()) + .orElseThrow( + () -> new IllegalStateException("Canonical launch association is unavailable")); + CompleteLaunchBindingEvidence binding = association.launchBindingEvidence(); + var descriptor = binding.descriptor(); + var attestation = binding.releaseAttestation(); + descriptor.requireValid(); + attestation.requireValid(descriptor); + if (request.readRequestId().equals(descriptor.authoredWorldSourceOperationId()) + || request.readRequestId().toString().equals(descriptor.controlPlaneRequestId()) + || !configuredNamespace.equals(association.targetNamespace()) + || !request.targetNamespace().equals(association.targetNamespace()) + || !request.canonicalTenantId().equals(association.canonicalTenantId()) + || !request.worldSlug().equals(association.worldSlug()) + || !request.gameInstanceUuid().equals(association.gameInstanceUuid()) + || !request.controlPlaneRequestId().equals(association.controlPlaneRequestId()) + || !request.launchDescriptorId().equals(association.launchDescriptorId()) + || !request.expectedDescriptorRequestDigest().equals(descriptor.requestDigest()) + || !request.expectedDescriptorResultDigest().equals(descriptor.resultDigest()) + || !request + .expectedReleaseAttestationEvidenceDigest() + .equals(attestation.evidenceDigest())) { + throw new IllegalStateException( + "Canonical launch association does not match the exact read selector"); + } + return association; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java new file mode 100644 index 0000000000..9bd141e8bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionService.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; + +/** Game Session-owned canonical initial OPEN operation and exact owner readback. */ +public interface CanonicalInitialAdmissionService { + CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request); + + CanonicalInitialAdmissionOwnerProof abort( + CanonicalInitialAdmissionRequest request, String reason); + + CanonicalInitialAdmissionOwnerProof read(String targetNamespace, String requestId); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java new file mode 100644 index 0000000000..448d9e7f74 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalInitialAdmissionWorldVerifier.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; + +/** + * Remote World owner boundary. Implementations must verify the current ACTIVE lifecycle evidence + * and exact immutable {@code WorldCanonicalInitialAdmissionHold.HoldIdentity} outside SQL, then + * return its complete request/hold tuple and World binding digest. A supplied local request or + * caller authentication context is never owner proof. + */ +public interface CanonicalInitialAdmissionWorldVerifier { + CanonicalInitialAdmissionWorldProof verify(CanonicalInitialAdmissionRequest request); +} 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 new file mode 100644 index 0000000000..5e47274f8c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java @@ -0,0 +1,272 @@ +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; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.jooq.exception.DataAccessException; + +/** + * Read-only composition of current Game Session catalog, OPEN proof, and owner-qualified runtime. + */ +public final class CanonicalPlayerRouteReadService { + private final String targetNamespace; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + 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, + CanonicalInitialAdmissionRepository admissionRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository) { + this.targetNamespace = targetNamespace; + this.catalogRepository = catalogRepository; + this.admissionRepository = admissionRepository; + this.launchRepository = launchRepository; + } + + /** + * A default-off identity configuration produces unavailable authority without a startup error. + */ + public static CanonicalPlayerRouteReadService unavailable() { + return new CanonicalPlayerRouteReadService(null, null, null, null); + } + + /** Lists only current visible public-production routes from canonical owner evidence. */ + public List readVisiblePublicProductionTargets() { + requireConfigured(); + List catalogs; + try { + catalogs = catalogRepository.readVisiblePublicProductionSnapshots(targetNamespace); + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical realm catalog read is unavailable", ex); + } catch (RuntimeException ex) { + throw new InvalidAuthorityException("Canonical realm catalog is invalid", ex); + } + if (catalogs == null) { + throw new ReadUnavailableException("Canonical realm catalog read returned no result"); + } + + Set tenantIds = new HashSet<>(); + ArrayList targets = new ArrayList<>(catalogs.size()); + for (CanonicalRealmCatalogSnapshot catalog : catalogs) { + if (catalog == null || !tenantIds.add(catalog.tenantId())) { + throw new InvalidAuthorityException( + "Canonical public-production catalog has duplicate tenant authority"); + } + targets.add(readTargetForCatalog(catalog)); + } + return List.copyOf(targets); + } + + /** Rereads the selected tenant's unique catalog, current OPEN pointer proof, and launch row. */ + public CanonicalPlayableTarget readCurrentTarget(CanonicalPlayableTarget expected) { + Objects.requireNonNull(expected, "expected"); + requireConfigured(); + if (!targetNamespace.equals(expected.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + return readCurrentTarget(expected.canonicalTenantId()); + } + + /** + * Reads one current target by its canonical tenant selector, without trusting caller counters. + */ + public CanonicalPlayableTarget readCurrentTarget(UUID canonicalTenantId) { + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + if (new UUID(0L, 0L).equals(canonicalTenantId)) { + throw new InvalidAuthorityException("Canonical tenant selector must be non-nil"); + } + requireConfigured(); + CanonicalRealmCatalogSnapshot catalog; + try { + catalog = + catalogRepository + .readUniqueVisiblePublicProduction(targetNamespace, canonicalTenantId) + .orElseThrow( + () -> + new InvalidAuthorityException( + "Canonical public-production realm catalog is missing")); + } catch (ReadUnavailableException | InvalidAuthorityException ex) { + throw ex; + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical realm catalog read is unavailable", ex); + } catch (RuntimeException ex) { + throw new InvalidAuthorityException("Canonical realm catalog is invalid", ex); + } + return readTargetForCatalog(catalog); + } + + /** + * Returns false for reachable stale or malformed authority; transport/storage failure escapes. + */ + public boolean matchesCurrentTarget(CanonicalPlayableTarget expected) { + try { + return expected.equals(readCurrentTarget(expected)); + } catch (ReadUnavailableException ex) { + throw ex; + } catch (InvalidAuthorityException ex) { + return false; + } + } + + private CanonicalPlayableTarget readTargetForCatalog(CanonicalRealmCatalogSnapshot catalog) { + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot openSnapshot; + try { + openSnapshot = + admissionRepository.readCurrentOpenSnapshotForRealm( + targetNamespace, catalog.tenantId(), catalog.realmId()); + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical admission owner read is unavailable", ex); + } catch (RuntimeException ex) { + throw new InvalidAuthorityException( + "Canonical OPEN pointer or terminal owner proof is invalid", ex); + } + CanonicalInitialAdmissionOwnerProof proof = openSnapshot.ownerProof(); + requireCatalogMatchesProof(catalog, proof); + + CanonicalInitialAdmissionLaunchTarget launch; + try { + launch = + launchRepository + .readForInitialAdmission( + targetNamespace, + catalog.tenantId(), + catalog.realmId(), + proof.canonicalGameInstanceId()) + .orElseThrow( + () -> + new InvalidAuthorityException( + "Canonical OPEN target has no owner-qualified launch association")); + } catch (DataAccessException ex) { + throw new ReadUnavailableException("Canonical launch association read is unavailable", ex); + } catch (InvalidAuthorityException | ReadUnavailableException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new InvalidAuthorityException("Canonical launch association is invalid", ex); + } + requireLaunchMatchesCatalogAndProof(catalog, proof, launch); + + return new CanonicalPlayableTarget( + targetNamespace, + catalog.tenantSlug(), + catalog.tenantId(), + catalog.worldSlug(), + catalog.sourceIntakeReceipt().source().worldDisplayName(), + catalog.realmId(), + catalog.realmSlug(), + catalog.realmDisplayName(), + launch.association().gameSessionTenantId(), + launch.gameInstanceId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + proof.canonicalGameInstanceId(), + proof.canonicalVersionId(), + launch.runtimeVersionId(), + catalog.catalogRevision(), + proof.committedPointerVersion(), + openSnapshot.admissionPointerSnapshotDigest(), + proof.activeLifecycleEpoch(), + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.originKind(), + proof.expectedPriorPointerVersion(), + proof.holdId(), + proof.holdFence(), + proof.holdBindingDigest(), + proof.auditEventId(), + proof.proofDigest(), + proof.outcome(), + proof.positiveDurableAbort(), + proof.terminalAt(), + catalog.characterCreationPolicy()); + } + + private void requireCatalogMatchesProof( + CanonicalRealmCatalogSnapshot catalog, CanonicalInitialAdmissionOwnerProof proof) { + if (proof == null + || !proof.provesCommit() + || !targetNamespace.equals(proof.targetNamespace()) + || !targetNamespace.equals(catalog.targetNamespace()) + || !catalog.tenantId().equals(proof.canonicalTenantId()) + || !catalog.worldSlug().equals(proof.worldSlug()) + || !catalog.realmId().equals(proof.realmId()) + || !catalog.playableStateNamespaceId().equals(proof.playableStateNamespaceId()) + || !catalog.stateScope().equals(proof.playableStateScope()) + || catalog.catalogRevision() != proof.expectedCatalogRevision() + || proof.committedPointerVersion() == null + || proof.auditEventId() == null + || proof.proofDigest() == null + || proof.terminalAt() == null) { + throw new InvalidAuthorityException( + "Canonical catalog does not match the committed current OPEN proof"); + } + } + + private void requireLaunchMatchesCatalogAndProof( + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionOwnerProof proof, + CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + if (association.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !association.targetNamespace().equals(targetNamespace) + || !association.canonicalTenantId().equals(catalog.tenantId()) + || !association.worldSlug().equals(catalog.worldSlug()) + || !association.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !association.playableStateScope().name().equals(catalog.stateScope()) + || !association.publicProduction() + || !association.gameInstanceUuid().equals(proof.canonicalGameInstanceId()) + || !launch.realmId().equals(catalog.realmId()) + || !launch.canonicalVersionId().equals(proof.canonicalVersionId())) { + throw new InvalidAuthorityException( + "Canonical launch association does not match the current catalog and OPEN proof"); + } + } + + private void requireConfigured() { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || catalogRepository == null + || admissionRepository == null + || launchRepository == null) { + throw new ReadUnavailableException("Canonical player route authority is not configured"); + } + } + + public static final class ReadUnavailableException extends RuntimeException { + public ReadUnavailableException(String message) { + super(message); + } + + public ReadUnavailableException(String message, RuntimeException cause) { + super(message, cause); + } + } + + public static final class InvalidAuthorityException extends RuntimeException { + public InvalidAuthorityException(String message) { + super(message); + } + + public InvalidAuthorityException(String message, RuntimeException cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java new file mode 100644 index 0000000000..c1d266e897 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java @@ -0,0 +1,519 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +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.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.jooq.exception.DataAccessException; + +/** + * Read-only composition of current Game Session routing and a fresh complete Game Design policy + * set. A result is source evidence only and does not enable PLAY or actor admission. + */ +public final class CanonicalPublishedPlayerRouteReadService { + private final String targetNamespace; + private final CanonicalPlayerRouteReadService routeReader; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + private final GameDesignPublishedRealmPolicyClient policyClient; + + public CanonicalPublishedPlayerRouteReadService( + String targetNamespace, + CanonicalPlayerRouteReadService routeReader, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameDesignPublishedRealmPolicyClient policyClient) { + this.targetNamespace = targetNamespace; + this.routeReader = routeReader; + this.catalogRepository = catalogRepository; + this.launchRepository = launchRepository; + this.policyClient = policyClient; + } + + /** Default-off source client: absent composition produces unavailable, never an open route. */ + public static CanonicalPublishedPlayerRouteReadService unavailable() { + return new CanonicalPublishedPlayerRouteReadService(null, null, null, null, null); + } + + /** + * Reads fresh owner policy for an exact current route, checks the original source and launch + * bindings, then rereads the full current route before returning the sealed evidence. + */ + public CanonicalPublishedPlayerRoute readCurrent(CanonicalPlayableTarget expected) { + Objects.requireNonNull(expected, "expected"); + return readCurrent(expected, null); + } + + /** + * Reads an exact caller-selected tenant target and returns complete source evidence for Entity. + * The Account UUID is echoed only; this method does not establish Account membership or PLAY + * authority. + */ + public CanonicalGameplayRosterOwnerReadEvidence readCurrent( + CanonicalGameplayRosterOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + CanonicalPublishedPlayerRoute route = readCurrent(null, request); + return new CanonicalGameplayRosterOwnerReadEvidence( + request, + route.route().admissionPointerSnapshotDigest(), + ownerProof(route.route()), + route.policySetEvidence()); + } + + /** + * Reads assignment source evidence from exact immutable selectors while deriving current pointer + * and lifecycle counters from Game Session-owned route evidence. This is a staging-only source + * read; the Account selectors are correlation data and do not establish membership or admission. + */ + public PreseededActorAssignmentOwnerReadEvidence readCurrentForAssignment( + PreseededActorAssignmentOwnerReadEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireConfigured(); + if (!targetNamespace.equals(request.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + + CanonicalPlayableTarget current = readRoute(request.canonicalTenantUuid()); + requireAssignmentSelectors(request, current); + var sourceRequest = + PreseededActorAssignmentOwnerReadEvidence.sourceRequest(request, ownerProof(current)); + CanonicalGameplayRosterOwnerReadEvidence sourceEvidence = readCurrent(sourceRequest); + return new PreseededActorAssignmentOwnerReadEvidence(request, sourceEvidence); + } + + private CanonicalPublishedPlayerRoute readCurrent( + CanonicalPlayableTarget expected, CanonicalGameplayRosterOwnerReadEvidence.Request request) { + if ((expected == null) == (request == null)) { + throw new IllegalArgumentException("Exactly one canonical route selector is required"); + } + requireConfigured(); + if (expected != null && !targetNamespace.equals(expected.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + if (request != null && !targetNamespace.equals(request.targetNamespace())) { + throw new InvalidAuthorityException("Selected route belongs to another owner namespace"); + } + + CanonicalPlayableTarget before = + expected == null ? readRoute(request.canonicalTenantUuid()) : readRoute(expected); + if (expected != null) { + requireExpectedRoute(expected, before); + } else { + requireExpectedRequest(request, before); + } + CanonicalRealmCatalogSnapshot catalogBefore = readCatalog(before); + CanonicalInitialAdmissionLaunchTarget launchBefore = readLaunch(before); + requireCurrentRouteBinding(before, catalogBefore, launchBefore); + + PublishedRealmEntryPolicySetEvidence policySet = + readPolicy(before.canonicalTenantId(), before.canonicalVersionId()); + PublishedRealmEntryPolicySetEvidence complete = verifySet(policySet); + PublishedRealmEntryPolicyEvidence selected = + requirePublishedPreseededPolicy(complete, before, catalogBefore, launchBefore); + + CanonicalPlayableTarget after = + expected == null ? readRoute(request.canonicalTenantUuid()) : readRoute(before); + if (!before.equals(after)) { + throw new StaleAuthorityException("Canonical player route changed during policy read"); + } + if (request != null) { + requireExpectedRequest(request, after); + } + CanonicalRealmCatalogSnapshot catalogAfter = readCatalog(after); + CanonicalInitialAdmissionLaunchTarget launchAfter = readLaunch(after); + if (!catalogBefore.equals(catalogAfter) + || !sameCurrentLaunchBinding(launchBefore, launchAfter)) { + throw new StaleAuthorityException( + "Canonical source or complete launch binding changed during policy read"); + } + requireCurrentRouteBinding(after, catalogAfter, launchAfter); + + PublishedRealmEntryPolicySetEvidence confirmedPolicySet = + verifySet(readPolicy(after.canonicalTenantId(), after.canonicalVersionId())); + if (!complete.equals(confirmedPolicySet)) { + throw new StaleAuthorityException( + "Game Design policy source or capture changed during owner read"); + } + + return new CanonicalPublishedPlayerRoute(after, complete, selected); + } + + private GameSessionCanonicalInitialAdmissionOwnerProof ownerProof(CanonicalPlayableTarget route) { + if (route.ownerProofOutcome() != CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + throw new InvalidAuthorityException("Current route lacks terminal COMMITTED owner proof"); + } + WorldCanonicalInitialAdmissionHold.Request request = + new WorldCanonicalInitialAdmissionHold.Request( + route.targetNamespace(), + route.canonicalTenantId(), + route.worldSlug(), + route.realmId(), + route.playableStateNamespaceId(), + route.playableStateScope(), + route.canonicalGameInstanceId(), + route.canonicalVersionId(), + route.activeWorldEpoch(), + route.initialAdmissionRequestId(), + route.initialAdmissionRequestDigest(), + route.initialAdmissionOriginKind() + == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER + ? WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER + : WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.EXPECT_CLOSED, + route.catalogRevision(), + route.expectedPriorPointerVersion()); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, route.holdId(), route.holdFence()); + if (!hold.holdBindingDigest().equals(route.holdBindingDigest())) { + throw new InvalidAuthorityException( + "Current route hold digest differs from the complete World-held request"); + } + GameSessionCanonicalInitialAdmissionOwnerProof proof = + new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + route.pointerVersion(), + route.auditEventId(), + route.ownerProofDigest(), + false, + route.ownerProofTerminalAt()); + return GameSessionCanonicalInitialAdmissionOwnerProofCodec.fromStored( + GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof)); + } + + private static void requireExpectedRequest( + CanonicalGameplayRosterOwnerReadEvidence.Request expected, CanonicalPlayableTarget current) { + if (current == null + || !expected.targetNamespace().equals(current.targetNamespace()) + || !expected.canonicalTenantUuid().equals(current.canonicalTenantId()) + || !expected.worldSlug().equals(current.worldSlug()) + || !expected.realmUuid().equals(current.realmId()) + || !expected.realmSlug().equals(current.realmSlug()) + || !expected.playableStateNamespaceUuid().equals(current.playableStateNamespaceId()) + || !expected.playableStateScope().equals(current.playableStateScope()) + || !expected.canonicalGameInstanceUuid().equals(current.canonicalGameInstanceId()) + || !expected.canonicalVersionUuid().equals(current.canonicalVersionId()) + || expected.expectedCatalogRevision() != current.catalogRevision() + || expected.expectedPointerVersion() != current.pointerVersion() + || expected.expectedActiveWorldEpoch() != current.activeWorldEpoch()) { + throw new StaleAuthorityException( + "Canonical current route differs from the exact requested selectors and counters"); + } + } + + private static void requireAssignmentSelectors( + PreseededActorAssignmentOwnerReadEvidence.Request expected, CanonicalPlayableTarget current) { + if (current == null + || !expected.targetNamespace().equals(current.targetNamespace()) + || !expected.canonicalTenantUuid().equals(current.canonicalTenantId()) + || !expected.worldSlug().equals(current.worldSlug()) + || !expected.realmUuid().equals(current.realmId()) + || !expected.realmSlug().equals(current.realmSlug()) + || !expected.playableStateNamespaceUuid().equals(current.playableStateNamespaceId()) + || !expected.playableStateScope().equals(current.playableStateScope()) + || !expected.canonicalGameInstanceUuid().equals(current.canonicalGameInstanceId()) + || !expected.canonicalVersionUuid().equals(current.canonicalVersionId()) + || expected.expectedCatalogRevision() != current.catalogRevision()) { + throw new StaleAuthorityException( + "Canonical current route differs from the exact actor-assignment selectors"); + } + } + + private CanonicalPlayableTarget readRoute(CanonicalPlayableTarget expected) { + try { + return routeReader.readCurrentTarget(expected); + } catch (CanonicalPlayerRouteReadService.ReadUnavailableException unavailable) { + throw new StorageUnavailableException("Canonical route storage is unavailable", unavailable); + } catch (CanonicalPlayerRouteReadService.InvalidAuthorityException invalid) { + throw new InvalidAuthorityException("Canonical route authority is invalid", invalid); + } + } + + private CanonicalPlayableTarget readRoute(UUID canonicalTenantId) { + try { + return routeReader.readCurrentTarget(canonicalTenantId); + } catch (CanonicalPlayerRouteReadService.ReadUnavailableException unavailable) { + throw new StorageUnavailableException("Canonical route storage is unavailable", unavailable); + } catch (CanonicalPlayerRouteReadService.InvalidAuthorityException invalid) { + throw new InvalidAuthorityException("Canonical route authority is invalid", invalid); + } + } + + private CanonicalRealmCatalogSnapshot readCatalog(CanonicalPlayableTarget route) { + try { + return catalogRepository + .readUniqueVisiblePublicProduction(targetNamespace, route.canonicalTenantId()) + .orElseThrow( + () -> new StaleAuthorityException("Canonical public-production catalog is missing")); + } catch (DataAccessException unavailable) { + throw new StorageUnavailableException( + "Canonical catalog storage is unavailable", unavailable); + } catch (StaleAuthorityException stale) { + throw stale; + } catch (RuntimeException invalid) { + throw new InvalidAuthorityException("Canonical catalog source evidence is invalid", invalid); + } + } + + private CanonicalInitialAdmissionLaunchTarget readLaunch(CanonicalPlayableTarget route) { + try { + return launchRepository + .readForInitialAdmission( + targetNamespace, + route.canonicalTenantId(), + route.realmId(), + route.canonicalGameInstanceId()) + .orElseThrow( + () -> new StaleAuthorityException("Current canonical launch binding is missing")); + } catch (DataAccessException unavailable) { + throw new StorageUnavailableException("Canonical launch storage is unavailable", unavailable); + } catch (StaleAuthorityException stale) { + throw stale; + } catch (RuntimeException invalid) { + throw new InvalidAuthorityException("Canonical launch binding is invalid", invalid); + } + } + + private PublishedRealmEntryPolicySetEvidence readPolicy( + UUID canonicalTenantId, UUID canonicalVersionId) { + try { + return policyClient.listPublishedRealmEntryPolicies(canonicalTenantId, canonicalVersionId); + } catch (StatusRuntimeException | IllegalStateException unavailable) { + throw new GameDesignUnavailableException( + "Game Design policy transport is unavailable", unavailable); + } catch (IllegalArgumentException rejected) { + throw new InvalidAuthorityException("Game Design policy owner read was rejected", rejected); + } + } + + private PublishedRealmEntryPolicySetEvidence verifySet( + PublishedRealmEntryPolicySetEvidence policySet) { + if (policySet == null) { + throw new InvalidAuthorityException("Game Design returned no published policy set"); + } + try { + return PublishedRealmEntryPolicySetEvidence.fromStored(policySet.canonicalBytes()); + } catch (RuntimeException invalid) { + throw new InvalidAuthorityException( + "Game Design policy set is not complete closed evidence", invalid); + } + } + + private PublishedRealmEntryPolicyEvidence requirePublishedPreseededPolicy( + PublishedRealmEntryPolicySetEvidence complete, + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch) { + var source = catalog.sourceIntakeReceipt().source(); + var targetProof = complete.target(); + var operation = GameDesignPublicationOperationBinding.fromStored(complete.operationBytes()); + var terminal = + GameDesignPublicationTerminalEvidence.fromStored(complete.terminalEvidenceBytes()); + var association = launch.association(); + var descriptor = association.launchBindingEvidence().descriptor(); + var release = association.launchBindingEvidence().releaseAttestation(); + if (!operation.account().input().selection().target().equals(targetProof) + || !targetNamespace.equals(operation.world().request().targetNamespace()) + || !targetNamespace.equals(terminal.worldEvidence().request().targetNamespace()) + || !route.canonicalTenantId().equals(operation.world().request().canonicalTenantId()) + || !route.canonicalVersionId().equals(operation.world().request().canonicalVersionId()) + || !complete.target().canonicalTenantId().equals(route.canonicalTenantId()) + || !complete.target().canonicalVersionId().equals(route.canonicalVersionId()) + || !targetNamespace.equals(source.targetNamespace()) + || !route.canonicalTenantId().equals(source.canonicalTenantId()) + || targetProof.sourceGameRowId() != source.sourceGameRowId() + || !targetProof.sourceGameTenantKey().equals(source.sourceGameTenantKey()) + || !targetProof.gameDesignVersionTenantKey().equals(source.sourceGameTenantKey()) + || !targetProof.sourceProvenanceKind().equals(source.provenanceKind()) + || !release.authoredWorldSourceOperationId().equals(source.operationId()) + || !release.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest()) + || !release.commitId().equals(complete.sourceCommitId().toString()) + || !release.publishedReleaseBundleRef().equals(complete.publishedReleaseBundleRef()) + || !release.publishWorkflowId().equals(complete.publishWorkflowId()) + || !release.manifestHash().equals(complete.manifestHash()) + || release.versionStateEpoch() != complete.publicationVersionStateEpoch() + || !terminal.publishedReleaseBundleRef().equals(complete.publishedReleaseBundleRef()) + || !terminal.publishedReleaseBundleDigest().equals(complete.publishedReleaseBundleDigest()) + || !terminal.releaseContent().publishWorkflowId().equals(complete.publishWorkflowId()) + || !terminal.releaseContent().manifestHash().equals(complete.manifestHash()) + || terminal.publicationVersionStateEpoch() != complete.publicationVersionStateEpoch() + || !descriptor.publishedReleaseBundleRef().equals(complete.publishedReleaseBundleRef()) + || descriptor.versionStateEpoch() != complete.publicationVersionStateEpoch()) { + throw new InvalidAuthorityException( + "Published policy source or release does not match the current complete launch binding"); + } + + var matches = + complete.policies().stream() + .filter( + evidence -> + evidence.policy().worldSlug().equals(route.worldSlug()) + && evidence.policy().realmSlug().equals(route.realmSlug())) + .toList(); + if (matches.size() != 1) { + throw new InvalidAuthorityException("Published policy set lacks the exact current selector"); + } + PublishedRealmEntryPolicyEvidence selected = matches.getFirst(); + RealmEntryPolicy policy = selected.policy(); + if (!policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY + || !catalog.visible() + || !catalog.publicProduction() + || !"SHARED".equals(catalog.stateScope())) { + throw new InvalidAuthorityException( + "Published policy and current public-production route do not match PRESEEDED_ONLY"); + } + return selected; + } + + private void requireCurrentRouteBinding( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + var source = catalog.sourceIntakeReceipt().source(); + var descriptor = association.launchBindingEvidence().descriptor(); + var release = association.launchBindingEvidence().releaseAttestation(); + if (!targetNamespace.equals(route.targetNamespace()) + || !targetNamespace.equals(catalog.targetNamespace()) + || !route.canonicalTenantId().equals(catalog.tenantId()) + || !route.worldSlug().equals(catalog.worldSlug()) + || !route.realmId().equals(catalog.realmId()) + || !route.realmSlug().equals(catalog.realmSlug()) + || !route.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !route.playableStateScope().equals(catalog.stateScope()) + || !catalog.visible() + || !catalog.publicProduction() + || !"SHARED".equals(catalog.stateScope()) + || !route.canonicalTenantId().equals(association.canonicalTenantId()) + || !route.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !route.worldSlug().equals(association.worldSlug()) + || !route.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || association.playableStateScope() != RealmEntryPolicy.StateScope.SHARED + || !association.publicProduction() + || association.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !route.realmId().equals(launch.realmId()) + || route.gameInstanceId() != launch.gameInstanceId() + || route.runtimeVersionId() != launch.runtimeVersionId() + || !route.canonicalVersionId().equals(launch.canonicalVersionId()) + || !targetNamespace.equals(descriptor.targetNamespace()) + || !route.canonicalTenantId().equals(descriptor.canonicalTenantId()) + || !route.worldSlug().equals(descriptor.worldSlug()) + || !route.canonicalTenantId().equals(release.canonicalTenantId()) + || !route.canonicalVersionId().equals(release.canonicalVersionId()) + || !route.worldSlug().equals(release.worldSlug()) + || !targetNamespace.equals(release.targetNamespace()) + || !source.operationId().equals(descriptor.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(descriptor.authoredWorldSourceEvidenceDigest()) + || !source.operationId().equals(release.authoredWorldSourceOperationId()) + || !source.evidenceDigest().equals(release.authoredWorldSourceEvidenceDigest()) + || descriptor.versionId() != route.runtimeVersionId() + || descriptor.versionStateEpoch() != release.versionStateEpoch() + || !descriptor.publishedReleaseBundleRef().equals(release.publishedReleaseBundleRef()) + || !association.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId()) + || !association.launchDescriptorId().equals(descriptor.launchDescriptorId())) { + throw new InvalidAuthorityException( + "Canonical catalog, route, and complete launch binding disagree"); + } + } + + private static void requireExpectedRoute( + CanonicalPlayableTarget expected, CanonicalPlayableTarget current) { + if (current == null || !expected.equals(current)) { + throw new StaleAuthorityException( + "Selected canonical player route changed before policy read"); + } + } + + private static boolean sameCurrentLaunchBinding( + CanonicalInitialAdmissionLaunchTarget left, CanonicalInitialAdmissionLaunchTarget right) { + if (right == null + || !left.realmId().equals(right.realmId()) + || left.gameInstanceId() != right.gameInstanceId() + || left.runtimeVersionId() != right.runtimeVersionId()) { + return false; + } + CanonicalGameInstanceLaunchAssociation first = left.association(); + CanonicalGameInstanceLaunchAssociation second = right.association(); + return first.targetNamespace().equals(second.targetNamespace()) + && first.gameSessionTenantId() == second.gameSessionTenantId() + && first.tenantAssociationOperationId().equals(second.tenantAssociationOperationId()) + && first.canonicalTenantId().equals(second.canonicalTenantId()) + && first.gameInstanceUuid().equals(second.gameInstanceUuid()) + && first.worldSlug().equals(second.worldSlug()) + && first.playableStateNamespaceId().equals(second.playableStateNamespaceId()) + && first.playableStateScope() == second.playableStateScope() + && first.publicProduction() == second.publicProduction() + && first.controlPlaneRequestId().equals(second.controlPlaneRequestId()) + && first.launchDescriptorId().equals(second.launchDescriptorId()) + && first.capturedStartingRowVersion() == second.capturedStartingRowVersion() + && first.currentRowVersion() == second.currentRowVersion() + && first.launchBindingEvidence().equals(second.launchBindingEvidence()) + && first.currentGameInstanceStatus() == second.currentGameInstanceStatus(); + } + + private void requireConfigured() { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || routeReader == null + || catalogRepository == null + || launchRepository == null + || policyClient == null) { + throw new StorageUnavailableException("Canonical published player-route reader is disabled"); + } + } + + public static class InvalidAuthorityException extends RuntimeException { + public InvalidAuthorityException(String message) { + super(message); + } + + public InvalidAuthorityException(String message, Throwable cause) { + super(message, cause); + } + } + + public static final class StaleAuthorityException extends InvalidAuthorityException { + public StaleAuthorityException(String message) { + super(message); + } + } + + public static final class StorageUnavailableException extends RuntimeException { + public StorageUnavailableException(String message, Throwable cause) { + super(message, cause); + } + + public StorageUnavailableException(String message) { + super(message); + } + } + + public static final class GameDesignUnavailableException extends RuntimeException { + public GameDesignUnavailableException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java new file mode 100644 index 0000000000..bf3aa9a4bb --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FreshGameSessionTenantAssociation.java @@ -0,0 +1,26 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence; + +/** Immutable Game Session-local mapping to exact authenticated fresh Game Design identity. */ +public record FreshGameSessionTenantAssociation( + UUID associationOperationId, + long legacyGameSessionTenantId, + RuntimeTenantIdentityEvidence sourceEvidence) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public FreshGameSessionTenantAssociation { + if (associationOperationId == null || NIL_UUID.equals(associationOperationId)) { + throw new IllegalArgumentException("associationOperationId must be a non-nil UUID"); + } + if (legacyGameSessionTenantId <= 0) { + throw new IllegalArgumentException("legacyGameSessionTenantId must be positive"); + } + Objects.requireNonNull(sourceEvidence, "sourceEvidence"); + if (!"NEW_GAME_ROW".equals(sourceEvidence.provenanceKind())) { + throw new IllegalArgumentException("Fresh association requires NEW_GAME_ROW provenance"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapter.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapter.java new file mode 100644 index 0000000000..d1eb68ea5b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapter.java @@ -0,0 +1,166 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadGrpcCodec; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.grpc.server.service.GrpcService; + +/** + * Entity-only source read adapter. Its Game Session and Game Design evidence does not replace the + * Account staging snapshot supplied to Entity and never enables PLAY, actor entry, bootstrap, OPEN, + * or generation. + */ +@GrpcService +public final class CanonicalGameplayRosterOwnerReadGrpcAdapter + extends CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase { + private final ObjectProvider sourceReaderProvider; + private final CanonicalGameplayRosterOwnerReadWorkloadGuard workloadGuard; + + public CanonicalGameplayRosterOwnerReadGrpcAdapter( + ObjectProvider sourceReaderProvider, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.sourceReaderProvider = sourceReaderProvider; + this.workloadGuard = new CanonicalGameplayRosterOwnerReadWorkloadGuard(workloadNamespace); + } + + @Override + public void getCanonicalGameplayRosterOwnerRead( + GetCanonicalGameplayRosterOwnerReadRequest request, + StreamObserver responseObserver) { + CanonicalGameplayRosterOwnerReadEvidence.Request typedRequest; + try { + workloadGuard.requireEntityOwnerReadCaller(); + typedRequest = CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(request); + workloadGuard.requireConfiguredTargetNamespace(typedRequest.targetNamespace()); + } catch (AdminAuthorizationException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Canonical gameplay roster owner read is not authorized") + .asRuntimeException()); + return; + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical gameplay roster owner read request is invalid") + .asRuntimeException()); + return; + } + try { + CanonicalPublishedPlayerRouteReadService sourceReader = sourceReaderProvider.getIfAvailable(); + if (sourceReader == null) { + throw new SourceUnavailableException(); + } + CanonicalGameplayRosterOwnerReadEvidence evidence = sourceReader.readCurrent(typedRequest); + responseObserver.onNext( + CanonicalGameplayRosterOwnerReadGrpcCodec.toResponse(typedRequest, evidence)); + responseObserver.onCompleted(); + } catch (CanonicalPublishedPlayerRouteReadService.StaleAuthorityException stale) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical gameplay roster route is stale") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException invalid) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical gameplay roster authority is invalid") + .asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical gameplay roster authority is invalid") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.StorageUnavailableException + | CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + | CanonicalPlayerRouteReadService.ReadUnavailableException + | SourceUnavailableException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Canonical gameplay roster owner read is unavailable") + .asRuntimeException()); + } catch (RuntimeException unexpected) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Canonical gameplay roster owner read failed") + .asRuntimeException()); + } + } + + @Override + public void getPreseededActorAssignmentOwnerRead( + GetPreseededActorAssignmentOwnerReadRequest request, + StreamObserver responseObserver) { + PreseededActorAssignmentOwnerReadEvidence.Request typedRequest; + try { + workloadGuard.requireEntityAssignmentOwnerReadCaller(); + typedRequest = PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(request); + workloadGuard.requireConfiguredTargetNamespace(typedRequest.targetNamespace()); + } catch (AdminAuthorizationException denied) { + responseObserver.onError( + Status.PERMISSION_DENIED + .withDescription("Actor assignment owner read is not authorized") + .asRuntimeException()); + return; + } catch (IllegalArgumentException invalid) { + responseObserver.onError( + Status.INVALID_ARGUMENT + .withDescription("Actor assignment owner read request is invalid") + .asRuntimeException()); + return; + } + try { + CanonicalPublishedPlayerRouteReadService sourceReader = sourceReaderProvider.getIfAvailable(); + if (sourceReader == null) { + throw new SourceUnavailableException(); + } + PreseededActorAssignmentOwnerReadEvidence evidence = + sourceReader.readCurrentForAssignment(typedRequest); + responseObserver.onNext( + PreseededActorAssignmentOwnerReadGrpcCodec.toResponse(typedRequest, evidence)); + responseObserver.onCompleted(); + } catch (CanonicalPublishedPlayerRouteReadService.StaleAuthorityException stale) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical actor assignment route is stale") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException invalid) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical actor assignment authority is invalid") + .asRuntimeException()); + } catch (IllegalArgumentException invalidEvidence) { + responseObserver.onError( + Status.FAILED_PRECONDITION + .withDescription("Canonical actor assignment authority is invalid") + .asRuntimeException()); + } catch (CanonicalPublishedPlayerRouteReadService.StorageUnavailableException + | CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + | CanonicalPlayerRouteReadService.ReadUnavailableException + | SourceUnavailableException unavailable) { + responseObserver.onError( + Status.UNAVAILABLE + .withDescription("Actor assignment owner read is unavailable") + .asRuntimeException()); + } catch (RuntimeException unexpected) { + responseObserver.onError( + Status.INTERNAL + .withDescription("Actor assignment owner read failed") + .asRuntimeException()); + } + } + + private static final class SourceUnavailableException extends RuntimeException {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadWorkloadGuard.java new file mode 100644 index 0000000000..6731e61ade --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadWorkloadGuard.java @@ -0,0 +1,58 @@ +package net.firedevops.firemud.gamesession.service.impl; + +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.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; + +/** Exact same-namespace Entity workload authorization for roster and assignment owner reads. */ +public final class CanonicalGameplayRosterOwnerReadWorkloadGuard { + private static final String ROSTER_METHOD_NAME = + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead"; + private static final String ASSIGNMENT_METHOD_NAME = + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead"; + private static final String ENTITY_MANAGEMENT_SERVICE = "entity-management-service"; + + private final String trustedNamespace; + + public CanonicalGameplayRosterOwnerReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireEntityOwnerReadCaller() { + requireEntityOwnerReadCaller( + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetCanonicalGameplayRosterOwnerReadMethod() + .getFullMethodName()); + } + + public void requireEntityAssignmentOwnerReadCaller() { + requireEntityOwnerReadCaller( + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetPreseededActorAssignmentOwnerReadMethod() + .getFullMethodName()); + } + + private void requireEntityOwnerReadCaller(String expectedMethod) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if ((!ROSTER_METHOD_NAME.equals(expectedMethod) + && !ASSIGNMENT_METHOD_NAME.equals(expectedMethod)) + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peer == null + || !ENTITY_MANAGEMENT_SERVICE.equals(peer.service()) + || !trustedNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + ENTITY_MANAGEMENT_SERVICE) + .equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Game Session owner read requires the exact same-namespace " + + "Entity Management workload without caller context"); + } + } + + public void requireConfiguredTargetNamespace(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || !trustedNamespace.equals(targetNamespace)) { + throw new AdminAuthorizationException( + "Game Session owner-read target namespace is not configured here"); + } + } +} 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 new file mode 100644 index 0000000000..113acd8cbd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.gamesession.service.impl; + +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; + +/** + * Durable owner operation; remote World proof is acquired before entering its short SQL + * transaction. + */ +public final class DatabaseCanonicalInitialAdmissionService + implements CanonicalInitialAdmissionService { + private final CanonicalInitialAdmissionRepository repository; + private final GameSessionCanonicalAdmissionPointerRepository pointerRepository; + private final CanonicalInitialAdmissionWorldVerifier worldVerifier; + + public DatabaseCanonicalInitialAdmissionService( + CanonicalInitialAdmissionRepository repository, + GameSessionCanonicalAdmissionPointerRepository pointerRepository, + CanonicalInitialAdmissionWorldVerifier worldVerifier) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.pointerRepository = Objects.requireNonNull(pointerRepository, "pointerRepository"); + this.worldVerifier = Objects.requireNonNull(worldVerifier, "worldVerifier"); + } + + @Override + public CanonicalInitialAdmissionOwnerProof bind(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + 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); + 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; + } + + @Override + public CanonicalInitialAdmissionOwnerProof abort( + CanonicalInitialAdmissionRequest request, String reason) { + Objects.requireNonNull(request, "request"); + repository.reserve(request); + CanonicalInitialAdmissionOwnerProof beforeAbort = + requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + if (beforeAbort.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + return beforeAbort; + } + PreparedExpectedClosed preparedOrigin = prepareExpectedClosed(request); + repository.abort(request, preparedOrigin, reason); + return requireRead(request.targetNamespace(), request.initialAdmissionRequestId()); + } + + @Override + public CanonicalInitialAdmissionOwnerProof read(String targetNamespace, String requestId) { + return requireRead(targetNamespace, requestId); + } + + 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 + .read(targetNamespace, requestId) + .orElseThrow( + () -> + new CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission attempt has no durable owner result")); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java new file mode 100644 index 0000000000..62eee4e673 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultDeniedCanonicalInitialAdmissionWorldVerifier.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import java.util.Objects; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * Safe default unless the typed authenticated World initial-admission owner is explicitly composed. + * Caller context, local configuration, and supplied hold identifiers are never owner proof. + */ +@Component +@ConditionalOnProperty( + prefix = "firemud.canonical-initial-admission-world-owner", + name = "enabled", + havingValue = "false", + matchIfMissing = true) +public final class DefaultDeniedCanonicalInitialAdmissionWorldVerifier + implements CanonicalInitialAdmissionWorldVerifier { + @Override + public CanonicalInitialAdmissionWorldProof verify(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + throw new IllegalStateException( + "Canonical initial admission is denied until authenticated World ACTIVE/hold verification is wired"); + } +} diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 085467d1a1..0d9de7b362 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -129,6 +129,8 @@ firemud: force-internal-service-outbound: true public-methods: - game_session.v1.GameSessionService/Ping + - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead + - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} 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 new file mode 100644 index 0000000000..0e107db1ce --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -0,0 +1,718 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.UUID; +import 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.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +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.GameSessionCanonicalRealmCatalogRepository; +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 org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.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; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalRealmCatalogRepositoryIntegrationTest { + private static final String NAMESPACE = "canonical-realm-catalog-it"; + private static final long RETAINED_TENANT_ID = 917L; + private static final long ODD_RETAINED_TENANT_ID = 918L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final UUID RETAINED_REALM_ID = uuid(801); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(802); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(803); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumericEvidence() { + 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"); + String retainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String retainedPointerXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class); + String oddRetainedNamespaceXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + CanonicalRealmCatalogSnapshot replay = fixture.create(request); + + assertThat(created).isEqualTo(replay); + assertThat(created.tenantId()).isEqualTo(tenant(1)); + assertThat(created.tenantSlug()).isEqualTo(source.source().tenantSlug()); + assertThat(created.worldSlug()).isEqualTo("new-world"); + assertThat(created.realmSlug()).isEqualTo(" Public Realm / East "); + assertThat(created.stateScope()).isEqualTo("SHARED"); + assertThat(created.catalogRevision()).isEqualTo(1L); + assertThat(created.playableStateNamespaceId()).isNotEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat(created.sourceIntakeReceipt()).isEqualTo(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat(fixture.catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, tenant(1))) + .contains(created); + + assertThat( + requiredRecord( + fixture.dsl, + "SELECT tenant_id, canonical_tenant_id, playable_state_namespace_id " + + "FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .satisfies( + row -> { + assertThat(row.get("tenant_id", Long.class)).isNull(); + assertThat(row.get("canonical_tenant_id", UUID.class)).isEqualTo(tenant(1)); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(created.playableStateNamespaceId()); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT realm_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("realm_id", UUID.class)) + .isEqualTo(RETAINED_REALM_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_admission_pointer WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedPointerXmin); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(NIL_UUID); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + ODD_RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(oddRetainedNamespaceXmin); + + // The existing runtime selector remains supported by the new nullable-tenant identity layout. + fixture.dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?) " + + "ON CONFLICT (tenant_id) DO NOTHING", + RETAINED_TENANT_ID, + uuid(804)); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(3); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("xmin", String.class)) + .isEqualTo(retainedNamespaceXmin); + + assertThatThrownBy( + () -> + fixture.create( + request( + source, + uuid(21), + "another-realm", + "Another Realm", + "owner-mode", + "SHARED"))) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("already has a public-production"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_realm_catalog SET realm_slug = ? " + + "WHERE creation_request_id = ?", + "rewritten-realm", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + request.requestId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy(() -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint"); + // The disposable schema's CASCADE form reaches the statement immutability guards after + // PostgreSQL's separate catalog/pointer foreign-key precondition has been satisfied. + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog CASCADE")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE canonical_tenant_id = ?", + uuid(805), + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE gameplay_tenant_shared_playable_state_namespace")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("fresh shared namespace identity is immutable"); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + } + + @Test + void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenance() { + Fixture fixture = fixture(false); + IntakeReceipt source = fixture.register(tenant(2), "world-two", "World Two", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest request = + request(source, uuid(30), "realm", "Realm", "owner-mode", "SHARED"); + + PreparedInitialPublicProduction prepared = + fixture.catalogRepository.prepareInitialPublicProduction(request); + assertThatThrownBy(() -> fixture.catalogRepository.createInitialPublicProduction(prepared)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active owner transaction"); + TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); + readOnly.setReadOnly(true); + assertThatThrownBy( + () -> + readOnly.execute( + status -> fixture.catalogRepository.createInitialPublicProduction(prepared))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-write"); + + CanonicalRealmCatalogSnapshot created = fixture.create(request); + String beforeXmin = + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class); + CreateCanonicalRealmCatalogRequest changed = + request(source, request.requestId(), "realm", "Changed Realm", "owner-mode", "SHARED"); + assertThatThrownBy(() -> fixture.create(changed)).isInstanceOf(CatalogConflictException.class); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(created); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT xmin::text AS xmin FROM game_session_canonical_realm_catalog " + + "WHERE creation_request_id = ?", + request.requestId()) + .get("xmin", String.class)) + .isEqualTo(beforeXmin); + + CreateCanonicalRealmCatalogRequest wrongSource = + new CreateCanonicalRealmCatalogRequest( + uuid(32), + NAMESPACE, + source.source().canonicalTenantId(), + uuid(33), + "other-realm", + "Other Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy(() -> fixture.catalogRepository.prepareInitialPublicProduction(wrongSource)) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("source intake is missing"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + + IntakeReceipt otherTenantSource = + fixture.register(tenant(9), "world-nine", "World Nine", "NEW_GAME_ROW"); + CreateCanonicalRealmCatalogRequest mismatchedSource = + new CreateCanonicalRealmCatalogRequest( + uuid(34), + NAMESPACE, + source.source().canonicalTenantId(), + otherTenantSource.operationId(), + "mismatched-realm", + "Mismatched Realm", + true, + true, + "SHARED", + "owner-mode", + null, + null); + assertThatThrownBy( + () -> fixture.catalogRepository.prepareInitialPublicProduction(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")))) + .isEqualTo(1); + + IntakeReceipt retained = + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V30"); + assertThatThrownBy( + () -> + fixture.create( + request(retained, uuid(31), "retained-realm", "Realm", "owner-mode", "SHARED"))) + .isInstanceOf(InvalidCatalogEvidenceException.class) + .hasMessageContaining("fresh Game Design"); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + } + + @Test + void isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry() { + Fixture fixture = fixture(true); + IntakeReceipt firstSource = + fixture.register(tenant(4), "world-four", "World Four", "NEW_GAME_ROW"); + IntakeReceipt secondSource = + fixture.register(tenant(5), "world-five", "World Five", "NEW_GAME_ROW"); + + CanonicalRealmCatalogSnapshot first = + fixture.create( + request(firstSource, uuid(40), "realm-four", "Realm Four", "owner-mode", "ISOLATED")); + CanonicalRealmCatalogSnapshot second = + fixture.create( + request(secondSource, uuid(50), "realm-five", "Realm Five", "owner-mode", "ISOLATED")); + + assertThat(first.playableStateNamespaceId()).isNotEqualTo(second.playableStateNamespaceId()); + assertThat(first.tenantSlug()).isNotEqualTo(first.worldSlug()); + assertThat(second.tenantSlug()).isNotEqualTo(second.worldSlug()); + assertThat( + fixture.dsl.fetch( + "SELECT canonical_tenant_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id IS NOT NULL")) + .isEmpty(); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(40))).contains(first); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(50))).contains(second); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE tenant_id = ?", + first.playableStateNamespaceId(), + RETAINED_TENANT_ID)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining( + "Legacy tenant SHARED namespace conflicts with a canonical ISOLATED realm namespace"); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + } + + @Test + void concurrentExactCreationRecoversOneDurableRealmAndNamespace() throws Exception { + Fixture fixture = fixture(false); + 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"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + Future second = + executor.submit(() -> raceCreate(fixture, ready, start, request)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + CanonicalRealmCatalogSnapshot firstResult = first.get(20, TimeUnit.SECONDS); + CanonicalRealmCatalogSnapshot secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())) + .contains(firstResult); + assertThat( + fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("gameplay_tenant_shared_playable_state_namespace")))) + .isEqualTo(1); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void freshCatalogAndRetainedAssociationCannotBothAcquireTenantAuthorityInEitherOrder() { + Fixture associationFirst = fixture(false); + IntakeReceipt associationFirstSource = + associationFirst.register( + tenant(7), "association-first-world", "Association First", "NEW_GAME_ROW"); + associationFirst.insertRetainedAssociation(associationFirstSource, uuid(70)); + CreateCanonicalRealmCatalogRequest afterAssociation = + request( + associationFirstSource, + uuid(71), + "association-first-realm", + "Association First Realm", + "owner-mode", + "SHARED"); + assertThatThrownBy( + () -> + associationFirst.catalogRepository.prepareInitialPublicProduction(afterAssociation)) + .isInstanceOf(CatalogConflictException.class) + .hasMessageContaining("retained numeric Game Session identity"); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isZero(); + assertThat( + associationFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isEqualTo(1); + + Fixture catalogFirst = fixture(false); + IntakeReceipt catalogFirstSource = + catalogFirst.register(tenant(8), "catalog-first-world", "Catalog First", "NEW_GAME_ROW"); + CanonicalRealmCatalogSnapshot catalog = + catalogFirst.create( + request( + catalogFirstSource, + uuid(80), + "catalog-first-realm", + "Catalog First Realm", + "owner-mode", + "SHARED")); + assertThatThrownBy(() -> catalogFirst.insertRetainedAssociation(catalogFirstSource, uuid(81))) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("cannot replace fresh canonical tenant namespace authority"); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_realm_catalog")))) + .isEqualTo(1); + assertThat(catalogFirst.catalogRepository.readByRequest(NAMESPACE, uuid(80))).contains(catalog); + assertThat( + catalogFirst.dsl.fetchCount( + DSL.table(DSL.name("game_session_retained_tenant_association")))) + .isZero(); + } + + private CanonicalRealmCatalogSnapshot raceCreate( + Fixture fixture, + CountDownLatch ready, + CountDownLatch start, + CreateCanonicalRealmCatalogRequest request) + throws Exception { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for canonical realm creation race"); + } + return fixture.create(request); + } + + private static CreateCanonicalRealmCatalogRequest request( + IntakeReceipt source, + UUID requestId, + String realmSlug, + String displayName, + String policy, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + source.source().canonicalTenantId(), + source.operationId(), + realmSlug, + displayName, + true, + true, + scope, + policy, + null, + null); + } + + private static AuthoredWorldSourceEvidence source( + UUID tenantId, String worldSlug, String displayName, String provenance) { + UUID registrationRequestId = + UUID.nameUUIDFromBytes( + ("registration-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + UUID sourceOperationId = + UUID.nameUUIDFromBytes( + ("operation-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + String tenantSlug = "tenant-" + tenantId.toString().substring(0, 8); + long sourceGameRowId = Math.abs(tenantId.getMostSignificantBits()) + 10L; + String sourceGameTenantKey = "gds-tenant-" + tenantId.toString().substring(0, 8); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, tenantId, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + tenantId, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + provenance, + evidenceDigest); + } + + private Fixture fixture(boolean seedRetainedNumericRows) { + String schema = "gs_canonical_realm_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + 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) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + if (seedRetainedNumericRows) { + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_SHARED_NAMESPACE_ID); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + ODD_RETAINED_TENANT_ID, + NIL_UUID); + dsl.execute( + "INSERT INTO gameplay_admission_pointer " + + "(world_slug, world_display_name, realm_slug, 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, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "legacy-world", + "Legacy World", + "legacy-realm", + "Legacy Realm", + RETAINED_TENANT_ID, + 501L, + 1L, + true, + false, + "SHARED", + "ALLOW_NEW", + "fixture", + "retained evidence", + true, + RETAINED_REALM_ID, + RETAINED_PLAYABLE_NAMESPACE_ID); + } + + 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 transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new Fixture( + transactionalDsl, + new GameSessionAuthoredWorldSourceRepository(transactionalDsl), + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl), + transactionManager, + transactions); + } + + private static UUID tenant(int value) { + return uuid(100 + value); + } + + 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"); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions) { + IntakeReceipt register(UUID tenantId, String worldSlug, String displayName, String provenance) { + AuthoredWorldSourceEvidence source = + GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.source( + tenantId, worldSlug, displayName, provenance); + UUID intakeRequestId = + UUID.nameUUIDFromBytes( + ("intake-" + tenantId).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(intakeRequestId, source)); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot create(CreateCanonicalRealmCatalogRequest request) { + PreparedInitialPublicProduction prepared = + catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot snapshot = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(snapshot); + } + + void insertRetainedAssociation(IntakeReceipt source, UUID requestId) { + AuthoredWorldSourceEvidence evidence = source.source(); + String digest = "sha256:" + "a".repeat(64); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association (" + + "operation_id, approval_schema_version, target_namespace, association_request_id, " + + "request_digest, approval_operation_id, signer_key_id, approved_by, " + + "approval_reference, signed_at, legacy_game_session_tenant_id, canonical_tenant_id, " + + "source_game_row_id, source_game_tenant_key, provenance_kind, " + + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " + + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + UUID.nameUUIDFromBytes( + ("retained-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + NAMESPACE, + requestId, + digest, + UUID.nameUUIDFromBytes( + ("approval-operation-" + requestId) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + "fixture-key", + "fixture-operator", + "fixture-reference", + "2026-10-03T00:00:00Z", + RETAINED_TENANT_ID, + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.provenanceKind(), + evidence.evidenceDigest(), + digest, + "A".repeat(86) + "==", + "{}", + digest, + digest); + } + } +} diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java new file mode 100644 index 0000000000..135c86ee96 --- /dev/null +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalCurrentOpenPointerSnapshotDigestTest.java @@ -0,0 +1,234 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import org.junit.jupiter.api.Test; + +class CanonicalCurrentOpenPointerSnapshotDigestTest { + @Test + void canonicalEncodingMatchesFixedVectorIncludingLongUtf8AndNullOriginVersion() { + var projection = new Fixture().projection(); + + assertThat(projection.initialAdmissionRequestId()).hasSize(120); + assertThat(CanonicalCurrentOpenPointerSnapshotDigest.digest(projection)) + .isEqualTo("7bb3cb77966978f60e81ebd7189bae2ac40ead75fa6f496f4bf87d0366cf3cc2"); + } + + @Test + void canonicalDecimalCounterEncodingSupportsMaximumPositiveLongValues() { + Fixture fixture = new Fixture(); + fixture.catalogRevision = Long.MAX_VALUE; + fixture.pointerVersion = Long.MAX_VALUE; + fixture.activeWorldEpoch = Long.MAX_VALUE; + fixture.auditEventId = Long.MAX_VALUE; + fixture.originKind = OriginKind.EXPECT_CLOSED; + fixture.expectedPriorPointerVersion = Long.MAX_VALUE; + + assertThat(CanonicalCurrentOpenPointerSnapshotDigest.digest(fixture.projection())) + .isEqualTo("02703fae1556ed0b11d9d580e9d02b916f2e13cab623d5e3d73dad8cd9ead28f"); + } + + @Test + void changesToCurrentPointerTupleOrTerminalOwnerEvidenceChangeDigest() { + String base = digest(new Fixture()); + + Fixture changedPointerVersion = new Fixture(); + changedPointerVersion.pointerVersion = 74L; + assertThat(digest(changedPointerVersion)).isNotEqualTo(base); + + Fixture changedCatalogRevision = new Fixture(); + changedCatalogRevision.catalogRevision = 42L; + assertThat(digest(changedCatalogRevision)).isNotEqualTo(base); + + Fixture changedRequestIdentity = new Fixture(); + changedRequestIdentity.initialAdmissionRequestId = "first-open-operation-18"; + assertThat(digest(changedRequestIdentity)).isNotEqualTo(base); + + Fixture changedRequestDigest = new Fixture(); + changedRequestDigest.initialAdmissionRequestDigest = "b".repeat(64); + assertThat(digest(changedRequestDigest)).isNotEqualTo(base); + + Fixture changedHoldFence = new Fixture(); + changedHoldFence.holdFence = uuid("99999999-9999-4999-8999-999999999999"); + assertThat(digest(changedHoldFence)).isNotEqualTo(base); + + Fixture changedHoldDigest = new Fixture(); + changedHoldDigest.holdBindingDigest = "sha256:" + "d".repeat(64); + assertThat(digest(changedHoldDigest)).isNotEqualTo(base); + + Fixture changedOwnerProof = new Fixture(); + changedOwnerProof.ownerProofDigest = "sha256:" + "e".repeat(64); + assertThat(digest(changedOwnerProof)).isNotEqualTo(base); + + Fixture changedAudit = new Fixture(); + changedAudit.auditEventId = 28L; + assertThat(digest(changedAudit)).isNotEqualTo(base); + + Fixture changedTerminalTime = new Fixture(); + changedTerminalTime.terminalAt = Instant.parse("2026-10-07T00:00:00.000001Z"); + assertThat(digest(changedTerminalTime)).isNotEqualTo(base); + } + + @Test + void rejectsNoncurrentFlagsInvalidSelectorsAndMalformedDigests() { + Fixture hidden = new Fixture(); + hidden.visible = false; + assertInvalid(hidden); + + Fixture privateRealm = new Fixture(); + privateRealm.publicProductionRealm = false; + assertInvalid(privateRealm); + + Fixture isolatedRealm = new Fixture(); + isolatedRealm.playableStateScope = "ISOLATED"; + assertInvalid(isolatedRealm); + + Fixture closedPointer = new Fixture(); + closedPointer.admissionState = "CLOSED"; + assertInvalid(closedPointer); + + Fixture changedSelector = new Fixture(); + changedSelector.worldSlug = "not a canonical slug"; + assertInvalid(changedSelector); + + Fixture nonpositivePointer = new Fixture(); + nonpositivePointer.pointerVersion = 0L; + assertInvalid(nonpositivePointer); + + Fixture nonpositiveCatalog = new Fixture(); + nonpositiveCatalog.catalogRevision = 0L; + assertInvalid(nonpositiveCatalog); + + Fixture nonpositiveEpoch = new Fixture(); + nonpositiveEpoch.activeWorldEpoch = 0L; + assertInvalid(nonpositiveEpoch); + + Fixture malformedRequestDigest = new Fixture(); + malformedRequestDigest.initialAdmissionRequestDigest = "A".repeat(64); + assertInvalid(malformedRequestDigest); + + Fixture malformedHoldDigest = new Fixture(); + malformedHoldDigest.holdBindingDigest = "sha256:" + "G".repeat(64); + assertInvalid(malformedHoldDigest); + + Fixture requiresCharacterSelection = new Fixture(); + requiresCharacterSelection.requiresCharacterSelection = true; + assertInvalid(requiresCharacterSelection); + + Fixture preparedVersionUpgrade = new Fixture(); + preparedVersionUpgrade.preparedVersionUpgradeId = "prepared-upgrade"; + assertInvalid(preparedVersionUpgrade); + + Fixture invalidNullableOrigin = new Fixture(); + invalidNullableOrigin.expectedPriorPointerVersion = 1L; + assertInvalid(invalidNullableOrigin); + + Fixture invalidUtf16 = new Fixture(); + invalidUtf16.worldDisplayName = "bad\uD800"; + assertInvalid(invalidUtf16); + } + + @Test + void nullablePriorVersionHasAClosedOriginRepresentation() { + Fixture noPrior = new Fixture(); + assertThat(noPrior.expectedPriorPointerVersion).isNull(); + String noPriorDigest = digest(noPrior); + + Fixture expectedClosed = new Fixture(); + expectedClosed.originKind = OriginKind.EXPECT_CLOSED; + expectedClosed.expectedPriorPointerVersion = 1L; + assertThat(digest(expectedClosed)).isNotEqualTo(noPriorDigest); + + expectedClosed.expectedPriorPointerVersion = null; + assertInvalid(expectedClosed); + } + + private static String digest(Fixture fixture) { + return CanonicalCurrentOpenPointerSnapshotDigest.digest(fixture.projection()); + } + + private static void assertInvalid(Fixture fixture) { + assertThatThrownBy(() -> fixture.projection()).isInstanceOf(IllegalArgumentException.class); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class Fixture { + int representationVersion = 3; + String targetNamespace = "gameplay"; + UUID canonicalTenantId = uuid("11111111-1111-4111-8111-111111111111"); + String worldSlug = "demo-world"; + String worldDisplayName = "Demo Ω World"; + UUID realmId = uuid("22222222-2222-4222-8222-222222222222"); + String realmSlug = "main"; + String realmDisplayName = "Production — Main"; + UUID playableStateNamespaceId = uuid("33333333-3333-4333-8333-333333333333"); + String playableStateScope = "SHARED"; + long catalogRevision = 41L; + long pointerVersion = 73L; + String admissionState = "OPEN"; + boolean visible = true; + boolean publicProductionRealm = true; + Boolean requiresCharacterSelection; + String characterCreationPolicy = "ALLOW_NEW"; + UUID canonicalGameInstanceId = uuid("44444444-4444-4444-8444-444444444444"); + UUID canonicalVersionId = uuid("55555555-5555-4555-8555-555555555555"); + String initialAdmissionRequestId = "request-" + "x".repeat(112); + String initialAdmissionRequestDigest = "a".repeat(64); + OriginKind originKind = OriginKind.NO_PRIOR_POINTER; + Long expectedPriorPointerVersion; + long activeWorldEpoch = 82L; + UUID holdId = uuid("77777777-7777-4777-8777-777777777777"); + UUID holdFence = uuid("88888888-8888-4888-8888-888888888888"); + String holdBindingDigest = "sha256:" + "c".repeat(64); + String lastUpdatedBy = "game-session-canonical-initial-admission"; + String lastUpdateReason = "World-held initial admission"; + String preparedVersionUpgradeId; + String ownerProofDigest = "sha256:" + "f".repeat(64); + long auditEventId = 27L; + Instant terminalAt = Instant.parse("2026-10-07T00:00:00Z"); + + CanonicalCurrentOpenPointerSnapshotDigest.Projection projection() { + return new CanonicalCurrentOpenPointerSnapshotDigest.Projection( + representationVersion, + targetNamespace, + canonicalTenantId, + worldSlug, + worldDisplayName, + realmId, + realmSlug, + realmDisplayName, + playableStateNamespaceId, + playableStateScope, + catalogRevision, + pointerVersion, + admissionState, + visible, + publicProductionRealm, + requiresCharacterSelection, + characterCreationPolicy, + canonicalGameInstanceId, + canonicalVersionId, + initialAdmissionRequestId, + initialAdmissionRequestDigest, + originKind, + expectedPriorPointerVersion, + activeWorldEpoch, + holdId, + holdFence, + holdBindingDigest, + lastUpdatedBy, + lastUpdateReason, + preparedVersionUpgradeId, + ownerProofDigest, + auditEventId, + terminalAt); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java new file mode 100644 index 0000000000..d930818393 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java @@ -0,0 +1,809 @@ +package unit.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.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.lang.reflect.Field; +import java.security.MessageDigest; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +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.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayRosterClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_UUID = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID ACCOUNT_UUID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID ACTOR_UUID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID SNAPSHOT_UUID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ASSIGNMENT_UUID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + // Golden v3 vector from Entity's CanonicalGameplayRosterSnapshotDigest.compute contract. + private static final String ENTITY_OWNED_ROSTER_DIGEST_VECTOR = + "a567381a308464fb6f6b5d18fcd7caa1eb29faf5c37903b130f98ef351a0060f"; + + @Test + void sendsExactPublishedTargetWithAccountAndValidatesSourceSnapshot() throws Exception { + var route = publishedRoute(); + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + var actor = actor(ACTOR_UUID, "Pilot One"); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of(ACTOR_UUID.toString(), "Pilot One"))) + .addActors(actor) + .build(); + }); + var client = newClient(stub); + + var roster = client.listPreseededRoster(route, ACCOUNT_UUID); + + assertThat(roster.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(roster.snapshotUuid()).isEqualTo(SNAPSHOT_UUID); + assertThat(roster.target().getTenantUuid()).isEqualTo(TENANT_UUID.toString()); + assertThat(roster.target().getPublishedPolicyDigest()) + .isEqualTo(route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())); + assertThat(roster.target().getPublishedPolicyDigest()).matches("[0-9a-f]{64}"); + assertThat(roster.target().getPublishedReleaseBundleRef()) + .isEqualTo(route.policySetEvidence().publishedReleaseBundleRef()); + assertThat(roster.target().getPublishedOwnerProofDigest()).isEqualTo("f".repeat(64)); + assertThat(roster.actors()) + .containsExactly(new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One")); + + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + var requestCaptor = org.mockito.ArgumentCaptor.forClass(CanonicalGameplayRosterRequest.class); + verify(stub).listPreseededRoster(requestCaptor.capture()); + var request = requestCaptor.getValue(); + assertThat(UUID.fromString(request.getRequestUuid()).toString()) + .isEqualTo(request.getRequestUuid()); + assertThat(request.getCanonicalAccountUuid()).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(request.getExpectedTarget()).isEqualTo(roster.target()); + assertThat(request.getExpectedTarget().getPublishedPolicyDigest()) + .isEqualTo(route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())); + } + + @Test + void matchesEntityOwnedRosterDigestV3GoldenVector() throws Exception { + var target = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid("11111111-1111-4111-8111-111111111111") + .setRealmUuid("22222222-2222-4222-8222-222222222222") + .setWorldSlug("earth") + .setRealmSlug("main") + .setGameInstanceUuid("44444444-4444-4444-8444-444444444444") + .setCatalogRevision(1L) + .setPointerVersion(7L) + .setActiveWorldEpoch(82L) + .setCanonicalVersionUuid("33333333-3333-4333-8333-333333333333") + .setPublishedPolicyDigest("a".repeat(64)) + .setPublishedReleaseBundleRef("release/fixture-v1") + .setAdmissionPointerSnapshotDigest("d".repeat(64)) + .setPublishedOwnerProofDigest("f".repeat(64)) + .setPlayableStateNamespaceUuid("55555555-5555-4555-8555-555555555555") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + var calculateDigest = + CanonicalGameplayRosterClient.class.getDeclaredMethod( + "calculateSnapshotDigest", UUID.class, CanonicalGameplayRosterTarget.class, List.class); + calculateDigest.setAccessible(true); + + String digest = + (String) + calculateDigest.invoke( + null, + ACCOUNT_UUID, + target, + List.of(new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"))); + + assertThat(digest).isEqualTo(ENTITY_OWNED_ROSTER_DIGEST_VECTOR); + } + + @Test + void rejectsChangedAccountAndCompleteTargetEcho() throws Exception { + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(TENANT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .build(); + }); + + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("canonical account UUID"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget().toBuilder().setPointerVersion(99L).build()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + } + + @Test + void rejectsDuplicateMalformedAndUnsupportedActors() throws Exception { + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + var duplicate = actor(ACTOR_UUID, "Pilot One"); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of( + ACTOR_UUID.toString(), + "Pilot One", + ACTOR_UUID.toString(), + "Pilot One"))) + .addActors(duplicate) + .addActors(duplicate) + .build(); + }); + + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("duplicate character UUID"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .addActors( + actor(ACTOR_UUID, "Pilot One").toBuilder().setDisplayName(" Pilot ").build()) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("display name is malformed"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .addActors( + actor(ACTOR_UUID, "Pilot One").toBuilder() + .setActorKind( + CanonicalGameplayRosterActorKind + .CANONICAL_ROSTER_ACTOR_KIND_UNSPECIFIED) + .build()) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unsupported actor kind"); + } + + @Test + void rejectsBadSnapshotDigestAndEntityApplicationErrors() throws Exception { + var stub = mockStub(); + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .addActors(actor(ACTOR_UUID, "Pilot One")) + .build(); + }); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("snapshot_digest does not bind"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA") + .setSnapshotDigest("a".repeat(64)) + .build(); + }) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("snapshot_uuid is not a canonical non-nil UUID"); + + doReturn( + CanonicalGameplayRosterResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("OWNER_EVIDENCE_UNAVAILABLE") + .setMessage("not returned as roster data")) + .build()) + .when(stub) + .listPreseededRoster(any()); + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("OWNER_EVIDENCE_UNAVAILABLE"); + } + + @Test + void readsExactSelectedAssignmentAndReturnsBoundNonAdmissionCapability() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request); + }); + + var verified = client.readSelectedPreseededAssignment(roster, ACTOR_UUID); + + assertThat(verified.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(verified.selectedCharacterUuid()).isEqualTo(ACTOR_UUID); + assertThat(verified.target()).isEqualTo(roster.target()); + assertThat(verified.rosterSnapshotUuid()).isEqualTo(SNAPSHOT_UUID); + assertThat(verified.rosterSnapshotDigest()).isEqualTo(roster.snapshotDigest()); + assertThat(verified.assignmentOperationId()).isEqualTo(ASSIGNMENT_UUID); + assertThat(verified.intentDigest()).isEqualTo("c".repeat(64)); + + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(CanonicalGameplayRosterSelectedAssignmentRequest.class); + verify(stub).readSelectedPreseededAssignment(requestCaptor.capture()); + var request = requestCaptor.getValue(); + UUID requestUuid = UUID.fromString(request.getRequestUuid()); + assertThat(requestUuid.toString()).isEqualTo(request.getRequestUuid()); + assertThat(requestUuid.version()).isEqualTo(4); + assertThat(requestUuid.variant()).isEqualTo(2); + assertThat(requestUuid).isNotIn(ACCOUNT_UUID, ACTOR_UUID, SNAPSHOT_UUID, ASSIGNMENT_UUID); + assertThat(request.getCanonicalAccountUuid()).isEqualTo(ACCOUNT_UUID.toString()); + assertThat(request.getSelectedCharacterUuid()).isEqualTo(ACTOR_UUID.toString()); + assertThat(request.getExpectedTarget()).isEqualTo(roster.target()); + verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsChangedAssignmentCorrelationAccountActorAndCompleteTarget() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var responseNumber = new AtomicInteger(); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + var response = selectedAssignmentResponse(request).toBuilder(); + return switch (responseNumber.getAndIncrement()) { + case 0 -> response.setRequestUuid(UUID.randomUUID().toString()).build(); + case 1 -> response.setCanonicalAccountUuid(TENANT_UUID.toString()).build(); + case 2 -> response.setSelectedCharacterUuid(SNAPSHOT_UUID.toString()).build(); + default -> + response + .setTarget(request.getExpectedTarget().toBuilder().setPointerVersion(99L)) + .build(); + }; + }); + + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("request correlation"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("canonical account UUID"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("selected character UUID"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + } + + @Test + void rejectsUnknownFieldsErrorsAndMissingSelectedAssignmentFields() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var unknown = + UnknownFieldSet.newBuilder() + .addField(101, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setUnknownFields(unknown) + .build(); + }); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("unknown fields"); + + doAnswer( + invocation -> + CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("SELECTED_ASSIGNMENT_UNAVAILABLE") + .setMessage("not assignment data")) + .build()) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTED_ASSIGNMENT_UNAVAILABLE"); + + doAnswer( + invocation -> + CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("SELECTED_ASSIGNMENT_UNAVAILABLE") + .setUnknownFields(unknown)) + .build()) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("error contains unknown fields"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder().clearTarget().build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setTarget(request.getExpectedTarget().toBuilder().setUnknownFields(unknown)) + .build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("complete expected target"); + } + + @Test + void rejectsNilOrMalformedAssignmentReferenceAndIntentDigest() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + + for (String assignmentUuid : + List.of( + "00000000-0000-0000-0000-000000000000", + "BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB", + "not-an-assignment-uuid")) { + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = + invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setAssignmentUuid(assignmentUuid) + .build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("assignment_uuid"); + } + + for (String intentDigest : List.of("", "C".repeat(64), "sha256:" + "c".repeat(64))) { + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = + invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder() + .setIntentDigest(intentDigest) + .build(); + }) + .when(stub) + .readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("intent_digest"); + } + } + + @Test + void rejectsAbsentOrDuplicateSelectedActorInRosterInput() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var absentRoster = + rosterWithActors( + roster, + List.of( + new CanonicalGameplayRosterClient.RosterActor( + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), "Other Pilot"))); + var duplicateRoster = + rosterWithActors( + roster, + List.of( + new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"), + new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"))); + + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(absentRoster, ACTOR_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exactly once"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(duplicateRoster, ACTOR_UUID)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate actor"); + verify(stub, never()).readSelectedPreseededAssignment(any()); + } + + @Test + void refusesSelectedAssignmentReadInsideTransactionOrSynchronization() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + + try { + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("transaction or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + verify(stub, never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsNilAccountBeforeClientUseAndRequiresWorkloadMtls() { + var factory = mock(GrpcChannelFactory.class); + var uninitialized = newClientWithoutStub(factory); + assertThatThrownBy(() -> uninitialized.listPreseededRoster(publishedRoute(), new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical non-nil"); + verifyNoInteractions(factory); + + var plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), plaintext, factory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), mtlsProperties(), factory, "invalid.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(factory); + } + + @Test + void rejectsResponsesFromOtherEntityWorkloadIdentity() throws Exception { + ManagedChannel channel = mock(ManagedChannel.class); + SSLSession sslSession = mock(SSLSession.class); + X509Certificate peerCertificate = mock(X509Certificate.class); + when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] {peerCertificate}); + when(peerCertificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/other/sa/entity-management-service"))); + Attributes attributes = + Attributes.newBuilder().set(io.grpc.Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build(); + @SuppressWarnings("unchecked") + ClientCall call = + mock(ClientCall.class); + when(call.getAttributes()).thenReturn(attributes); + doAnswer( + invocation -> { + @SuppressWarnings("unchecked") + ClientCall.Listener listener = + invocation.getArgument(0); + listener.onMessage(CanonicalGameplayRosterResponse.getDefaultInstance()); + listener.onClose(Status.OK, new Metadata()); + return null; + }) + .when(call) + .start(any(), any()); + when(channel.newCall( + any(), any())) + .thenReturn(call); + + var client = newClientWithChannel(channel); + assertThatThrownBy(() -> client.listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + } + + private static CanonicalPublishedPlayerRoute publishedRoute() { + var fixture = + PublishedRealmPolicyEvidenceFixture.fixture( + PublishedRealmPolicyEvidenceFixture.policy("main", true, true, "SHARED")); + var policySet = fixture.set(); + PublishedRealmEntryPolicyEvidence selected = policySet.policies().getFirst(); + var route = + new CanonicalPlayableTarget( + NAMESPACE, + "tenant-key", + TENANT_UUID, + "earth", + "Earth", + uuid("22222222-2222-4222-8222-222222222222"), + "main", + "main", + 101L, + 202L, + uuid("33333333-3333-4333-8333-333333333333"), + "SHARED", + uuid("44444444-4444-4444-8444-444444444444"), + fixture.target().canonicalVersionId(), + 303L, + 1L, + 7L, + "d".repeat(64), + 82L, + "first-open-operation-17", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + uuid("99999999-9999-4999-8999-999999999999"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "sha256:" + "c".repeat(64), + 27L, + "sha256:" + "f".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.parse("2026-10-07T00:00:00Z"), + "ALLOW_NEW"); + return new CanonicalPublishedPlayerRoute(route, policySet, selected); + } + + private static net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor actor( + UUID characterUuid, String displayName) { + return net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(characterUuid.toString()) + .setDisplayName(displayName) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build(); + } + + private static CanonicalGameplayRosterClient.PreseededRosterSnapshot validatedRoster( + CanonicalGameplayRosterClient client, + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) { + when(stub.listPreseededRoster(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of(ACTOR_UUID.toString(), "Pilot One"))) + .addActors(actor(ACTOR_UUID, "Pilot One")) + .build(); + }); + return client.listPreseededRoster(publishedRoute(), ACCOUNT_UUID); + } + + private static CanonicalGameplayRosterSelectedAssignmentResponse selectedAssignmentResponse( + CanonicalGameplayRosterSelectedAssignmentRequest request) { + return CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(request.getExpectedTarget()) + .setAssignmentUuid(ASSIGNMENT_UUID.toString()) + .setIntentDigest("c".repeat(64)) + .build(); + } + + private static CanonicalGameplayRosterClient.PreseededRosterSnapshot rosterWithActors( + CanonicalGameplayRosterClient.PreseededRosterSnapshot source, + List actors) + throws Exception { + List digestEntries = new ArrayList<>(actors.size() * 2); + for (var actor : actors) { + digestEntries.add(actor.characterUuid().toString()); + digestEntries.add(actor.displayName()); + } + return new CanonicalGameplayRosterClient.PreseededRosterSnapshot( + source.canonicalAccountUuid(), + source.snapshotUuid(), + snapshotDigest(source.canonicalAccountUuid(), source.target(), digestEntries), + source.target(), + actors); + } + + private static String snapshotDigest( + UUID accountUuid, + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget target, + List actors) + throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + for (String value : + List.of( + "firemud.entity.canonical-gameplay-roster.v3", + accountUuid.toString(), + target.getTenantUuid(), + target.getRealmUuid(), + target.getWorldSlug(), + target.getRealmSlug(), + target.getGameInstanceUuid(), + Long.toString(target.getCatalogRevision()), + Long.toString(target.getPointerVersion()), + Long.toString(target.getActiveWorldEpoch()), + target.getCanonicalVersionUuid(), + target.getPublishedPolicyDigest(), + target.getPublishedReleaseBundleRef(), + target.getAdmissionPointerSnapshotDigest(), + target.getPublishedOwnerProofDigest(), + target.getPlayableStateNamespaceUuid(), + target.getPlayableStateScope().name(), + "PRESEEDED_ONLY", + Integer.toString(actors.size() / 2))) { + write(output, value); + } + for (String actorValue : actors) { + write(output, actorValue); + } + } + return java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray())); + } + + private static void write(DataOutputStream output, String value) throws Exception { + byte[] encoded = value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + output.writeInt(encoded.length); + output.write(encoded); + } + + private static CanonicalGameplayRosterClient newClient( + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static CanonicalGameplayRosterClient newClientWithChannel(ManagedChannel channel) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + var buildStub = + CanonicalGameplayRosterClient.class.getDeclaredMethod("buildStub", ManagedChannel.class); + buildStub.setAccessible(true); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, buildStub.invoke(client, channel)); + return client; + } + + private static CanonicalGameplayRosterClient newClientWithoutStub(GrpcChannelFactory factory) { + return new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), mtlsProperties(), factory, NAMESPACE); + } + + private static CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub + mockStub() { + var stub = + mock(CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static CommonGrpcClientProperties mtlsProperties() { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/entity-management-ca.crt"); + return tls; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java new file mode 100644 index 0000000000..cf2617292e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -0,0 +1,293 @@ +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.Mockito.doAnswer; +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 com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Attributes; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Field; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +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.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import org.junit.jupiter.api.Test; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class GameDesignPublishedRealmPolicyClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + + @Test + void returnsCompleteTypedEvidenceAndSendsExactRequestWithDeadline() throws Exception { + var evidence = evidence(); + var stub = mockStub(); + when(stub.listPublishedRealmEntryPolicies(any())) + .thenAnswer( + invocation -> { + var request = + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + invocation.getArgument(0, ListPublishedRealmEntryPoliciesRequest.class)); + return PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); + }); + var client = newClient(stub); + + PublishedRealmEntryPolicySetEvidence result = + client.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID); + + assertThat(result).isEqualTo(evidence); + assertThat(result.hasValidDigest()).isTrue(); + assertThat(result.policies()).hasSize(2); + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(ListPublishedRealmEntryPoliciesRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).listPublishedRealmEntryPolicies(requestCaptor.capture()); + var exactRequest = requestCaptor.getValue(); + assertThat(exactRequest.getSchemaVersion()).isEqualTo(1); + assertThat(exactRequest.getTargetNamespace()).isEqualTo(NAMESPACE); + assertThat(UUID.fromString(exactRequest.getReadRequestId()).toString()) + .isEqualTo(exactRequest.getReadRequestId()); + assertThat(exactRequest.getCanonicalTenantId()).isEqualTo(TENANT_ID.toString()); + assertThat(exactRequest.getCanonicalVersionId()).isEqualTo(VERSION_ID.toString()); + } + + @Test + void rejectsMalformedCanonicalTenantOrVersionBeforeStubUse() { + var channelFactory = mock(GrpcChannelFactory.class); + var client = newClientWithoutStub(channelFactory); + + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(null, VERSION_ID)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(TENANT_ID, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(new UUID(0L, 0L), VERSION_ID)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsUninitializedClientAndPropagatesUnavailableOwner() throws Exception { + var channelFactory = mock(GrpcChannelFactory.class); + var uninitialized = newClientWithoutStub(channelFactory); + assertThatThrownBy(() -> uninitialized.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized"); + verifyNoInteractions(channelFactory); + + var stub = mockStub(); + StatusRuntimeException unavailable = + Status.UNAVAILABLE.withDescription("Game Design unavailable").asRuntimeException(); + when(stub.listPublishedRealmEntryPolicies(any())).thenThrow(unavailable); + var client = newClient(stub); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isSameAs(unavailable); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + } + + @Test + void rejectsChangedRequestUnknownFieldsAndMalformedClosedEvidence() throws Exception { + var expectedEvidence = evidence(); + var stub = mockStub(); + when(stub.listPublishedRealmEntryPolicies(any())) + .thenAnswer( + invocation -> { + ListPublishedRealmEntryPoliciesRequest request = invocation.getArgument(0); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest( + request.toBuilder().setCanonicalVersionId(TENANT_ID.toString()).build()) + .setPolicySetEvidence(ByteString.copyFrom(expectedEvidence.canonicalBytes())) + .build(); + }); + assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("response is invalid"); + + doAnswer( + invocation -> { + var request = (ListPublishedRealmEntryPoliciesRequest) invocation.getArgument(0); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(request) + .setPolicySetEvidence(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build(); + }) + .when(stub) + .listPublishedRealmEntryPolicies(any()); + assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(IllegalStateException.class); + + doAnswer( + invocation -> { + var request = (ListPublishedRealmEntryPoliciesRequest) invocation.getArgument(0); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(request) + .setPolicySetEvidence(ByteString.copyFrom(expectedEvidence.canonicalBytes())) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + }) + .when(stub) + .listPublishedRealmEntryPolicies(any()); + assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsResponseFromDifferentMtlsWorkloadNamespace() throws Exception { + ManagedChannel channel = mock(ManagedChannel.class); + SSLSession sslSession = mock(SSLSession.class); + X509Certificate peerCertificate = mock(X509Certificate.class); + when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] {peerCertificate}); + when(peerCertificate.getSubjectAlternativeNames()) + .thenReturn(List.of(List.of(6, "spiffe://firemud/ns/other/sa/game-design-service"))); + Attributes attributes = + Attributes.newBuilder().set(io.grpc.Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession).build(); + @SuppressWarnings("unchecked") + ClientCall + call = mock(ClientCall.class); + when(call.getAttributes()).thenReturn(attributes); + doAnswer( + invocation -> { + @SuppressWarnings("unchecked") + ClientCall.Listener listener = + invocation.getArgument(0); + var request = + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + ListPublishedRealmEntryPoliciesRequest.newBuilder() + .setSchemaVersion(1) + .setTargetNamespace(NAMESPACE) + .setReadRequestId(UUID.randomUUID().toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setCanonicalVersionId(VERSION_ID.toString()) + .build()); + listener.onMessage( + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence())); + listener.onClose(Status.OK, new Metadata()); + return null; + }) + .when(call) + .start(any(), any()); + when(channel + . + newCall(any(), any())) + .thenReturn(call); + + var client = newClientWithChannel(channel); + assertThatThrownBy(() -> client.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + } + + @Test + void rejectsPlaintextIncompleteClasspathTlsAndInvalidNamespaceBeforeChannelCreation() { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = mtlsProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("TLS configuration is required"); + + var classpath = mtlsProperties(); + classpath.setPrivateKey("classpath:certs/client.key"); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + assertThatThrownBy( + () -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("one DNS label"); + verifyNoInteractions(channelFactory); + } + + private static PublishedRealmEntryPolicySetEvidence evidence() { + return PublishedRealmPolicyEvidenceFixture.fixture( + PublishedRealmPolicyEvidenceFixture.policy("main", true, true, "SHARED"), + PublishedRealmPolicyEvidenceFixture.policy("playtest", true, false, "ISOLATED")) + .set(); + } + + private static GameDesignPublishedRealmPolicyClient newClient( + PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub stub) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static GameDesignPublishedRealmPolicyClient newClientWithChannel(ManagedChannel channel) + throws Exception { + var client = newClientWithoutStub(mock(GrpcChannelFactory.class)); + var buildStub = + GameDesignPublishedRealmPolicyClient.class.getDeclaredMethod( + "buildStub", ManagedChannel.class); + buildStub.setAccessible(true); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, buildStub.invoke(client, channel)); + return client; + } + + private static GameDesignPublishedRealmPolicyClient newClientWithoutStub( + GrpcChannelFactory channelFactory) { + return new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, NAMESPACE); + } + + private static PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + mockStub() { + var stub = + mock( + PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub + .class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + return stub; + } + + private static CommonGrpcClientProperties mtlsProperties() { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("certs/game-session-client.crt"); + tls.setPrivateKey("certs/game-session-client.key"); + tls.setCaCert("certs/game-design-ca.crt"); + return tls; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelectionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelectionTest.java new file mode 100644 index 0000000000..4810b7c5b2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelectionTest.java @@ -0,0 +1,135 @@ +package net.firedevops.firemud.gamesession.command.text; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import org.junit.jupiter.api.Test; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayActorSelectionTest { + private static final UUID ACCOUNT_UUID = + PublishedRealmPolicyEvidenceFixture.uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID FIRST_ACTOR_UUID = + PublishedRealmPolicyEvidenceFixture.uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID SECOND_ACTOR_UUID = + PublishedRealmPolicyEvidenceFixture.uuid("99999999-9999-4999-8999-999999999999"); + + @Test + void automaticallySelectsTheOnlyActorAndCarriesItsExactSnapshotBinding() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"))); + var validated = + CanonicalGameplayActorSelection.validate(snapshot, ACCOUNT_UUID, route).orElseThrow(); + + var selection = CanonicalGameplayActorSelection.select(validated, null); + + assertThat(selection) + .isInstanceOfSatisfying( + CanonicalGameplayActorSelection.Selected.class, + selected -> { + assertThat(selected.characterUuid()).isEqualTo(FIRST_ACTOR_UUID); + assertThat(selected.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(selected.rosterSnapshotUuid()).isEqualTo(snapshot.snapshotUuid()); + assertThat(selected.rosterSnapshotDigest()).isEqualTo(snapshot.snapshotDigest()); + assertThat(selected.target()).isEqualTo(snapshot.target()); + assertThat(selected.ordinal()).isEqualTo(1); + }); + } + + @Test + void deniesZeroActorsAndRequiresAnOrdinalForMultipleActors() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var emptySnapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot(route, ACCOUNT_UUID, List.of()); + var emptyRoster = + CanonicalGameplayActorSelection.validate(emptySnapshot, ACCOUNT_UUID, route).orElseThrow(); + assertThat(CanonicalGameplayActorSelection.select(emptyRoster, null)) + .isEqualTo( + new CanonicalGameplayActorSelection.Denied( + CanonicalGameplayActorSelection.Denial.NO_PRESEEDED_ACTOR)); + + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of( + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"), + new CanonicalGameplayRosterClient.RosterActor(SECOND_ACTOR_UUID, "Pilot Two"))); + var roster = + CanonicalGameplayActorSelection.validate(snapshot, ACCOUNT_UUID, route).orElseThrow(); + assertThat(CanonicalGameplayActorSelection.select(roster, null)) + .isEqualTo( + new CanonicalGameplayActorSelection.SelectionRequired( + List.of( + new CanonicalGameplayActorSelection.Choice(1, "Pilot One"), + new CanonicalGameplayActorSelection.Choice(2, "Pilot Two")))); + assertThat(CanonicalGameplayActorSelection.select(roster, "2")) + .isInstanceOfSatisfying( + CanonicalGameplayActorSelection.Selected.class, + selected -> assertThat(selected.characterUuid()).isEqualTo(SECOND_ACTOR_UUID)); + } + + @Test + void rejectsUuidNameAndNonCanonicalOrdinalSelectors() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"))); + var roster = + CanonicalGameplayActorSelection.validate(snapshot, ACCOUNT_UUID, route).orElseThrow(); + + for (String selector : List.of(FIRST_ACTOR_UUID.toString(), "Pilot One", "01", "+1", "2")) { + assertThat(CanonicalGameplayActorSelection.select(roster, selector)) + .isInstanceOf(CanonicalGameplayActorSelection.Denied.class); + } + } + + @Test + void rejectsCrossAccountChangedTargetAndMalformedActors() { + var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var actor = new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, "Pilot One"); + var snapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot(route, ACCOUNT_UUID, List.of(actor)); + + assertThat(CanonicalGameplayActorSelection.validate(snapshot, SECOND_ACTOR_UUID, route)) + .isEmpty(); + + CanonicalGameplayRosterTarget changedTarget = + snapshot.target().toBuilder() + .setPointerVersion(snapshot.target().getPointerVersion() + 1L) + .build(); + var changedSnapshot = + new CanonicalGameplayRosterClient.PreseededRosterSnapshot( + ACCOUNT_UUID, + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + changedTarget, + snapshot.actors()); + assertThat(CanonicalGameplayActorSelection.validate(changedSnapshot, ACCOUNT_UUID, route)) + .isEmpty(); + + var duplicateActorSnapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, ACCOUNT_UUID, List.of(actor, actor)); + assertThat( + CanonicalGameplayActorSelection.validate(duplicateActorSnapshot, ACCOUNT_UUID, route)) + .isEmpty(); + + var malformedNameSnapshot = + PublishedRealmPolicyEvidenceFixture.rosterSnapshot( + route, + ACCOUNT_UUID, + List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR_UUID, " Pilot "))); + assertThat(CanonicalGameplayActorSelection.validate(malformedNameSnapshot, ACCOUNT_UUID, route)) + .isEmpty(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java new file mode 100644 index 0000000000..4bed895cca --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java @@ -0,0 +1,56 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.config.CanonicalGameInstanceLaunchAssociationReadConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameInstanceLaunchAssociationReadService; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; + +class CanonicalGameInstanceLaunchAssociationReadConfigurationTest { + private static final String OWNER_OPT_IN = + "firemud.canonical-game-instance-launch-association-owner-read.enabled"; + + @Test + void defaultConfigurationLeavesCanonicalOwnerReadInactive() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalGameInstanceLaunchAssociationReadConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(CanonicalGameInstanceLaunchAssociationRepository.class); + assertThat(context) + .doesNotHaveBean(CanonicalGameInstanceLaunchAssociationReadService.class); + }); + } + + @Test + void explicitConfigurationCreatesOnlyTheReadOwnerComposition() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(CanonicalGameInstanceLaunchAssociationRepository.class); + assertThat(context) + .hasSingleBean(CanonicalGameInstanceLaunchAssociationReadService.class); + }); + } + + @TestConfiguration(proxyBeanMethods = false) + static class Dependencies { + @Bean + DSLContext dsl() { + return mock(DSLContext.class); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java new file mode 100644 index 0000000000..4fb2cf6dde --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java @@ -0,0 +1,87 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import net.firedevops.firemud.gamesession.config.CanonicalGameInstanceLaunchAssociationReadConfiguration; +import net.firedevops.firemud.gamesession.config.CanonicalInitialAdmissionOwnerConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +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 org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; + +class CanonicalInitialAdmissionOwnerConfigurationTest { + private static final String OWNER_OPT_IN = + "firemud.canonical-game-instance-launch-association-owner-read.enabled"; + + @Test + void disabledOwnerCompositionDoesNotRequireCanonicalLaunchRepositories() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalInitialAdmissionOwnerConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionService.class); + }); + } + + @Test + void enabledOwnerCompositionFailsClosedWithoutItsExplicitLaunchPrerequisite() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalInitialAdmissionOwnerConfiguration.class) + .withPropertyValues(OWNER_OPT_IN + "=true") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void enabledCompositionCreatesOwnerServiceOnlyWithItsExplicitDependencies() { + new ApplicationContextRunner() + .withUserConfiguration( + CanonicalGameInstanceLaunchAssociationReadConfiguration.class, + CanonicalInitialAdmissionOwnerConfiguration.class, + OwnerDependencies.class) + .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionService.class); + }); + } + + @TestConfiguration(proxyBeanMethods = false) + static class OwnerDependencies { + @Bean + DSLContext initialAdmissionDsl() { + return mock(DSLContext.class); + } + + @Bean + GameSessionCanonicalRealmCatalogRepository initialAdmissionCatalogRepository() { + return mock(GameSessionCanonicalRealmCatalogRepository.class); + } + + @Bean + GameSessionCanonicalAdmissionPointerRepository initialAdmissionPointerRepository() { + return mock(GameSessionCanonicalAdmissionPointerRepository.class); + } + + @Bean + GameplayAdmissionPointerEventRepository initialAdmissionEventRepository() { + return mock(GameplayAdmissionPointerEventRepository.class); + } + + @Bean + CanonicalInitialAdmissionWorldVerifier initialAdmissionWorldVerifier() { + return mock(CanonicalInitialAdmissionWorldVerifier.class); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java new file mode 100644 index 0000000000..8435699239 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java @@ -0,0 +1,162 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +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.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +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.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.config.CanonicalPlayerRouteReadConfiguration; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class CanonicalPlayerRouteReadConfigurationTest { + @Test + void defaultConfigurationLeavesCanonicalRosterRouteSourceUnregistered() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + }); + } + + @Test + void explicitlyDisabledConfigurationLeavesCanonicalRosterRouteSourceUnregistered() { + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .withPropertyValues("firemud.canonical-gameplay-roster-owner-read.enabled=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + }); + } + + // Composition proof only: repositories and the channel are controlled doubles; no owner read or + // database read is performed. The client-level test owns RPC identity and deadline proof. + @Test + void enabledConfigurationComposesRealRouteSourcesWithFileBackedTlsAndExactTarget( + @TempDir Path directory) throws IOException { + Path clientCertificate = Files.createFile(directory.resolve("game-session-client.crt")); + Path clientKey = Files.createFile(directory.resolve("game-session-client.key")); + Path serverCa = Files.createFile(directory.resolve("game-design-ca.crt")); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.test:7654"); + var tlsProperties = new CommonGrpcClientProperties(); + tlsProperties.setCertChain(clientCertificate.toString()); + tlsProperties.setPrivateKey(clientKey.toString()); + tlsProperties.setCaCert(serverCa.toString()); + var channelFactory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + anyString(), anyInt(), any(CommonGrpcClientProperties.class), anyBoolean())) + .thenReturn(channel); + + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .withBean(ServiceEndpointsProperties.class, () -> endpoints) + .withBean(CommonGrpcClientProperties.class, () -> tlsProperties) + .withBean(GrpcChannelFactory.class, () -> channelFactory) + .withBean( + GameSessionCanonicalRealmCatalogRepository.class, + () -> mock(GameSessionCanonicalRealmCatalogRepository.class)) + .withBean( + CanonicalInitialAdmissionRepository.class, + () -> mock(CanonicalInitialAdmissionRepository.class)) + .withBean( + CanonicalGameInstanceLaunchAssociationRepository.class, + () -> mock(CanonicalGameInstanceLaunchAssociationRepository.class)) + .withPropertyValues( + "firemud.canonical-gameplay-roster-owner-read.enabled=true", + "firemud.grpc.workload-namespace=games") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).hasSingleBean(CanonicalPlayerRouteReadService.class); + assertThat(context).hasSingleBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat( + Mockito.mockingDetails( + context.getBean(GameDesignPublishedRealmPolicyClient.class)) + .isMock()) + .isFalse(); + assertThat( + Mockito.mockingDetails(context.getBean(CanonicalPlayerRouteReadService.class)) + .isMock()) + .isFalse(); + assertThat( + Mockito.mockingDetails( + context.getBean(CanonicalPublishedPlayerRouteReadService.class)) + .isMock()) + .isFalse(); + verify(channelFactory) + .buildChannel(eq("game-design.test:7654"), eq(6565), eq(tlsProperties), eq(true)); + verifyNoInteractions( + context.getBean(GameSessionCanonicalRealmCatalogRepository.class), + context.getBean(CanonicalInitialAdmissionRepository.class), + context.getBean(CanonicalGameInstanceLaunchAssociationRepository.class)); + }); + } + + @Test + void enabledConfigurationRejectsInvalidNamespaceBeforeOpeningChannel(@TempDir Path directory) + throws IOException { + Path clientCertificate = Files.createFile(directory.resolve("game-session-client.crt")); + Path clientKey = Files.createFile(directory.resolve("game-session-client.key")); + Path serverCa = Files.createFile(directory.resolve("game-design-ca.crt")); + var tlsProperties = new CommonGrpcClientProperties(); + tlsProperties.setCertChain(clientCertificate.toString()); + tlsProperties.setPrivateKey(clientKey.toString()); + tlsProperties.setCaCert(serverCa.toString()); + var channelFactory = mock(GrpcChannelFactory.class); + + new ApplicationContextRunner() + .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) + .withBean(ServiceEndpointsProperties.class, ServiceEndpointsProperties::new) + .withBean(CommonGrpcClientProperties.class, () -> tlsProperties) + .withBean(GrpcChannelFactory.class, () -> channelFactory) + .withBean( + GameSessionCanonicalRealmCatalogRepository.class, + () -> mock(GameSessionCanonicalRealmCatalogRepository.class)) + .withBean( + CanonicalInitialAdmissionRepository.class, + () -> mock(CanonicalInitialAdmissionRepository.class)) + .withBean( + CanonicalGameInstanceLaunchAssociationRepository.class, + () -> mock(CanonicalGameInstanceLaunchAssociationRepository.class)) + .withPropertyValues( + "firemud.canonical-gameplay-roster-owner-read.enabled=true", + "firemud.grpc.workload-namespace=games.invalid") + .run( + context -> { + assertThat(context).hasFailed(); + verifyNoInteractions(channelFactory); + }); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java new file mode 100644 index 0000000000..5308699e5c --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java @@ -0,0 +1,189 @@ +package unit.net.firedevops.firemud.gamesession.dto; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +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.publication.RealmEntryPolicy; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import org.junit.jupiter.api.Test; + +class CanonicalGameInstanceLaunchAssociationTest { + private static final String NAMESPACE = "launch-owner"; + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID INSTANCE_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID ASSOCIATION_ID = + UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID STATE_NAMESPACE_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + + @Test + void retainsTheCompleteBindingAndSeparatesCapturedFromCurrentOwnerProjection() { + CompleteLaunchBindingEvidence evidence = evidence(); + CanonicalGameInstanceLaunchAssociation association = + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING, + 8L); + + assertThat(association.capturedStartingRowVersion()).isEqualTo(3L); + assertThat(association.currentRowVersion()).isEqualTo(8L); + assertThat(association.currentGameInstanceStatus()) + .isEqualTo(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + assertThat(association.launchBindingEvidence()).isSameAs(evidence); + } + + @Test + void rejectsNonSharedAndNonProductionLaunchAssociations() { + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.ISOLATED, true, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("SHARED"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, false, 3L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("public production"); + } + + @Test + void rejectsSelectorsAndCurrentRowVersionsThatDifferFromTheOwnerEvidence() { + assertThatThrownBy( + () -> + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "mars", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence(), + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + assertThatThrownBy( + () -> association(evidence(), RealmEntryPolicy.StateScope.SHARED, true, 4L, 3L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not precede"); + } + + private static CanonicalGameInstanceLaunchAssociation association( + CompleteLaunchBindingEvidence evidence, + RealmEntryPolicy.StateScope scope, + boolean publicProduction, + long capturedVersion, + long currentVersion) { + return new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "earth", + STATE_NAMESPACE_ID, + scope, + publicProduction, + "launch-request-1", + "descriptor-902", + capturedVersion, + evidence, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + currentVersion); + } + + private static CompleteLaunchBindingEvidence evidence() { + UUID sourceOperationId = UUID.fromString("55555555-5555-4555-8555-555555555555"); + String sourceEvidenceDigest = "sha256:" + "a".repeat(64); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "launch-request-1", + TENANT_ID, + "earth", + sourceOperationId, + sourceEvidenceDigest, + 810L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor-902", + 902L, + false, + null, + "{}", + "generation-4", + 4L, + 903L, + "prb:tenant:902:903", + false, + null); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "902", + false, + null, + "publish-commit-902", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence attestation = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + TENANT_ID, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "earth", + sourceOperationId, + sourceEvidenceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + "publish-commit-902", + participants, + "sha256:" + "b".repeat(64), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, attestation); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java index 87790d4fc6..529936b386 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java @@ -1,68 +1,181 @@ -package net.firedevops.firemud.gamesession.dto; +package unit.net.firedevops.firemud.gamesession.dto; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.UUID; +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.service.impl.DefaultDeniedCanonicalInitialAdmissionWorldVerifier; import org.junit.jupiter.api.Test; class CanonicalInitialAdmissionRequestTest { + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID GAME_INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID CANONICAL_VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID HOLD_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID HOLD_FENCE = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + @Test - void initialAdmissionRequestIdMatches128CharacterOwnerAndIntentBounds() { - for (int length : new int[] {120, 121, 128}) { - request("r".repeat(length)); - } + void gameSessionRequestDigestIsBareAndWorldBindingDigestRemainsDistinct() { + CanonicalInitialAdmissionRequest request = noPriorRequest(); + + assertThat(request.requestDigest()).matches("[0-9a-f]{64}").doesNotStartWith("sha256:"); + assertThat(request.holdBindingDigest()).matches("sha256:[0-9a-f]{64}"); + assertThat(request.holdBindingDigest()).isNotEqualTo("sha256:" + request.requestDigest()); + assertThat(request.canonicalVersionId()).isEqualTo(CANONICAL_VERSION); + } - assertThatThrownBy(() -> request("r".repeat(129))) + @Test + void bothOriginsRequireTheirExactPriorPointerShape() { + assertThatThrownBy( + () -> + new CanonicalInitialAdmissionRequest( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.NO_PRIOR_POINTER, + 13L, + "gs-initial-admission-17", + noPriorRequest().requestDigest(), + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("initialAdmissionRequestId must contain 1..128 characters"); + .hasMessageContaining("must not carry"); + + assertThatThrownBy( + () -> + new CanonicalInitialAdmissionRequest( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.EXPECT_CLOSED, + null, + "gs-initial-admission-17", + noPriorRequest().requestDigest(), + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("requires a positive"); } - private static CanonicalInitialAdmissionRequest request(String requestId) { - String targetNamespace = "firemud-prod"; - UUID tenantId = UUID.randomUUID(); - String worldSlug = "world"; - UUID realmId = UUID.randomUUID(); - UUID playableStateNamespaceId = UUID.randomUUID(); - String playableStateScope = "SHARED"; - UUID gameInstanceId = UUID.randomUUID(); - UUID versionId = UUID.randomUUID(); - long lifecycleEpoch = 1L; - long catalogRevision = 1L; - CanonicalInitialAdmissionRequest.OriginKind originKind = - CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER; - String requestDigest = + @Test + void worldProofMustMatchCanonicalVersionOriginCatalogAndHoldBinding() { + CanonicalInitialAdmissionRequest request = noPriorRequest(); + CanonicalInitialAdmissionWorldProof proof = + 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()); + + proof.requireMatches(request); + assertThatThrownBy( + () -> + new CanonicalInitialAdmissionWorldProof( + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.targetNamespace(), + proof.canonicalTenantId(), + proof.worldSlug(), + proof.realmId(), + proof.playableStateNamespaceId(), + proof.playableStateScope(), + proof.canonicalGameInstanceId(), + uuid("66666666-6666-4666-8666-666666666666"), + proof.lifecycleState(), + proof.activeLifecycleEpoch(), + proof.originKind(), + proof.expectedCatalogRevision(), + proof.expectedPriorPointerVersion(), + proof.holdId(), + proof.holdFence(), + proof.holdBindingDigest()) + .requireMatches(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match"); + } + + @Test + void unauthenticatedDefaultWorldVerifierNeverTreatsCallerTupleAsOwnerProof() { + assertThatThrownBy( + () -> + new DefaultDeniedCanonicalInitialAdmissionWorldVerifier().verify(noPriorRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("denied until authenticated World"); + } + + private static CanonicalInitialAdmissionRequest noPriorRequest() { + String requestId = "gs-initial-admission-17"; + String digest = CanonicalInitialAdmissionRequest.computeRequestDigest( - targetNamespace, - tenantId, - worldSlug, - realmId, - playableStateNamespaceId, - playableStateScope, - gameInstanceId, - versionId, - lifecycleEpoch, - catalogRevision, - originKind, + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.NO_PRIOR_POINTER, null, requestId); - return new CanonicalInitialAdmissionRequest( - targetNamespace, - tenantId, - worldSlug, - realmId, - playableStateNamespaceId, - playableStateScope, - gameInstanceId, - versionId, - lifecycleEpoch, - catalogRevision, - originKind, + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.NO_PRIOR_POINTER, null, requestId, - requestDigest, - UUID.randomUUID(), - UUID.randomUUID(), - "sha256:" + "a".repeat(64)); + digest, + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); } } 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 new file mode 100644 index 0000000000..d8e97a1639 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java @@ -0,0 +1,63 @@ +package unit.net.firedevops.firemud.gamesession.repository; + +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.RuntimeTenantIdentityEvidence; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class CanonicalGameInstanceLaunchAssociationRepositoryTest { + private static final String NAMESPACE = "launch-owner"; + + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void captureRequiresAWritableOwnerTransactionBeforeReadingAnyRuntimeRow() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + var tenant = freshTenant(); + + assertThatThrownBy(() -> repository.capture(tenant, 92L, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("writable owner transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void committedReadCannotBeComposedInsideAnotherOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy(() -> repository.read("launch-request-1")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("committed owner read"); + + verifyNoInteractions(dsl); + } + + private static FreshGameSessionTenantAssociation freshTenant() { + RuntimeTenantIdentityEvidence source = + new RuntimeTenantIdentityEvidence( + 1, + NAMESPACE, + UUID.fromString("11111111-1111-4111-8111-111111111111"), + UUID.fromString("22222222-2222-4222-8222-222222222222"), + 1L, + "source-game-tenant-key", + "NEW_GAME_ROW"); + return new FreshGameSessionTenantAssociation( + UUID.fromString("33333333-3333-4333-8333-333333333333"), 701L, source); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java new file mode 100644 index 0000000000..ca61e68055 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.junit.jupiter.api.Test; + +class GameSessionAuthoredWorldIntakeDigestTest { + private static final UUID REQUEST = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID OPERATION = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String SOURCE_GAME_TENANT_KEY = "source-22222222"; + private static final String SOURCE_PROVENANCE_KIND = "NEW_GAME_ROW"; + + @Test + void emitsFixedVectorsBindingTheCompleteMultibyteOwnerReceipt() { + var source = source("Café 🐉"); + String request = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); + assertThat(source.evidenceDigest()) + .isEqualTo("sha256:ea835c1f4fbae6206a7f870f509bbdc6b767415608f7be56a44dcd061f1116f7"); + assertThat(request) + .isEqualTo("sha256:7b9ee59edffc076f301c1a47e73e45417dfdff99f2916e6043faa68bbb5aca28"); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, source.evidenceDigest())) + .isEqualTo("sha256:4d1afd818098152d268f33d0ba7467bd1c0963700fa05ec170b1181100de93e9"); + } + + @Test + void changedRequestSourceOrOperationCannotReplayTheSameLocalReceipt() { + var source = source("Café 🐉"); + var changedSource = source("Café 🐲"); + String request = GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, source); + String receipt = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, source.evidenceDigest()); + assertThat(GameSessionAuthoredWorldIntakeDigest.requestDigest(OPERATION, source)) + .isNotEqualTo(request); + assertThat(GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, changedSource)) + .isNotEqualTo(request); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + REQUEST, request, source.evidenceDigest())) + .isNotEqualTo(receipt); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, + GameSessionAuthoredWorldIntakeDigest.requestDigest(OPERATION, source), + source.evidenceDigest())) + .isNotEqualTo(receipt); + assertThat( + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, request, changedSource.evidenceDigest())) + .isNotEqualTo(receipt); + } + + @Test + void rejectsMissingNilOrMalformedOperationAndDigestInputs() { + assertThatThrownBy(() -> GameSessionAuthoredWorldIntakeDigest.requestDigest(null, source("x"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameSessionAuthoredWorldIntakeDigest.requestDigest(new UUID(0, 0), source("x"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + new UUID(0, 0), source("x").requestDigest(), source("x").evidenceDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> GameSessionAuthoredWorldIntakeDigest.receiptDigest(OPERATION, null, "sha256:x")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, source("x").requestDigest(), "SHA256:" + "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AuthoredWorldSourceEvidence source(String displayName) { + var registration = UUID.fromString("11111111-1111-4111-8111-111111111111"); + var tenant = UUID.fromString("22222222-2222-4222-8222-222222222222"); + var operation = UUID.fromString("33333333-3333-4333-8333-333333333333"); + String request = + AuthoredWorldSourceDigest.requestDigest( + "firemud", registration, tenant, "north-star", "violet-wilds", displayName); + String evidence = + AuthoredWorldSourceDigest.evidenceDigest( + "firemud", + registration, + operation, + request, + tenant, + "north-star", + "violet-wilds", + displayName, + 42L, + SOURCE_GAME_TENANT_KEY, + SOURCE_PROVENANCE_KIND); + return new AuthoredWorldSourceEvidence( + 1, + "firemud", + registration, + operation, + request, + tenant, + "north-star", + "violet-wilds", + displayName, + 42L, + SOURCE_GAME_TENANT_KEY, + SOURCE_PROVENANCE_KIND, + evidence); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..e501ca164b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java @@ -0,0 +1,232 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalClosedAdmissionPointerRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalAdmissionPointerRepositoryTest { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String TARGET_NAMESPACE = "canonical-closed-pointer-test"; + + @Test + void requestAndReceiptDigestsMatchFixedOrderUtf8GoldenVectors() { + CreateCanonicalClosedAdmissionPointerRequest request = request("Café 🐉", "close 東京"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + + assertThat(requestDigest) + .isEqualTo("sha256:0dc3926970e3d5be36349ff3fe259869fed779f3429b767e2e20ece407313d24"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.requestDigest( + request("Café 🐲", "close 東京"), catalog)) + .isNotEqualTo(requestDigest); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 123L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + assertThat( + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, + catalog, + requestDigest, + 124L, + Instant.parse("2026-10-03T00:00:00.123456Z"))) + .isNotEqualTo("sha256:5d465f6eec3f08d0de06c5562ba60d2bd44d335c41f82355c4adc158d5806286"); + } + + @Test + void requestRejectsNilIdentityAndNonCanonicalTargetNamespace() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + NIL_UUID, TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("non-nil UUID"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), "Canonical_Closed", uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical DNS label"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 0L, "actor", "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("catalogRevision must be positive"); + } + + @Test + void requestRejectsMalformedOrUnboundedAuditText() { + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), + TARGET_NAMESPACE, + uuid(2), + uuid(3), + uuid(4), + 1L, + "bad" + (char) 0xD800, + "reason")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy( + () -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", " ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("bounded and nonblank"); + } + + @Test + void expectedClosedVersionCheckRequiresTheExactInitialPointerAndCatalogTuple() { + CreateCanonicalClosedAdmissionPointerRequest request = request("origin actor", "origin reason"); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + String requestDigest = + GameSessionCanonicalAdmissionPointerRepository.requestDigest(request, catalog); + Instant updatedAt = Instant.parse("2026-10-03T00:00:00.123456Z"); + CanonicalClosedAdmissionPointerSnapshot origin = + new CanonicalClosedAdmissionPointerSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId(), + catalog.worldSlug(), + catalog.realmSlug(), + 1L, + catalog.catalogRevision(), + "CLOSED", + null, + request.requestId(), + requestDigest, + GameSessionCanonicalAdmissionPointerRepository.receiptDigest( + request, catalog, requestDigest, 123L, updatedAt), + request.actorPrincipal(), + request.reason(), + 123L, + updatedAt, + catalog); + + assertThatCode( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 1L)) + .doesNotThrowAnyException(); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 2L, 1L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + assertThatThrownBy( + () -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( + origin, 1L, 2L)) + .isInstanceOf( + GameSessionCanonicalAdmissionPointerRepository + .InvalidCanonicalClosedPointerEvidenceException.class) + .hasMessageContaining("versions do not match"); + } + + private static CreateCanonicalClosedAdmissionPointerRequest request( + String actorPrincipal, String reason) { + return new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, actorPrincipal, reason); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot() { + UUID tenantId = uuid(2); + UUID registrationRequestId = uuid(10); + UUID sourceOperationId = uuid(11); + String tenantSlug = "unit-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceGameTenantKey = "gds-unit-tenant"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + TARGET_NAMESPACE, + registrationRequestId, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + TARGET_NAMESPACE, + registrationRequestId, + sourceOperationId, + sourceRequestDigest, + tenantId, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceGameTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + UUID intakeRequestId = uuid(12); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + IntakeReceipt sourceReceipt = + new IntakeReceipt( + uuid(13), + intakeRequestId, + intakeRequestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + uuid(13), intakeRequestDigest, source.evidenceDigest())); + return new CanonicalRealmCatalogSnapshot( + TARGET_NAMESPACE, + tenantId, + tenantSlug, + worldSlug, + uuid(3), + "Arcology", + "Public Realm", + true, + true, + "SHARED", + uuid(14), + "owner-policy-v1", + 1L, + uuid(4), + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + sourceReceipt); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} 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 new file mode 100644 index 0000000000..b3418aceca --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -0,0 +1,222 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.junit.jupiter.api.Test; + +class GameSessionCanonicalRealmCatalogRepositoryTest { + private static final String NAMESPACE = "canonical-realm-catalog-test"; + private static final UUID TENANT_ID = uuid(1); + private static final UUID INTAKE_OPERATION_ID = uuid(2); + private static final UUID INTAKE_REQUEST_ID = uuid(3); + private static final UUID CREATE_REQUEST_ID = uuid(4); + + @Test + void explicitPublicRequestPreservesRealmSelectorAndOpaqueOwnerPolicyExactly() { + CreateCanonicalRealmCatalogRequest request = + request(" Production Realm/West ", "Café 🐉", "realm-local-characters-v7"); + + assertThat(request.realmSlug()).isEqualTo(" Production Realm/West "); + assertThat(request.characterCreationPolicy()).isEqualTo("realm-local-characters-v7"); + assertThat(request.visible()).isTrue(); + assertThat(request.publicProduction()).isTrue(); + assertThat(request.stateScope()).isEqualTo("SHARED"); + } + + @Test + void rejectsMissingPublicStatePrivateLifecycleAndMalformedUtf8Inputs() { + assertThatThrownBy(() -> request("realm", "Display", "policy", false, true, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, false, "SHARED")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("visible public production"); + assertThatThrownBy(() -> request("realm", "Display", "policy", true, true, "PRIVATE")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stateScope"); + assertThatThrownBy( + () -> + new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + "realm", + "Display", + true, + true, + "SHARED", + "policy", + uuid(5), + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("private/playtest"); + String malformedUtf8 = "bad" + (char) 0xD800; + assertThatThrownBy(() -> request(malformedUtf8, "Display", "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", malformedUtf8, "policy")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + assertThatThrownBy(() -> request("realm", "Display", malformedUtf8)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("well-formed UTF-8"); + } + + @Test + void requestDigestIsStableAndBindsEachCreationInputAndExactSourceReceipt() { + IntakeReceipt source = sourceReceipt(); + CreateCanonicalRealmCatalogRequest original = request("Arcology", "The City", "owner-mode"); + String digest = GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source); + + assertThat(GameSessionCanonicalRealmCatalogRepository.requestDigest(original, source)) + .isEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("arcology", "The City", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "Another Display", "owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "owner-mode", true, true, "ISOLATED"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "another-owner-mode"), source)) + .isNotEqualTo(digest); + assertThat( + GameSessionCanonicalRealmCatalogRepository.requestDigest( + request("Arcology", "The City", "owner-mode", uuid(6)), source)) + .isNotEqualTo(digest); + } + + @Test + void snapshotRejectsTenantAndWorldSelectorsThatDifferFromPersistedSource() { + IntakeReceipt source = sourceReceipt(); + assertThatThrownBy( + () -> + new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT_ID, + "different-tenant", + "authored-world", + uuid(7), + "realm", + "Realm", + true, + true, + "SHARED", + uuid(8), + "policy", + 1, + CREATE_REQUEST_ID, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + source)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("do not match"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy) { + return request(realmSlug, display, policy, true, true, "SHARED"); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, + String display, + String policy, + boolean visible, + boolean production, + String scope) { + return new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + visible, + production, + scope, + policy, + null, + null); + } + + private static CreateCanonicalRealmCatalogRequest request( + String realmSlug, String display, String policy, UUID requestId) { + return new CreateCanonicalRealmCatalogRequest( + requestId, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + realmSlug, + display, + true, + true, + "SHARED", + policy, + null, + null); + } + + private static IntakeReceipt sourceReceipt() { + String tenantSlug = "stable-tenant"; + String worldSlug = "authored-world"; + String worldDisplayName = "Authored World"; + String sourceTenantKey = "game-design-tenant-42"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, uuid(10), TENANT_ID, tenantSlug, worldSlug, worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + uuid(10), + uuid(11), + sourceRequestDigest, + TENANT_ID, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST_ID, source); + String intakeReceiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + INTAKE_OPERATION_ID, intakeRequestDigest, source.evidenceDigest()); + return new IntakeReceipt( + INTAKE_OPERATION_ID, INTAKE_REQUEST_ID, intakeRequestDigest, source, intakeReceiptDigest); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index 8ddcdfdd87..4899ccb889 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -2,6 +2,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; import java.sql.Connection; import java.sql.DriverManager; @@ -9,6 +12,9 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import org.jooq.DSLContext; @@ -17,6 +23,26 @@ import org.junit.jupiter.api.Test; class GameplayAdmissionPointerEventRepositoryTest { + @Test + void canonicalOpenAuditCannotBeWrittenOutsideItsWritableOwnerTransaction() { + DSLContext dsl = mock(DSLContext.class); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + assertThrows( + IllegalStateException.class, + () -> + repository.appendCanonicalInitialAdmissionOpen( + mock(CanonicalInitialAdmissionRequest.class), + mock(CanonicalRealmCatalogSnapshot.class), + mock(CanonicalInitialAdmissionLaunchTarget.class), + 1L, + 1L, + Instant.EPOCH)); + + verifyNoInteractions(dsl); + } + @Test void savesCatalogRevisionAndStableIdentityAndKeepsUnknownValuesNull() throws Exception { try (Connection connection = 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 new file mode 100644 index 0000000000..d7752e1908 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java @@ -0,0 +1,315 @@ +package unit.net.firedevops.firemud.gamesession.security; + +import static org.assertj.core.api.Assertions.assertThat; +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.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayInputStream; +import java.nio.file.Path; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Comparator; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.FileSystemResource; + +/** + * Exercises the configured JWT and TLS-peer gRPC interceptors around the Entity-only owner read. + */ +class CanonicalGameplayRosterOwnerReadInterceptorChainTest { + private static final String NAMESPACE = "gameplay"; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final String METHOD = + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetCanonicalGameplayRosterOwnerReadMethod() + .getFullMethodName(); + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void exactEntityCertificatePassesJwtBypassAndAbsentSourceRemainsUnavailable() { + var provider = sourceReaderProvider(); + var response = new CapturingObserver(); + + invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter(provider), request(), response); + + assertThat(response.errorWasStatusRuntimeException).isTrue(); + assertThat(response.errorCode).isEqualTo(Status.Code.UNAVAILABLE); + verify(provider).getIfAvailable(); + } + + @Test + void absentWrongServiceCrossNamespaceAndPlayerCallerContextAreDenied() { + var provider = sourceReaderProvider(); + var adapter = adapter(provider); + + var absent = new CapturingObserver(); + invokeThroughConfiguredChain(null, adapter, request(), absent); + assertPermissionDenied(absent); + + var wrongService = new CapturingObserver(); + invokeThroughConfiguredChain( + peerIdentity(NAMESPACE, "game-session-service"), adapter, request(), wrongService); + assertPermissionDenied(wrongService); + + var otherNamespace = new CapturingObserver(); + invokeThroughConfiguredChain(entityIdentity("other"), adapter, request(), otherNamespace); + assertPermissionDenied(otherNamespace); + + SessionContext.setContext(ACCOUNT.toString(), List.of("player"), java.util.Map.of()); + var callerContext = new CapturingObserver(); + invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter, request(), callerContext); + assertPermissionDenied(callerContext); + + verifyNoInteractions(provider); + } + + private static ObjectProvider sourceReaderProvider() { + @SuppressWarnings("unchecked") + ObjectProvider provider = mock(ObjectProvider.class); + when(provider.getIfAvailable()).thenReturn(null); + return provider; + } + + private static CanonicalGameplayRosterOwnerReadGrpcAdapter adapter( + ObjectProvider provider) { + return new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + } + + private static AuthTokenInterceptor configuredAuthInterceptor() { + Properties properties = applicationProperties(); + List configured = publicMethods(properties); + assertThat(configured) + .containsExactly( + "game_session.v1.GameSessionService/Ping", + "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", + "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", + "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof", + METHOD, + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead") + .doesNotContain("game_session.v1.*"); + Set publicMethods = Set.copyOf(configured); + return new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), publicMethods); + } + + private static List publicMethods(Properties properties) { + List indexes = + properties.stringPropertyNames().stream() + .filter(name -> name.startsWith("firemud.auth.grpc.public-methods[")) + .map(name -> name.substring(name.indexOf('[') + 1, name.indexOf(']'))) + .map(Integer::parseInt) + .sorted(Comparator.naturalOrder()) + .toList(); + return indexes.stream() + .map(index -> properties.getProperty("firemud.auth.grpc.public-methods[" + index + "]")) + .toList(); + } + + private static Properties applicationProperties() { + var yaml = new YamlPropertiesFactoryBean(); + yaml.setResources(new FileSystemResource(Path.of("src/main/resources/application.yml"))); + Properties properties = yaml.getObject(); + if (properties == null) { + throw new IllegalStateException("Game Session application properties are unavailable"); + } + return properties; + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetCanonicalGameplayRosterOwnerReadRequest request, + CapturingObserver response) { + ServerCall call = new TestServerCall(METHOD, sslSession(peerUri)); + Metadata headers = new Metadata(); + ServerInterceptor peer = new GrpcPeerIdentityInterceptor(); + ServerCallHandler handler = + (nextCall, ignoredHeaders) -> { + adapter.getCanonicalGameplayRosterOwnerRead(request, response); + return new ServerCall.Listener<>() {}; + }; + configuredAuthInterceptor() + .interceptCall( + call, + headers, + (authCall, authHeaders) -> peer.interceptCall(authCall, authHeaders, handler)); + } + + private static GetCanonicalGameplayRosterOwnerReadRequest request() { + return GetCanonicalGameplayRosterOwnerReadRequest.newBuilder() + .setSchemaVersion(1) + .setRequestUuid(uuid("66666666-6666-4666-8666-666666666666").toString()) + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantUuid(TENANT.toString()) + .setWorldSlug("earth") + .setRealmUuid(REALM.toString()) + .setRealmSlug("main") + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceUuid(INSTANCE.toString()) + .setCanonicalVersionUuid(VERSION.toString()) + .setExpectedCatalogRevision(71L) + .setExpectedPointerVersion(73L) + .setExpectedActiveWorldEpoch(82L) + .build(); + } + + private static String entityIdentity(String namespace) { + return peerIdentity(namespace, ENTITY_SERVICE); + } + + private static String peerIdentity(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static SSLSession sslSession(String peerUri) { + SSLSession session = mock(SSLSession.class); + if (peerUri == null) { + try { + when(session.getPeerCertificates()) + .thenThrow(new javax.net.ssl.SSLPeerUnverifiedException("No peer certificate")); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + X509Certificate certificate = mock(X509Certificate.class); + try { + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peerUri))); + } catch (java.security.cert.CertificateParsingException impossible) { + throw new IllegalStateException(impossible); + } + try { + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + + private static void assertPermissionDenied(CapturingObserver observer) { + assertThat(observer.errorWasStatusRuntimeException).isTrue(); + assertThat(observer.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class CapturingObserver + implements StreamObserver { + private boolean errorWasStatusRuntimeException; + private Status.Code errorCode; + + @Override + public void onNext(GetCanonicalGameplayRosterOwnerReadResponse response) {} + + @Override + public void onError(Throwable throwable) { + errorWasStatusRuntimeException = throwable instanceof StatusRuntimeException; + errorCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final class TestServerCall extends ServerCall { + private static final MethodDescriptor.Marshaller NOOP_MARSHALLER = + new MethodDescriptor.Marshaller<>() { + @Override + public java.io.InputStream stream(Object value) { + return new ByteArrayInputStream(new byte[0]); + } + + @Override + public Object parse(java.io.InputStream stream) { + return new Object(); + } + }; + + private final String fullMethodName; + private final Attributes attributes; + + private TestServerCall(String fullMethodName, SSLSession peerSession) { + this.fullMethodName = fullMethodName; + this.attributes = + peerSession == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, peerSession).build(); + } + + @Override + public void request(int numMessages) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(Object message) {} + + @Override + public void close(Status status, Metadata trailers) {} + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(NOOP_MARSHALLER) + .setResponseMarshaller(NOOP_MARSHALLER) + .build(); + } + } +} 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 new file mode 100644 index 0000000000..0628659fb2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java @@ -0,0 +1,321 @@ +package unit.net.firedevops.firemud.gamesession.security; + +import static org.assertj.core.api.Assertions.assertThat; +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.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayInputStream; +import java.nio.file.Path; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Comparator; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadGrpcCodec; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetPreseededActorAssignmentOwnerReadResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.FileSystemResource; + +/** Exercises the exact Entity-only assignment method through the configured JWT and TLS guards. */ +class PreseededActorAssignmentOwnerReadInterceptorChainTest { + private static final String NAMESPACE = "gameplay"; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final String METHOD = + CanonicalGameplayRosterOwnerReadServiceGrpc.getGetPreseededActorAssignmentOwnerReadMethod() + .getFullMethodName(); + private static final UUID ASSIGNMENT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID ACCOUNT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID TENANT = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID REALM = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID PLAYABLE_NAMESPACE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID INSTANCE = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID VERSION = uuid("66666666-6666-4666-8666-666666666666"); + + @AfterEach + void clearCallerContext() { + SessionContext.clear(); + } + + @Test + void exactEntityCertificatePassesExactJwtBypassAndReachesOwnerSource() { + var provider = sourceReaderProvider(); + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + var typedRequest = PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(request()); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrentForAssignment(typedRequest)) + .thenThrow( + new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "source unavailable")); + var response = new CapturingObserver(); + + invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter(provider), request(), response); + + assertThat(response.errorWasStatusRuntimeException).isTrue(); + assertThat(response.errorCode).isEqualTo(Status.Code.UNAVAILABLE); + verify(provider).getIfAvailable(); + verify(source).readCurrentForAssignment(typedRequest); + } + + @Test + void absentWrongServiceCrossNamespaceAndCallerContextAreDeniedBeforeSourceRead() { + var provider = sourceReaderProvider(); + var adapter = adapter(provider); + + var absentCertificate = new CapturingObserver(); + invokeThroughConfiguredChain(null, adapter, request(), absentCertificate); + assertPermissionDenied(absentCertificate); + + var wrongService = new CapturingObserver(); + invokeThroughConfiguredChain( + peerIdentity(NAMESPACE, "game-session-service"), adapter, request(), wrongService); + assertPermissionDenied(wrongService); + + var otherNamespace = new CapturingObserver(); + invokeThroughConfiguredChain(entityIdentity("other"), adapter, request(), otherNamespace); + assertPermissionDenied(otherNamespace); + + SessionContext.setContext(ACCOUNT.toString(), List.of("player"), java.util.Map.of()); + var callerContext = new CapturingObserver(); + invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter, request(), callerContext); + assertPermissionDenied(callerContext); + + verifyNoInteractions(provider); + } + + private static ObjectProvider sourceReaderProvider() { + @SuppressWarnings("unchecked") + ObjectProvider provider = mock(ObjectProvider.class); + return provider; + } + + private static CanonicalGameplayRosterOwnerReadGrpcAdapter adapter( + ObjectProvider provider) { + return new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + } + + private static AuthTokenInterceptor configuredAuthInterceptor() { + List configured = publicMethods(applicationProperties()); + assertThat(configured) + .containsExactly( + "game_session.v1.GameSessionService/Ping", + "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", + "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", + "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", + "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof", + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", + METHOD) + .doesNotContain("game_session.v1.*"); + Set publicMethods = Set.copyOf(configured); + return new AuthTokenInterceptor( + new JwtUtil("testsecretkeytestsecretkeytest1234", 60_000L), publicMethods); + } + + private static List publicMethods(Properties properties) { + List indexes = + properties.stringPropertyNames().stream() + .filter(name -> name.startsWith("firemud.auth.grpc.public-methods[")) + .map(name -> name.substring(name.indexOf('[') + 1, name.indexOf(']'))) + .map(Integer::parseInt) + .sorted(Comparator.naturalOrder()) + .toList(); + return indexes.stream() + .map(index -> properties.getProperty("firemud.auth.grpc.public-methods[" + index + "]")) + .toList(); + } + + private static Properties applicationProperties() { + var yaml = new YamlPropertiesFactoryBean(); + yaml.setResources(new FileSystemResource(Path.of("src/main/resources/application.yml"))); + Properties properties = yaml.getObject(); + if (properties == null) { + throw new IllegalStateException("Game Session application properties are unavailable"); + } + return properties; + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetPreseededActorAssignmentOwnerReadRequest request, + CapturingObserver response) { + ServerCall call = new TestServerCall(METHOD, sslSession(peerUri)); + Metadata headers = new Metadata(); + ServerInterceptor peer = new GrpcPeerIdentityInterceptor(); + ServerCallHandler handler = + (nextCall, ignoredHeaders) -> { + adapter.getPreseededActorAssignmentOwnerRead(request, response); + return new ServerCall.Listener<>() {}; + }; + configuredAuthInterceptor() + .interceptCall( + call, + headers, + (authCall, authHeaders) -> peer.interceptCall(authCall, authHeaders, handler)); + } + + private static GetPreseededActorAssignmentOwnerReadRequest request() { + return GetPreseededActorAssignmentOwnerReadRequest.newBuilder() + .setSchemaVersion(1) + .setAssignmentUuid(ASSIGNMENT.toString()) + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantUuid(TENANT.toString()) + .setWorldSlug("earth") + .setRealmUuid(REALM.toString()) + .setRealmSlug("main") + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceUuid(INSTANCE.toString()) + .setCanonicalVersionUuid(VERSION.toString()) + .setExpectedCatalogRevision(71L) + .setExpectedPolicyDigest("a".repeat(64)) + .setExpectedPublishedReleaseBundleRef("release:fixture") + .build(); + } + + private static String entityIdentity(String namespace) { + return peerIdentity(namespace, ENTITY_SERVICE); + } + + private static String peerIdentity(String namespace, String service) { + return "spiffe://firemud/ns/" + namespace + "/sa/" + service; + } + + private static SSLSession sslSession(String peerUri) { + SSLSession session = mock(SSLSession.class); + if (peerUri == null) { + try { + when(session.getPeerCertificates()) + .thenThrow(new javax.net.ssl.SSLPeerUnverifiedException("No peer certificate")); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + X509Certificate certificate = mock(X509Certificate.class); + try { + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peerUri))); + } catch (java.security.cert.CertificateParsingException impossible) { + throw new IllegalStateException(impossible); + } + try { + when(session.getPeerCertificates()).thenReturn(new Certificate[] {certificate}); + } catch (javax.net.ssl.SSLPeerUnverifiedException impossible) { + throw new IllegalStateException(impossible); + } + return session; + } + + private static void assertPermissionDenied(CapturingObserver observer) { + assertThat(observer.errorWasStatusRuntimeException).isTrue(); + assertThat(observer.errorCode).isEqualTo(Status.Code.PERMISSION_DENIED); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private static final class CapturingObserver + implements StreamObserver { + private boolean errorWasStatusRuntimeException; + private Status.Code errorCode; + + @Override + public void onNext(GetPreseededActorAssignmentOwnerReadResponse response) {} + + @Override + public void onError(Throwable throwable) { + errorWasStatusRuntimeException = throwable instanceof StatusRuntimeException; + errorCode = Status.fromThrowable(throwable).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static final class TestServerCall extends ServerCall { + private static final MethodDescriptor.Marshaller NOOP_MARSHALLER = + new MethodDescriptor.Marshaller<>() { + @Override + public java.io.InputStream stream(Object value) { + return new ByteArrayInputStream(new byte[0]); + } + + @Override + public Object parse(java.io.InputStream stream) { + return new Object(); + } + }; + + private final String fullMethodName; + private final Attributes attributes; + + private TestServerCall(String fullMethodName, SSLSession peerSession) { + this.fullMethodName = fullMethodName; + this.attributes = + peerSession == null + ? Attributes.EMPTY + : Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, peerSession).build(); + } + + @Override + public void request(int numMessages) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(Object message) {} + + @Override + public void close(Status status, Metadata trailers) {} + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(NOOP_MARSHALLER) + .setResponseMarshaller(NOOP_MARSHALLER) + .build(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java new file mode 100644 index 0000000000..af71e0cfaf --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java @@ -0,0 +1,478 @@ +package unit.net.firedevops.firemud.gamesession.service; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +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.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldIntakeDigest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import org.junit.jupiter.api.Test; + +class CanonicalPlayerRouteReadServiceTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final String REQUEST_ID = "first-open-operation-17"; + + @Test + void composesCanonicalCatalogCurrentOpenProofAndOwnerQualifiedRuntimeReadOnly() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + CanonicalInitialAdmissionOwnerProof proof = committedProof(7L); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget(); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalog)); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(proof)); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + + CanonicalPlayableTarget target = service.readVisiblePublicProductionTargets().getFirst(); + + assertThat(target.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(target.canonicalTenantId()).isEqualTo(TENANT); + assertThat(target.realmId()).isEqualTo(REALM); + assertThat(target.playableStateNamespaceId()).isEqualTo(PLAYABLE_NAMESPACE); + assertThat(target.canonicalGameInstanceId()).isEqualTo(INSTANCE); + assertThat(target.canonicalVersionId()).isEqualTo(VERSION); + assertThat(target.runtimeVersionId()).isEqualTo(303L); + assertThat(target.catalogRevision()).isEqualTo(1L); + assertThat(target.pointerVersion()).isEqualTo(7L); + assertThat(target.admissionPointerSnapshotDigest()).isEqualTo("d".repeat(64)); + assertThat(target.activeWorldEpoch()).isEqualTo(82L); + assertThat(target.initialAdmissionRequestId()).isEqualTo(REQUEST_ID); + assertThat(target.initialAdmissionRequestDigest()).isEqualTo("a".repeat(64)); + assertThat(target.initialAdmissionOriginKind()).isEqualTo(OriginKind.NO_PRIOR_POINTER); + assertThat(target.expectedPriorPointerVersion()).isNull(); + assertThat(target.holdId()).isEqualTo(uuid("77777777-7777-4777-8777-777777777777")); + assertThat(target.holdFence()).isEqualTo(uuid("88888888-8888-4888-8888-888888888888")); + assertThat(target.holdBindingDigest()).isEqualTo("sha256:" + "c".repeat(64)); + assertThat(target.auditEventId()).isEqualTo(27L); + assertThat(target.ownerProofDigest()).isEqualTo("sha256:" + "f".repeat(64)); + assertThat(target.ownerProofOutcome()) + .isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + assertThat(target.positiveDurableAbort()).isFalse(); + assertThat(target.ownerProofTerminalAt()).isEqualTo(Instant.parse("2026-10-07T00:00:00Z")); + assertThat(target.gameSessionTenantId()).isEqualTo(101L); + assertThat(target.gameInstanceId()).isEqualTo(202L); + + assertThat(service.matchesCurrentTarget(target)).isTrue(); + verify(catalogRepository).readVisiblePublicProductionSnapshots(NAMESPACE); + verify(catalogRepository).readUniqueVisiblePublicProduction(NAMESPACE, TENANT); + verify(admissionRepository, times(2)).readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM); + verify(launchRepository, times(2)).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + verifyNoMoreInteractions(catalogRepository, admissionRepository, launchRepository); + } + + @Test + void readsCurrentTargetByCanonicalTenantSelectorWithoutCallerCounters() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var catalog = catalogSnapshot(); + var proof = committedProof(7L); + var launch = launchTarget(); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(proof)); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + CanonicalPlayableTarget current = service.readCurrentTarget(TENANT); + + assertThat(current.canonicalTenantId()).isEqualTo(TENANT); + assertThat(current.canonicalGameInstanceId()).isEqualTo(INSTANCE); + assertThat(current.canonicalVersionId()).isEqualTo(VERSION); + assertThat(current.catalogRevision()).isEqualTo(1L); + assertThat(current.pointerVersion()).isEqualTo(7L); + verify(catalogRepository).readUniqueVisiblePublicProduction(NAMESPACE, TENANT); + verify(admissionRepository).readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM); + verify(launchRepository).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + verifyNoMoreInteractions(catalogRepository, admissionRepository, launchRepository); + } + + @Test + void changedCurrentPointerFenceDoesNotMatchPreviouslyDiscoveredTarget() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalog)); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn( + currentOpenSnapshot(committedProof(7L), "d".repeat(64)), + currentOpenSnapshot(committedProof(8L), "e".repeat(64))); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget(); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + CanonicalPlayableTarget discovered = service.readVisiblePublicProductionTargets().getFirst(); + + assertThat(service.matchesCurrentTarget(discovered)).isFalse(); + } + + @Test + void changedPointerSnapshotDigestDoesNotMatchPreviouslyDiscoveredTarget() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalRealmCatalogSnapshot catalog = catalogSnapshot(); + CanonicalInitialAdmissionOwnerProof proof = committedProof(7L); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalog)); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn( + currentOpenSnapshot(proof, "d".repeat(64)), currentOpenSnapshot(proof, "e".repeat(64))); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget(); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + CanonicalPlayableTarget discovered = service.readVisiblePublicProductionTargets().getFirst(); + + assertThat(service.matchesCurrentTarget(discovered)).isFalse(); + } + + @Test + void missingCurrentOpenOwnerProofFailsWithoutReadingLaunchAssociation() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenThrow(new IllegalStateException("No current OPEN owner proof")); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void abortedCurrentOwnerProofFailsWithoutReadingLaunchAssociation() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenThrow(new IllegalStateException("Current OPEN pointer has no committed proof")); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void proofNamespaceMustMatchConfiguredOwnerNamespace() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L, "another-owner", 1L))); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void catalogNamespaceMustMatchConfiguredOwnerNamespace() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot("another-owner", 1L))); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void catalogRevisionMustMatchCommittedOwnerProof() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L, NAMESPACE, 2L))); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + verify(launchRepository, never()).readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE); + } + + @Test + void launchAssociationMustMatchCanonicalTenantAndRealmTarget() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + CanonicalInitialAdmissionLaunchTarget launch = + launchTarget(NAMESPACE, uuid("99999999-9999-4999-8999-999999999999"), VERSION); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + } + + @Test + void launchAssociationNamespaceMustMatchConfiguredOwnerNamespace() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + CanonicalInitialAdmissionLaunchTarget launch = launchTarget("another-owner", TENANT, VERSION); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + } + + @Test + void launchVersionMustMatchCommittedOwnerProof() { + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) + .thenReturn(List.of(catalogSnapshot())); + when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(currentOpenSnapshot(committedProof(7L))); + CanonicalInitialAdmissionLaunchTarget launch = + launchTarget(NAMESPACE, TENANT, uuid("99999999-9999-4999-8999-999999999999")); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = routeReadService(catalogRepository, admissionRepository, launchRepository); + + assertThatThrownBy(service::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.InvalidAuthorityException.class); + } + + @Test + void unavailableOwnerSourceFailsClosed() { + assertThatThrownBy( + CanonicalPlayerRouteReadService.unavailable()::readVisiblePublicProductionTargets) + .isInstanceOf(CanonicalPlayerRouteReadService.ReadUnavailableException.class); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot() { + return catalogSnapshot(NAMESPACE, 1L); + } + + private static CanonicalRealmCatalogSnapshot catalogSnapshot( + String targetNamespace, long catalogRevision) { + IntakeReceipt receipt = sourceReceipt(targetNamespace); + return new CanonicalRealmCatalogSnapshot( + targetNamespace, + TENANT, + "demo-tenant", + "demo-world", + REALM, + "production", + "Production Realm", + true, + true, + "SHARED", + PLAYABLE_NAMESPACE, + "ALLOW_NEW", + catalogRevision, + uuid("66666666-6666-4666-8666-666666666666"), + "a".repeat(64), + "sha256:" + "b".repeat(64), + receipt); + } + + private static CanonicalInitialAdmissionOwnerProof committedProof(long pointerVersion) { + return committedProof(pointerVersion, NAMESPACE, 1L); + } + + private static CanonicalInitialAdmissionOwnerProof committedProof( + long pointerVersion, String targetNamespace, long catalogRevision) { + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + REQUEST_ID, + "a".repeat(64), + targetNamespace, + TENANT, + "demo-world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + catalogRevision, + OriginKind.NO_PRIOR_POINTER, + null, + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + "sha256:" + "c".repeat(64), + pointerVersion, + 27L, + "sha256:" + "f".repeat(64), + false, + Instant.parse("2026-10-07T00:00:00Z")); + } + + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentOpenSnapshot( + CanonicalInitialAdmissionOwnerProof proof) { + return currentOpenSnapshot(proof, "d".repeat(64)); + } + + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentOpenSnapshot( + CanonicalInitialAdmissionOwnerProof proof, String digest) { + return new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, digest); + } + + private static CanonicalPlayerRouteReadService routeReadService( + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalInitialAdmissionRepository admissionRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository) { + return new CanonicalPlayerRouteReadService( + NAMESPACE, catalogRepository, admissionRepository, launchRepository); + } + + private static CanonicalInitialAdmissionLaunchTarget launchTarget() { + return launchTarget(NAMESPACE, TENANT, VERSION); + } + + private static CanonicalInitialAdmissionLaunchTarget launchTarget( + String targetNamespace, UUID canonicalTenantId, UUID canonicalVersionId) { + CanonicalGameInstanceLaunchAssociation association = + mock(CanonicalGameInstanceLaunchAssociation.class); + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + when(association.targetNamespace()).thenReturn(targetNamespace); + when(association.gameSessionTenantId()).thenReturn(101L); + when(association.canonicalTenantId()).thenReturn(canonicalTenantId); + when(association.worldSlug()).thenReturn("demo-world"); + when(association.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(association.publicProduction()).thenReturn(true); + when(association.gameInstanceUuid()).thenReturn(INSTANCE); + + CanonicalInitialAdmissionLaunchTarget launch = + mock(CanonicalInitialAdmissionLaunchTarget.class); + when(launch.association()).thenReturn(association); + when(launch.realmId()).thenReturn(REALM); + when(launch.gameInstanceId()).thenReturn(202L); + when(launch.runtimeVersionId()).thenReturn(303L); + when(launch.canonicalVersionId()).thenReturn(canonicalVersionId); + return launch; + } + + private static IntakeReceipt sourceReceipt(String targetNamespace) { + UUID intakeOperationId = uuid("99999999-9999-4999-8999-999999999999"); + UUID intakeRequestId = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + UUID sourceOperationId = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + String tenantSlug = "demo-tenant"; + String worldSlug = "demo-world"; + String worldDisplayName = "Demo World"; + String sourceTenantKey = "game-design-tenant-42"; + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + targetNamespace, sourceOperationId, TENANT, tenantSlug, worldSlug, worldDisplayName); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + targetNamespace, + sourceOperationId, + intakeOperationId, + sourceRequestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + targetNamespace, + sourceOperationId, + intakeOperationId, + sourceRequestDigest, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + sourceTenantKey, + "NEW_GAME_ROW", + sourceEvidenceDigest); + String intakeRequestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(intakeRequestId, source); + String receiptDigest = + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + intakeOperationId, intakeRequestDigest, source.evidenceDigest()); + return new IntakeReceipt( + intakeOperationId, intakeRequestId, intakeRequestDigest, source, receiptDigest); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java new file mode 100644 index 0000000000..d8caec3dc5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java @@ -0,0 +1,307 @@ +package unit.net.firedevops.firemud.gamesession.service; + +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 java.util.Optional; +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.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import org.junit.jupiter.api.Test; + +class CanonicalPublishedPlayerRouteReadServiceTest { + private static final String NAMESPACE = "gameplay"; + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID SOURCE_OPERATION = uuid("66666666-6666-4666-8666-666666666666"); + private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void tenantSelectorOwnerReadRejectsChangedCanonicalSelectorOrCounterBeforeGameDesign() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(TENANT)).thenReturn(f.route()); + var request = exactRequest(999L, 0L, 0L); + + assertThatThrownBy(() -> f.service().readCurrent(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void tenantSelectorOwnerReadRejectsChangedTargetNamespaceBeforeOwnerRead() { + var f = fixture(); + var request = exactRequest(0L, 0L, 0L); + var changed = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + request.requestUuid(), + request.canonicalAccountUuid(), + "another-owner", + request.canonicalTenantUuid(), + request.worldSlug(), + request.realmUuid(), + request.realmSlug(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.canonicalGameInstanceUuid(), + request.canonicalVersionUuid(), + request.expectedCatalogRevision(), + request.expectedPointerVersion(), + request.expectedActiveWorldEpoch()); + + assertThatThrownBy(() -> f.service().readCurrent(changed)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.routeReader(), never()).readCurrentTarget(any(UUID.class)); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void assignmentSelectorReadDerivesRouteByTenantAndRejectsChangedSelectorBeforeGameDesign() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(TENANT)).thenReturn(f.route()); + var request = assignmentRequest(uuid("99999999-9999-4999-8999-999999999999")); + + assertThatThrownBy(() -> f.service().readCurrentForAssignment(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + + verify(f.routeReader()).readCurrentTarget(TENANT); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void staleRouteReturnsNoPolicyAndDoesNotContactGameDesign() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(f.route())) + .thenReturn(mock(CanonicalPlayableTarget.class)); + var service = f.service(); + + assertThatThrownBy(() -> service.readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void storageAndGameDesignTransportFailuresRemainDistinctAndReturnNoRoute() { + var storage = fixture(); + when(storage.routeReader().readCurrentTarget(storage.route())) + .thenThrow( + new CanonicalPlayerRouteReadService.ReadUnavailableException("database offline")); + assertThatThrownBy(() -> storage.service().readCurrent(storage.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class); + + var transport = fixture(); + when(transport.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow( + io.grpc.Status.UNAVAILABLE.withDescription("owner offline").asRuntimeException()); + assertThatThrownBy(() -> transport.service().readCurrent(transport.route())) + .isInstanceOf( + CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException.class); + } + + @Test + void missingCompleteGameDesignPolicySetFailsClosed() { + var f = fixture(); + + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.policyClient()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void changedCurrentSourceBindingFailsBeforePolicyRead() { + var f = fixture(); + when(f.source().operationId()).thenReturn(uuid("77777777-7777-4777-8777-777777777777")); + + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + @Test + void changedCanonicalVersionFailsBeforePolicyRead() { + var f = fixture(); + when(f.release().canonicalVersionId()).thenReturn(uuid("99999999-9999-4999-8999-999999999999")); + + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + + private static Fixture fixture() { + var routeReader = mock(CanonicalPlayerRouteReadService.class); + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + var policyClient = mock(GameDesignPublishedRealmPolicyClient.class); + var route = mock(CanonicalPlayableTarget.class); + var catalog = mock(CanonicalRealmCatalogSnapshot.class); + var receipt = mock(IntakeReceipt.class); + var source = mock(AuthoredWorldSourceEvidence.class); + var launch = mock(CanonicalInitialAdmissionLaunchTarget.class); + var association = mock(CanonicalGameInstanceLaunchAssociation.class); + var completeBinding = mock(CompleteLaunchBindingEvidence.class); + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + + when(route.targetNamespace()).thenReturn(NAMESPACE); + when(route.canonicalTenantId()).thenReturn(TENANT); + when(route.worldSlug()).thenReturn("earth"); + when(route.realmId()).thenReturn(REALM); + when(route.realmSlug()).thenReturn("main"); + when(route.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(route.playableStateScope()).thenReturn("SHARED"); + when(route.canonicalGameInstanceId()).thenReturn(INSTANCE); + when(route.gameInstanceId()).thenReturn(202L); + when(route.runtimeVersionId()).thenReturn(303L); + when(route.canonicalVersionId()).thenReturn(VERSION); + + when(catalog.targetNamespace()).thenReturn(NAMESPACE); + when(catalog.tenantId()).thenReturn(TENANT); + when(catalog.worldSlug()).thenReturn("earth"); + when(catalog.realmId()).thenReturn(REALM); + when(catalog.realmSlug()).thenReturn("main"); + when(catalog.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(catalog.visible()).thenReturn(true); + when(catalog.publicProduction()).thenReturn(true); + when(catalog.stateScope()).thenReturn("SHARED"); + when(catalog.sourceIntakeReceipt()).thenReturn(receipt); + when(receipt.source()).thenReturn(source); + when(source.targetNamespace()).thenReturn(NAMESPACE); + when(source.canonicalTenantId()).thenReturn(TENANT); + when(source.sourceGameRowId()).thenReturn(42L); + when(source.sourceGameTenantKey()).thenReturn("game-design-tenant-42"); + when(source.provenanceKind()).thenReturn("NEW_GAME_ROW"); + when(source.operationId()).thenReturn(SOURCE_OPERATION); + when(source.evidenceDigest()).thenReturn(SOURCE_DIGEST); + + when(launch.association()).thenReturn(association); + when(launch.realmId()).thenReturn(REALM); + when(launch.gameInstanceId()).thenReturn(202L); + when(launch.runtimeVersionId()).thenReturn(303L); + when(launch.canonicalVersionId()).thenReturn(VERSION); + when(association.targetNamespace()).thenReturn(NAMESPACE); + when(association.canonicalTenantId()).thenReturn(TENANT); + when(association.gameInstanceUuid()).thenReturn(INSTANCE); + when(association.worldSlug()).thenReturn("earth"); + when(association.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(association.publicProduction()).thenReturn(true); + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + when(association.controlPlaneRequestId()).thenReturn("launch-request"); + when(association.launchDescriptorId()).thenReturn("launch-descriptor"); + when(association.launchBindingEvidence()).thenReturn(completeBinding); + when(completeBinding.descriptor()).thenReturn(descriptor); + when(completeBinding.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(NAMESPACE); + when(descriptor.canonicalTenantId()).thenReturn(TENANT); + when(descriptor.worldSlug()).thenReturn("earth"); + when(descriptor.authoredWorldSourceOperationId()).thenReturn(SOURCE_OPERATION); + when(descriptor.authoredWorldSourceEvidenceDigest()).thenReturn(SOURCE_DIGEST); + when(descriptor.versionId()).thenReturn(303L); + when(descriptor.versionStateEpoch()).thenReturn(7L); + when(descriptor.publishedReleaseBundleRef()).thenReturn("bundle:exact"); + when(descriptor.controlPlaneRequestId()).thenReturn("launch-request"); + when(descriptor.launchDescriptorId()).thenReturn("launch-descriptor"); + when(release.targetNamespace()).thenReturn(NAMESPACE); + when(release.canonicalTenantId()).thenReturn(TENANT); + when(release.canonicalVersionId()).thenReturn(VERSION); + when(release.worldSlug()).thenReturn("earth"); + when(release.authoredWorldSourceOperationId()).thenReturn(SOURCE_OPERATION); + when(release.authoredWorldSourceEvidenceDigest()).thenReturn(SOURCE_DIGEST); + when(release.versionStateEpoch()).thenReturn(7L); + when(release.publishedReleaseBundleRef()).thenReturn("bundle:exact"); + + when(routeReader.readCurrentTarget(route)).thenReturn(route); + when(catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(launchRepository.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launch)); + var service = + new CanonicalPublishedPlayerRouteReadService( + NAMESPACE, routeReader, catalogRepository, launchRepository, policyClient); + return new Fixture( + routeReader, + catalogRepository, + launchRepository, + policyClient, + route, + source, + launch, + release, + service); + } + + private static CanonicalGameplayRosterOwnerReadEvidence.Request exactRequest( + long pointerDelta, long catalogDelta, long epochDelta) { + return new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + NAMESPACE, + TENANT, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L + catalogDelta, + 1L + pointerDelta, + 1L + epochDelta); + } + + private static PreseededActorAssignmentOwnerReadEvidence.Request assignmentRequest( + UUID realmUuid) { + return new PreseededActorAssignmentOwnerReadEvidence.Request( + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + NAMESPACE, + TENANT, + "earth", + realmUuid, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L, + "b".repeat(64), + "bundle:exact"); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record Fixture( + CanonicalPlayerRouteReadService routeReader, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameDesignPublishedRealmPolicyClient policyClient, + CanonicalPlayableTarget route, + AuthoredWorldSourceEvidence source, + CanonicalInitialAdmissionLaunchTarget launch, + AuthoredWorldReleaseAttestationEvidence release, + CanonicalPublishedPlayerRouteReadService service) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java new file mode 100644 index 0000000000..a578ef08e9 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java @@ -0,0 +1,300 @@ +package unit.net.firedevops.firemud.gamesession.service.impl; + +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 com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProofCodec; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterOwnerReadResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayRosterOwnerReadGrpcAdapterTest { + private static final String NAMESPACE = "gameplay"; + private static final String ENTITY_SERVICE = "entity-management-service"; + private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); + private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); + private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INSTANCE = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID VERSION = uuid("55555555-5555-4555-8555-555555555555"); + + @AfterEach + void tearDown() { + SessionContext.clear(); + } + + @Test + void exactEntityPeerReceivesExactProofAndEchoedAccountBinding() { + var provider = provider(); + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + var request = request(); + var typedRequest = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + uuid(request.getRequestUuid()), + ACCOUNT, + NAMESPACE, + TENANT, + "earth", + REALM, + "main", + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 71L, + 73L, + 82L); + var proof = ownerProof(); + byte[] proofBytes = GameSessionCanonicalInitialAdmissionOwnerProofCodec.canonicalBytes(proof); + var policySet = + PublishedRealmPolicyEvidenceFixture.fixture( + TENANT, + VERSION, + 73L, + 42L, + "source-game-key-42", + "RETAINED_GAME_V29", + 3, + PublishedRealmPolicyEvidenceFixture.policy("main", true, true, "SHARED")) + .set(); + byte[] policyBytes = policySet.canonicalBytes(); + var evidence = + new CanonicalGameplayRosterOwnerReadEvidence( + typedRequest, "a".repeat(64), proof, policySet); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrent(typedRequest)).thenReturn(evidence); + + var observer = responseObserver(); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request, observer)); + + var responseCaptor = + org.mockito.ArgumentCaptor.forClass(GetCanonicalGameplayRosterOwnerReadResponse.class); + verify(observer).onNext(responseCaptor.capture()); + verify(observer).onCompleted(); + verify(source).readCurrent(typedRequest); + assertThat(responseCaptor.getValue().getRequest()).isEqualTo(request); + assertThat(responseCaptor.getValue().getRequest().getCanonicalAccountUuid()) + .isEqualTo(ACCOUNT.toString()); + assertThat(responseCaptor.getValue().getGameSessionOwnerProof().toByteArray()) + .isEqualTo(proofBytes); + assertThat(responseCaptor.getValue().getPublishedPolicySetEvidence().toByteArray()) + .isEqualTo(policyBytes); + } + + @Test + void rejectsWrongPeerNamespaceCallerContextAndTargetNamespaceBeforeSourceRead() { + var provider = provider(); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + var observer = responseObserver(); + + runAsPeer( + "world-management-service", + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), observer)); + assertStatus(observer, Status.Code.PERMISSION_DENIED); + verify(provider, never()).getIfAvailable(); + + var wrongNamespaceObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + "other", + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), wrongNamespaceObserver)); + assertStatus(wrongNamespaceObserver, Status.Code.PERMISSION_DENIED); + verify(provider, never()).getIfAvailable(); + + SessionContext.setContext(ACCOUNT.toString(), List.of("player"), Map.of()); + var callerContextObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), callerContextObserver)); + assertStatus(callerContextObserver, Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + var targetObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> + adapter.getCanonicalGameplayRosterOwnerRead( + request().toBuilder().setTargetNamespace("other").build(), targetObserver)); + assertStatus(targetObserver, Status.Code.PERMISSION_DENIED); + verify(provider, never()).getIfAvailable(); + } + + @Test + void rejectsUnknownAndPartialRequestsAndUnavailableOwnerTransport() { + var provider = provider(); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + var unknownObserver = responseObserver(); + var unknown = + request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(unknown, unknownObserver)); + assertStatus(unknownObserver, Status.Code.INVALID_ARGUMENT); + verify(provider, never()).getIfAvailable(); + + when(provider.getIfAvailable()).thenReturn(null); + var unavailableObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), unavailableObserver)); + assertStatus(unavailableObserver, Status.Code.UNAVAILABLE); + + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class))) + .thenThrow( + new CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException( + "private backend detail", new IllegalStateException("transport"))); + var transportObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), transportObserver)); + assertStatus(transportObserver, Status.Code.UNAVAILABLE); + } + + @Test + void staleOrInvalidCurrentSelectorsFailClosed() { + var provider = provider(); + var source = mock(CanonicalPublishedPlayerRouteReadService.class); + when(provider.getIfAvailable()).thenReturn(source); + when(source.readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class))) + .thenThrow(new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException("stale")); + var adapter = new CanonicalGameplayRosterOwnerReadGrpcAdapter(provider, NAMESPACE); + var staleObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), staleObserver)); + assertStatus(staleObserver, Status.Code.FAILED_PRECONDITION); + + when(source.readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class))) + .thenThrow( + new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( + "changed policy or source")); + var invalidObserver = responseObserver(); + runAsPeer( + ENTITY_SERVICE, + NAMESPACE, + () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), invalidObserver)); + assertStatus(invalidObserver, Status.Code.FAILED_PRECONDITION); + } + + private static void assertStatus(StreamObserver observer, Status.Code expected) { + var errorCaptor = org.mockito.ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(errorCaptor.capture()); + assertThat(Status.fromThrowable(errorCaptor.getValue()).getCode()).isEqualTo(expected); + assertThat(errorCaptor.getValue()).isInstanceOf(StatusRuntimeException.class); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static StreamObserver responseObserver() { + return mock(StreamObserver.class); + } + + private static GetCanonicalGameplayRosterOwnerReadRequest request() { + return GetCanonicalGameplayRosterOwnerReadRequest.newBuilder() + .setSchemaVersion(1) + .setRequestUuid("66666666-6666-4666-8666-666666666666") + .setCanonicalAccountUuid(ACCOUNT.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantUuid(TENANT.toString()) + .setWorldSlug("earth") + .setRealmUuid(REALM.toString()) + .setRealmSlug("main") + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceUuid(INSTANCE.toString()) + .setCanonicalVersionUuid(VERSION.toString()) + .setExpectedCatalogRevision(71L) + .setExpectedPointerVersion(73L) + .setExpectedActiveWorldEpoch(82L) + .build(); + } + + private static ObjectProvider provider() { + @SuppressWarnings("unchecked") + ObjectProvider provider = mock(ObjectProvider.class); + return provider; + } + + private static GameSessionCanonicalInitialAdmissionOwnerProof ownerProof() { + var request = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + "initial-admission-owner-request", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 71L, + null); + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity( + request, + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888")); + return new GameSessionCanonicalInitialAdmissionOwnerProof( + hold, + GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + 73L, + 91L, + "sha256:" + "b".repeat(64), + false, + Instant.parse("2026-10-08T03:04:05Z")); + } + + private static void runAsPeer(String service, String namespace, Runnable action) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/" + service; + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, service)) + .run(action); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java new file mode 100644 index 0000000000..94ae82b2ba --- /dev/null +++ b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java @@ -0,0 +1,765 @@ +package support.net.firedevops.firemud.gamesession; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +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.GameDesignPublicationTerminalEvidence.Participant; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.ReleaseContent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.OwnedAffectedTuple; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence.Request; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; + +/** Complete canonical policy-set evidence for Game Session receiving-boundary tests. */ +public final class PublishedRealmPolicyEvidenceFixture { + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final UUID ACTOR_ID = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + private static final UUID OPERATION_ID = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + private static final UUID VERSION_IDENTITY_OPERATION_ID = + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaac"); + private static final UUID DRAFT_REQUEST_ID = uuid("44444444-4444-4444-8444-444444444444"); + private static final UUID COMMIT_ID = uuid("55555555-5555-4555-8555-555555555555"); + private static final UUID DRAFT_FENCE_ID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + private static final UUID INTAKE_REQUEST_ID = uuid("33333333-3333-4333-8333-333333333333"); + private static final UUID INTAKE_OPERATION_ID = uuid("ffffffff-ffff-4fff-8fff-ffffffffffff"); + private static final UUID REGION_TEMPLATE_ID = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ZONE_TEMPLATE_ID = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID ROOM_TEMPLATE_ID = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID REGION_REVISION_ID = uuid("12345678-1234-4234-8234-123456789001"); + private static final UUID ZONE_REVISION_ID = uuid("12345678-1234-4234-8234-123456789002"); + private static final UUID ROOM_REVISION_ID = uuid("12345678-1234-4234-8234-123456789003"); + private static final ObjectMapper JSON = new ObjectMapper(); + + private PublishedRealmPolicyEvidenceFixture() {} + + public static Fixture fixture(PolicySpec... requestedPolicies) { + return fixture( + uuid("11111111-1111-4111-8111-111111111111"), + uuid("22222222-2222-4222-8222-222222222222"), + 19L, + 42L, + "tenant-key", + "NEW_GAME_ROW", + 3, + requestedPolicies); + } + + public static Fixture fixture( + UUID canonicalTenantId, + UUID canonicalVersionId, + long versionRowId, + long sourceGameRowId, + String tenantKey, + String provenanceKind, + int versionNumber, + PolicySpec... requestedPolicies) { + TargetProof target = + new TargetProof( + canonicalTenantId, + canonicalVersionId, + versionRowId, + tenantKey, + sourceGameRowId, + tenantKey, + provenanceKind); + DraftCommitBinding draft = freshGraphBinding(target); + byte[] accountBytes = accountBinding(draft); + var selection = selection(target, draft); + var workflow = + PublicationDigestRequestBinding.full( + target.canonicalTenantId().toString(), + Long.toString(target.gameDesignVersionRowId()), + "publication-request") + .derivedWorkflowIdentity(); + var terminalReadRequest = + new WorldDraftTerminalReadEvidence.Request(1, "test", INTAKE_REQUEST_ID, accountBytes); + var committed = committedFreshGraphReadback(terminalReadRequest); + List tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var worldRequest = + new Request( + "test", + target.canonicalTenantId(), + target.canonicalVersionId(), + INTAKE_REQUEST_ID, + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), + "publication-request", + selection.digest().substring(7), + 5L, + workflow, + draft.commitId().toString(), + "b".repeat(64), + 3, + tuples); + JsonNode applied = JSON.readTree(committed.result()); + byte[] receipt = + Base64.getDecoder().decode(applied.get("startLocationReceiptBase64").textValue()); + var world = + new WorldPublishedStartLocationEvidence( + worldRequest, receipt, committed.fullBinding(), committed.result()); + var operation = new GameDesignPublicationOperationBinding(selectionAccount(selection), world); + var release = release(operation, versionNumber); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + 6L); + + List specs = + java.util.Arrays.stream(requestedPolicies) + .sorted( + java.util.Comparator.comparing(PolicySpec::worldSlug) + .thenComparing(PolicySpec::realmSlug)) + .toList(); + if (specs.isEmpty()) { + throw new IllegalArgumentException("At least one complete published policy is required"); + } + List policies = + specs.stream() + .map( + spec -> { + RealmEntryPolicy policy = policy(spec); + UUID policyId = + stableUuid("policy/" + canonicalVersionId + "/" + spec.realmSlug()); + UUID revisionId = + stableUuid("revision/" + canonicalVersionId + "/" + spec.realmSlug()); + String logicalRevisionId = + "realm-policy/" + spec.worldSlug() + "/" + spec.realmSlug(); + String policyDigest = + PublishedRealmEntryPolicySetEvidence.policyDigest( + policyId, + target, + versionNumber, + release.publishedReleaseBundleRef(), + release.contentDigest(), + workflow, + DIGEST, + draft.commitId(), + revisionId, + logicalRevisionId, + policy); + return new PublishedRealmEntryPolicyEvidence( + policyId, + draft.commitId(), + revisionId, + logicalRevisionId, + policy, + policyDigest); + }) + .toList(); + byte[] capture = capture(operation, draft, "43", specs, policies); + String setDigest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + target, + versionNumber, + draft.commitId(), + "43", + release.publishedReleaseBundleRef(), + release.contentDigest(), + workflow, + DIGEST, + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies); + PublishedRealmEntryPolicySetEvidence evidence = + new PublishedRealmEntryPolicySetEvidence( + target, + versionNumber, + draft.commitId(), + "43", + release.publishedReleaseBundleRef(), + release.contentDigest(), + workflow, + DIGEST, + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture, + terminal.canonicalBytes(), + policies.size(), + setDigest, + policies); + if (!evidence.hasValidDigest()) { + throw new IllegalStateException("Canonical Game Design policy evidence fixture is invalid"); + } + return new Fixture(target, evidence, operation, terminal, capture); + } + + public static CanonicalPublishedPlayerRoute canonicalPublishedRoute() { + var fixture = fixture(policy("main", true, true, "SHARED")); + var route = + new CanonicalPlayableTarget( + "test", + "tenant-key", + uuid("11111111-1111-4111-8111-111111111111"), + "earth", + "Earth", + uuid("22222222-2222-4222-8222-222222222222"), + "main", + "main", + 101L, + 202L, + uuid("33333333-3333-4333-8333-333333333333"), + "SHARED", + uuid("44444444-4444-4444-8444-444444444444"), + fixture.target().canonicalVersionId(), + 303L, + 1L, + 7L, + "d".repeat(64), + 82L, + "first-open-operation-17", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + uuid("99999999-9999-4999-8999-999999999999"), + uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "sha256:" + "c".repeat(64), + 27L, + "sha256:" + "f".repeat(64), + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + false, + Instant.parse("2026-10-07T00:00:00Z"), + "PRESEEDED_ONLY"); + return new CanonicalPublishedPlayerRoute( + route, fixture.set(), fixture.set().policies().getFirst()); + } + + public static CanonicalGameplayRosterClient.PreseededRosterSnapshot rosterSnapshot( + CanonicalPublishedPlayerRoute route, + UUID accountUuid, + List actors) { + var target = route.route(); + var publishedTarget = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(target.canonicalTenantId().toString()) + .setRealmUuid(target.realmId().toString()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(target.canonicalGameInstanceId().toString()) + .setCatalogRevision(target.catalogRevision()) + .setPointerVersion(target.pointerVersion()) + .setActiveWorldEpoch(target.activeWorldEpoch()) + .setCanonicalVersionUuid(target.canonicalVersionId().toString()) + .setPublishedPolicyDigest( + route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())) + .setPublishedReleaseBundleRef(route.policySetEvidence().publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest(target.admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest(target.ownerProofDigest().substring("sha256:".length())) + .setPlayableStateNamespaceUuid(target.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + return new CanonicalGameplayRosterClient.PreseededRosterSnapshot( + accountUuid, + uuid("88888888-8888-4888-8888-888888888888"), + "b".repeat(64), + publishedTarget, + actors); + } + + public static PolicySpec policy( + String realmSlug, boolean visible, boolean publicProduction, String scope) { + return new PolicySpec("earth", "Earth", realmSlug, realmSlug, visible, publicProduction, scope); + } + + private static AccountPublicationAuthorizationBinding selectionAccount( + AuthoredDraftPublishSelectionBinding selection) { + return new AccountPublicationAuthorizationBinding( + uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR_ID, selection), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + ACTOR_ID.toString(), + "1", + "1", + null, + null, + new byte[] {1, 2, 3}))); + } + + private static AuthoredDraftPublishSelectionBinding selection( + TargetProof target, DraftCommitBinding draft) { + String request = "publication-request"; + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + request, + "5", + "test publication", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + java.time.OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + } + + private static DraftCommitBinding freshGraphBinding(TargetProof target) { + String declaration = + JSON.writeValueAsString( + Map.of( + "tenantId", target.canonicalTenantId().toString(), + "versionId", target.canonicalVersionId().toString(), + "startLocation", + Map.of( + "tenantId", target.canonicalTenantId().toString(), + "versionId", target.canonicalVersionId().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 DraftCommitBinding.create( + target, + DRAFT_REQUEST_ID, + COMMIT_ID, + "base-1", + List.of( + new RevisionPayload( + "0", + REGION_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + REGION_REVISION_ID, + "WORLD_DESIGN_AGGREGATE_TYPE_REGION", + REGION_TEMPLATE_ID, + declaration)), + new RevisionPayload( + "1", + ZONE_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ZONE_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ZONE", ZONE_TEMPLATE_ID, null)), + new RevisionPayload( + "2", + ROOM_REVISION_ID, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + worldRevisionPayload( + ROOM_REVISION_ID, "WORLD_DESIGN_AGGREGATE_TYPE_ROOM", ROOM_TEMPLATE_ID, null))), + 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 static String worldRevisionPayload( + UUID revisionId, String family, UUID templateId, String declaration) { + var payload = new LinkedHashMap(); + payload.put("logicalRevisionId", revisionId.toString()); + payload.put("commitId", COMMIT_ID.toString()); + payload.put("aggregateType", family); + payload.put("aggregateId", templateId.toString()); + if (declaration != null) { + try { + payload.put("freshGraphDeclaration", JSON.readTree(declaration)); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + } + return JSON.writeValueAsString(payload); + } + + private static 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 static byte[] accountBinding(DraftCommitBinding draft) { + byte[] draftBytes = draft.canonicalBytes(); + return new DraftAuthorizationFenceBinding( + OPERATION_ID, + DRAFT_REQUEST_ID, + COMMIT_ID, + DRAFT_FENCE_ID, + ACTOR_ID, + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + draft.baseCommitId(), + "0", + draftBytes, + draftBytes, + draft.digest(), + List.of( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + ACTOR_ID.toString(), + null, + "1", + null, + null, + new byte[] {4, 5}))) + .canonicalBytes(); + } + + private static DraftAuthorizationFenceBinding.OwnerReadback committedFreshGraphReadback( + WorldDraftTerminalReadEvidence.Request request) { + try { + var account = request.accountBinding(); + DraftCommitBinding draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), + account.inputDigest()); + var operation = new ByteArrayOutputStream(); + var frames = new 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(), + VERSION_IDENTITY_OPERATION_ID.toString(), + Long.toString(draft.target().gameDesignVersionRowId()), + INTAKE_REQUEST_ID.toString(), + INTAKE_OPERATION_ID.toString(), + "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 = graphBytes(request, draft); + String graphDigest = sha256(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + request.targetNamespace(), + account.operationId(), + account.requestId(), + account.commitId(), + account.fenceId(), + sha256(account.canonicalBytes()), + draft.digest(), + new RoomTemplateRef( + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + ROOM_TEMPLATE_ID), + graphDigest); + byte[] receiptBytes = receipt.canonicalBytes(); + var result = new LinkedHashMap(); + result.put("schema", "world-draft-graph-applied/v2"); + result.put("status", "APPLIED"); + result.put( + "operationBytesBase64", Base64.getEncoder().encodeToString(operation.toByteArray())); + result.put("graphBytesBase64", Base64.getEncoder().encodeToString(graph)); + result.put("graphDigest", graphDigest); + result.put("startLocationReceiptBase64", Base64.getEncoder().encodeToString(receiptBytes)); + result.put("startLocationReceiptDigest", receipt.receiptDigest()); + 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", + Long.toString(Long.parseLong(unit.expectedEpoch()) + 1))) + .toList()); + byte[] resultBytes = canonical(JSON.valueToTree(result)); + return new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + account.operationId(), + account.commitId(), + account.fenceId(), + account.inputDigest(), + account.canonicalBytes(), + resultBytes); + } catch (Exception invalid) { + throw new IllegalStateException("Fresh World evidence fixture could not be created", invalid); + } + } + + private static byte[] graphBytes( + WorldDraftTerminalReadEvidence.Request request, DraftCommitBinding draft) throws Exception { + var root = new LinkedHashMap(); + root.put("schemaVersion", "2"); + root.put("canonicalTenantId", draft.target().canonicalTenantId().toString()); + root.put("canonicalVersionId", draft.target().canonicalVersionId().toString()); + var rows = new ArrayList>(); + int mappingId = 1; + long privateRowKey = 101; + for (RevisionPayload revision : draft.revisions()) { + if (revision.owner() != DraftCommitBinding.Owner.WORLD_MANAGEMENT) continue; + JsonNode mutation = JSON.readTree(revision.payload()); + String family = + mutation.get("aggregateType").textValue().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + var mapping = new 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", draft.target().gameDesignVersionRowId()); + mapping.put("version_identity_operation_id", VERSION_IDENTITY_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 static byte[] capture( + GameDesignPublicationOperationBinding operation, + DraftCommitBinding binding, + String sourceEpoch, + List specs, + List policies) { + try { + List> entries = + java.util.stream.IntStream.range(0, specs.size()) + .mapToObj( + index -> { + Map source = new LinkedHashMap<>(); + source.put("commitId", policies.get(index).sourceCommitId().toString()); + source.put("revisionId", policies.get(index).sourceRevisionId().toString()); + source.put("logicalRevisionId", policies.get(index).logicalRevisionId()); + try { + source.put( + "policy", JSON.readTree(policies.get(index).policy().canonicalJson())); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + return source; + }) + .toList(); + var snapshot = new LinkedHashMap(); + snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", sourceEpoch); + snapshot.put("policies", entries); + byte[] snapshotBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot)); + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(capture, snapshotBytes); + return capture.toByteArray(); + } catch (Exception invalid) { + throw new IllegalStateException( + "Policy source capture fixture could not be created", invalid); + } + } + + private static ReleaseContent release( + GameDesignPublicationOperationBinding operation, int versionNumber) { + var request = operation.world().request(); + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) + .toList(); + return new ReleaseContent( + request.canonicalTenantId(), + request.canonicalVersionId(), + "bundle:exact", + versionNumber, + "v2", + request.publishWorkflowId(), + DIGEST, + 1, + List.of(), + List.of(), + participants, + List.of("LOOK"), + "generation-1", + operation.world()); + } + + private static RealmEntryPolicy policy(PolicySpec spec) { + String json = + "{\"schemaVersion\":1,\"worldSlug\":\"" + + spec.worldSlug() + + "\",\"worldDisplayName\":\"" + + spec.worldDisplayName() + + "\",\"realmSlug\":\"" + + spec.realmSlug() + + "\",\"realmDisplayName\":\"" + + spec.realmDisplayName() + + "\",\"visible\":" + + spec.visible() + + ",\"publicProduction\":" + + spec.publicProduction() + + ",\"stateScope\":\"" + + spec.stateScope() + + "\",\"entryPolicy\":\"PRESEEDED_ONLY\"}"; + return RealmEntryPolicy.parse(json, JSON); + } + + private static byte[] canonical(JsonNode node) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(node)); + } + + private static String sha256(byte[] bytes) throws Exception { + return "sha256:" + + java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private static UUID stableUuid(String text) { + return UUID.nameUUIDFromBytes(text.getBytes(StandardCharsets.UTF_8)); + } + + public static UUID uuid(String value) { + return UUID.fromString(value); + } + + public record PolicySpec( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProduction, + String stateScope) {} + + public record Fixture( + TargetProof target, + PublishedRealmEntryPolicySetEvidence set, + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal, + byte[] captureBytes) { + public Fixture { + captureBytes = captureBytes.clone(); + } + + @Override + public byte[] captureBytes() { + return captureBytes.clone(); + } + } +} From 4108d7053ccce4ae67f40f241170bc10d8a4533d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:12:26 +1300 Subject: [PATCH 03/34] Preserve canonical launch producer and non-admitting Game Session preparation --- .../game-design-service/README.md | 4 + .../game-design-service/api-contracts.md | 19 +- .../game-session-service/README.md | 2 + .../game-session-service/runtime-and-data.md | 2 + ...ame-authoring-publishing-and-activation.md | 6 +- .../realm-routing-and-playable-state.md | 2 + .../game-design/v1/game_design_service.proto | 84 +- .../AuthoredWorldLaunchDescriptorClient.java | 201 ++++ ...uthoredWorldLaunchDescriptorGrpcCodec.java | 440 +++++++ ...thoredWorldLaunchDescriptorClientTest.java | 178 +++ ...redWorldLaunchDescriptorGrpcCodecTest.java | 663 +++++++++++ .../dto/CompleteLaunchBindingDto.java | 15 + .../dto/ResolvedLaunchDescriptorDto.java | 34 +- .../service/CompleteLaunchBindingService.java | 14 + .../service/LaunchDescriptorService.java | 24 +- .../CompleteLaunchBindingServiceImpl.java | 489 ++++++++ ...FrozenLaunchDescriptorDenialException.java | 23 + .../service/impl/GameDesignGrpcService.java | 315 ++++- .../impl/LaunchDescriptorServiceImpl.java | 754 +++++++++--- .../src/main/resources/application-prod.yml | 5 + .../src/main/resources/application.yml | 5 + ...teLaunchBindingServiceIntegrationTest.java | 582 +++++++++ ...aunchDescriptorServiceIntegrationTest.java | 1037 ++++++++++++++++- .../CanonicalLaunchGrpcAuthWiringTest.java | 463 ++++++++ .../TenantIdentityGrpcAuthWiringTest.java | 25 +- .../CompleteLaunchBindingServiceImplTest.java | 1011 ++++++++++++++++ .../impl/GameDesignGrpcServiceAuthTest.java | 109 +- .../GameDesignGrpcServiceHelpTopicTest.java | 1 + ...esignGrpcServiceSettingsAuthorityTest.java | 1 + .../impl/GameDesignGrpcServiceTest.java | 377 ++++-- .../impl/LaunchDescriptorServiceImplTest.java | 1024 +++++++++++++--- .../CanonicalLaunchPreparationSnapshot.java | 73 ++ ...eateCanonicalLaunchPreparationRequest.java | 130 +++ ...nCanonicalLaunchPreparationRepository.java | 656 +++++++++++ ...sionCanonicalLaunchPreparationService.java | 246 ++++ ...GameSessionApplicationIntegrationTest.java | 195 +--- ...unchPreparationServiceIntegrationTest.java | 588 ++++++++++ ...stanceServiceLifecycleIntegrationTest.java | 246 +--- ...CanonicalLaunchPreparationServiceTest.java | 853 ++++++++++++++ 39 files changed, 9969 insertions(+), 927 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java create mode 100644 services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java create mode 100644 services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java create mode 100644 services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 598505a693..aaa26a90da 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -16,6 +16,10 @@ Authoritative read surfaces worth wiring into creator/operator tooling: Current capability and proof gaps remain: Game Session's exact pin/epoch persistence and convergence, plus its append-only rollout-history append/readback, are partial and unproved; Game Design plugin publication currently uses the signed-only intake path and exposes one allowlisted `signerKeyId` rather than the target complete `verifiedSignatures[]` set. The ADR 0111 operator-permitted unsigned provenance path remains unimplemented. Draft commit coordination, owner-local compare-and-swap, and the synchronized read fence in [ADR 0129](../../decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) are also target-state and unproved. The official-hosted creator mutation gate in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and changed-term continuity in [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) are also target-only: no Account evidence check, stale-write classification, or durable tenant/evidence binding is implemented or proved. The target 25 MiB file limit, 2 GiB tenant quota, and streaming/chunked transfer for asset uploads are not implemented or proved, because `GameAssetServiceImpl` uses `MultipartFile.getBytes()` without matching limits in `AssetStoreProperties`; upload admission and resource-safety readiness remain blocked. The service exposes only the creator `POST /assets` path, with no public asset `GET`/download route. Publish/export later writes version-prefix objects and a manifest through the private object-store endpoint; target private-candidate/content-addressed publication and approved public `/assets/**` delivery remain unimplemented. Current asset repair, lifecycle CAS, and release-attestation gaps are recorded in [Asset Storage](./asset-storage.md), and the following target-state script-patch and release-bundle descriptions are not current implementation proof. See the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status), [modding-framework.md](./modding-framework.md), [ADR 0111](../../decisions/adr-0111-unified-dsl-with-distinct-embedded-script-and-plugin-lifecycles.md), and [ADR 0128](../../decisions/adr-0128-game-design-plugin-trust-provenance.md). +### Authored-World Launch Boundary + +The canonical authored-world launch slice includes source-qualified ResolveLaunchDescriptor, exact independent GetLaunchDescriptor, and GetCompleteLaunchBinding returning descriptor and release-attestation evidence separately. Game Session's evidence-only preparation and focused proof sources are present, but validation is deferred until published A/B/C dependencies are integrated. Numeric launch selectors are non-authorizing. + ## Responsibilities - Provide REST/gRPC tools and a web UI for editing game assets. diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index fe3ee5265f..affc71b720 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -6,6 +6,14 @@ The protobuf service definitions under [../../../../protos/game-design/v1](../.. For REST endpoints, the authoritative request/response schema source is [openapi.yaml](../../../../services/game-design-service/src/main/resources/openapi.yaml). Design-doc examples should be updated to match when those schemas evolve. +## Authored-World Launch Binding + +Launch resolution is authorized by an exact canonical authored-world source, not by a legacy numeric tenant selector, a template/default tuple alone, or retained Game Session instance metadata. ResolveLaunchDescriptor binds a canonical non-nil tenant UUID, worldSlug, authored-source operation UUID and expected source-evidence digest to the control-plane request and template selection. Optional inputs retain explicit presence in the closed request digest. Game Design verifies source evidence and template ownership, then persists one immutable descriptor outcome for the exact namespace, tenant, and controlPlaneRequestId; exact retries return that original result or deterministic denial, while changed request or source scope cannot replace it. The response carries the complete authored-world request/result evidence needed for independent verification. + +GetLaunchDescriptor is a separate exact read using a fresh non-nil read-request UUID, canonical tenant UUID, world slug, control-plane request ID, and expected request/result digests. A caller compares this committed readback with the original resolve response; a successful resolve response alone is not committed-evidence proof. GetCompleteLaunchBinding reads the same exact descriptor together with its matching immutable full-version release attestation, including participant digests and manifest/artifact evidence. Descriptor evidence and release attestation remain separate digested objects and must not be substituted for one another. These reads are read-only and do not authorize Game Session instance creation, World activation, admission, or PLAY. + +The launch resolver accepts only the exact same-namespace Game Session workload identity. Descriptor readback accepts same-namespace Game Session or World Management; complete-binding readback accepts same-namespace Game Session, World Management, or Entity Management. All reject absent/malformed peer identity, noncanonical or nil UUIDs, and unknown request fields before owner reads. Legacy numeric Game Session launch selectors fail closed and are not translated into this contract. + ## Fresh-Tenant Prerequisite Implementation Status The owner-local fresh-creation repository and exact Account/Game Session mTLS receipt read are implemented; authenticated creator authorization, Account enrollment, runtime admission, and playable proof remain unavailable. No creation RPC or activation is introduced. Current validation evidence and remaining gaps are recorded in the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#fresh-tenant-identity-prerequisite). @@ -54,7 +62,7 @@ The release-attestation, launch-resolution, version-state, settings, asset-purge The following implementation and proof gaps remain in these live paths: - Automation's full-version `GetDraftDesignDigest` receives `versionId` but queries tenant-wide script definitions and event bindings, then hashes that entire set alongside the requested identifier. It therefore does not attest the version-scoped script/binding set required by the [version-control digest contract](version-control.md#digest-participants-by-publish-type); until exact mapping exists, the participant must fail closed. Cross-version isolation and wrong-scope digest proof are absent. -- `GetPublishedReleaseBundle`, `ResolveLaunchDescriptor`, `GetVersionState`, and `GetVersionAssetArtifactState` share `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller. Concrete per-RPC workload allowlists, caller-to-tenant binding, and wrong-workload/cross-tenant negative proof remain absent; the target matrix is recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). +- `GetPublishedReleaseBundle`, `GetVersionState`, and `GetVersionAssetArtifactState` still share `requireLaunchAttestationReadAccess`, which accepts any `isInternalService` caller. Canonical `ResolveLaunchDescriptor`, `GetLaunchDescriptor`, and `GetCompleteLaunchBinding` now have explicit workload peer checks in source; focused proof is present but validation is deferred, and the broader read matrix remains recorded in [version control](version-control.md#launch-and-attestation-read-authorization-target-state). - `PublishPluginVersion` has no stable request identity or normalized request digest, serializes neither publication nor supersession, and has no database CAS/one-active constraint. Concurrent publication attempts can therefore both report `PUBLISHED`; deterministic winner/loser and retry proof remain absent. The target contract makes supersession one serialized owner decision, but it is a normal-path attempt attached to the winning publication, not a guarantee that every competing publication attempt supersedes another version. - `VersionServiceImpl` rejects an uploaded plugin row in terminal `SUPERSEDED` or `REVOKED_DESIGN` state before export or status mutation, so it cannot return to `PUBLISHED` under the same immutable `pluginVersionId`. Rollback/replacement still requires a new `pluginVersionId`, while the prior terminal row remains an immutable audit record; focused `VersionServiceImplTest` proof covers terminal-state rejection, but new-version rollback proof remains absent. - The live `PublishPluginVersionRequest` carries `distribution_manifest_hash` and `distribution_manifest_path`, but the idempotent comparison self-compares stored values and the normal path replaces both with newly exported values. Those inputs are neither removed nor bound as exact expected values, so a changed retry can replay success. The target write contract must choose one path explicitly: remove generated manifest fields from the request, or include them in the request identity/digest and exact validation. @@ -106,7 +114,9 @@ The Temporal owner-authorization seam is implemented at the receiver boundary: e - `GetDesignControlPlaneDigest` – digest surface for publish gating over normalized metadata. - `GetTemplateReferencePhase` – **Target state only; absent from the current proto and implementation:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle` – authoritative read surface for immutable release attestation used by activation, cutover preflight, and repair workflows. It also carries the canonical publish workflow identity and workflow-runtime status for operators. `NOT_FOUND` means the target version is not publish-complete; `SCHEMA_VERSION_UNSUPPORTED` means callers must fail closed until they understand the attestation schema. -- `ResolveLaunchDescriptor` – resolves template metadata and control-plane inputs into one immutable launch descriptor for a game-instance creation attempt. The request must include `controlPlaneRequestId`, and repeated calls for the same launch attempt must return the same descriptor values without re-resolving to newer attestation or patch state. The resolved descriptor now carries the real version-state CAS epoch rather than a derived release-bundle surrogate, and deterministic launch-preflight failures such as `RELEASE_BUNDLE_NOT_FOUND` and `LAUNCH_REMAP_REQUIRED` are returned as normal app errors rather than generic invalid-input collapse. When a cross-version replacement launch is valid, the descriptor now freezes the approved persisted `remapSetId` for the source/target version pair. +- `ResolveLaunchDescriptor` – resolves an exact canonical authored-world source, tenant/world selector, template, and closed optional override tuple into one immutable source-qualified descriptor. The descriptor contains request/result digests and source operation/evidence identity; exact retries replay the stored outcome, and changed reuse fails closed. +- `GetLaunchDescriptor` – independently reads the exact committed descriptor by read-request UUID, canonical tenant, world slug, control-plane request ID, and expected request/result digests. +- `GetCompleteLaunchBinding` – returns that exact descriptor together with its matching full-version release attestation and artifact/manifest evidence; it does not infer or authorize runtime admission. - `CreateTemplateRemapSet` / `ApproveTemplateRemapSet` / `GetTemplateRemapSet` – authoritative control-plane APIs for persisted version-to-version remap identities and their audit history. Game Design owns the `remapSetId` namespace consumed by replacement launch resolution and later cutover preflight. - `CanDeleteVersionAssets` – deletion-eligibility oracle for version-scoped asset prefixes. - `BeginPurgeVersionAssets` – **Target state:** CAS-guarded purge start that atomically re-checks deletion eligibility and transitions `version_asset_artifact` into purge-in-progress state. The current implementation has no database CAS or shared idempotency ledger. @@ -154,8 +164,9 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `GetDesignControlPlaneDigest(GetDesignControlPlaneDigestRequest) returns (GetDesignControlPlaneDigestResponse)` – returns normalized metadata digest used by publish gates. - `GetTemplateReferencePhase(GetTemplateReferencePhaseRequest) returns (GetTemplateReferencePhaseResponse)` – **Target state only; the current proto has no such RPC:** returns the persisted normalized-reference enforcement phase (`BACKFILLING`, `VALIDATED`, `ENFORCED`) used by instance-creation and retirement workflows. - `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. -- `ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse)` – resolves template metadata and control-plane inputs into one immutable launch descriptor for a game-instance creation attempt. - Missing attestation must surface as `RELEASE_BUNDLE_NOT_FOUND`, unsupported attestation schema as `SCHEMA_VERSION_UNSUPPORTED`, and cross-version replacement launches without exactly one approved persisted remap set for the source/target pair as `LAUNCH_REMAP_REQUIRED`. +- `ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse)` – resolves a source-qualified canonical authored-world request and returns a descriptor carrying the complete request/result evidence. +- `GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse)` – performs an independent committed read using exact tenant, world, request, and expected-digest selectors. +- `GetCompleteLaunchBinding(GetLaunchDescriptorRequest) returns (GetCompleteLaunchBindingResponse)` – returns the exact descriptor plus a matching immutable release attestation; callers must compare both complete evidence objects. - `CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse)` – persists a draft remap set for a concrete `(tenantId, sourceVersionId, targetVersionId)` pair. - `ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) returns (ApproveTemplateRemapSetResponse)` – marks a persisted remap set approved for launch/cutover consumers and records approval reason. - `GetTemplateRemapSet(GetTemplateRemapSetRequest) returns (GetTemplateRemapSetResponse)` – returns the canonical remap-set payload and approval state for an existing `remapSetId`. diff --git a/design/architecture/microservices/game-session-service/README.md b/design/architecture/microservices/game-session-service/README.md index 871c6afd12..82c8b2433f 100644 --- a/design/architecture/microservices/game-session-service/README.md +++ b/design/architecture/microservices/game-session-service/README.md @@ -32,6 +32,8 @@ Target state makes Game Session the authoritative owner of region/tick coordinat Current seams are narrower: patch/request convergence reads, instance-scoped pause/resume, region-epoch fencing, and existing version-fence paths do not yet prove complete `scriptPinEpoch` propagation, final-effect enforcement, or Game-Session-owned append-only history. Track those implementation and proof gaps in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#active-gaps). +The canonical authored-world launch preparation service is an evidence-only, source-backed preparation seam. It validates the committed realm catalog and source intake, resolves the canonical descriptor, independently reads it back, and persists exact prepared evidence. It is not wired into instance creation or runtime composition and does not write game_instances, call World activation, admit gameplay, or authorize PLAY; focused proof sources are present and validation is deferred. + ## Terminology - **Tenant** – a hosted game world or project, identified by `tenantId`. All database rows and Redis keys include this prefix so data is isolated between games. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 2eeae8c3e3..934a3ad024 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,6 +10,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: +- Canonical authored-world launch preparation is an evidence-only source boundary: it checks committed catalog/source evidence, performs authenticated Game Design resolve plus independent exact descriptor readback, persists the immutable preparation snapshot, and verifies committed readback. It is not wired into GameInstanceServiceImpl, game_instances, World activation, admission, or PLAY; validation of this new proof family is deferred. + - Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; prepared `String` account-identity carriers still contain numeric row-id text and do not prove UUID consumption. Opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. 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 df5cae8a26..fc7156463f 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,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. +Canonical authored-world launch source now covers request-bound Resolve, exact descriptor Get readback, and complete descriptor-plus-release-attestation binding; the matching Game Session preparation persists evidence but is not runtime-wired or admitting. D's focused producer, consumer, and proof sources are present, but validation is deferred and prior numeric-launch evidence does not establish this canonical boundary. + Current residual: Game Session's effective-settings read is HTTP-`PRIVILEGED`, but the shared classifier admits a role scoped to any tenant and the controller does not bind requested tenant or persisted session scope to that role. A tenant-scoped operator can therefore request effective settings for another tenant (or a tenant-B session); denial proof remains unproved. The effective-settings capability remains partial, with scoped-tenant/session binding and explicit global-operator rules still open. Official-hosted creator-content acceptance remains an unimplemented target gap; see [ADR 0180](../../architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md). These links do not change current capability ratings or imply an operative hosted service. @@ -59,8 +61,8 @@ These links add decision provenance only; they do not change existing implementa | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `proven` for launch-descriptor, game-instance lifecycle, world-instance activation, failure, and termination seams; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.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); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | -| `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | Previously proved lifecycle, World activation, failure, and termination seams remain distinct from the canonical launch work; authored-world Resolve/Get/complete-binding and Game Session preparation sources are present, but validation is deferred and preparation is not runtime-wired; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.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); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | +| `AR-3.2` Release readiness, compatibility, and propagation | `partial` | Previously proved publish-gate, digest-read, release-bundle, and compatibility-check seams remain distinct from the canonical launch work; descriptor and complete-attestation sources are present, but validation is deferred; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index f908fd1ee5..e5a48cb4ab 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -10,6 +10,8 @@ The working realm-catalog projection, admission-pointer reads, bootstrap/connect ## Packet 4 Status and Proof Gaps +The Game Session canonical authored-world launch preparation service validates exact committed realm-catalog and source evidence, then persists authenticated descriptor resolution plus independent owner readback. This source remains evidence-only and unregistered for runtime admission: no routing pointer, game instance, World activation, PLAY, or runtime state is changed. Focused source/proof is present; validation is deferred, so no routing or playable-state capability rating is upgraded. + - `AA-3.3` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) remain the owners for namespace/replacement and lifecycle coordination. Current routing/playable-state implementation and focused proof remain partial; namespace transition, cutover, drain, cleanup, and termination proof are not established. - `AR-3.4` / `AA-3.2`: [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md), [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md), [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md), [Versioning & Runtime Configuration](../../architecture/system-architecture-versioning-runtime.md#fork-snapshot-boundary-for-playtest-realms), [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract), and [Session Behavior](../../architecture/system-architecture-session-behavior.md#playtest-grant-and-lifecycle-session-consequences) remain the canonical owners. This tracker claims no playtest/lifecycle implementation or proof; cross-owner integration remains unverified. diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index b7739f7145..5e2a40d2d9 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -35,6 +35,9 @@ service GameDesignService { returns (CompareAndSetVersionStateResponse); rpc ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse); + rpc GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse); + rpc GetCompleteLaunchBinding(GetLaunchDescriptorRequest) + returns (GetCompleteLaunchBindingResponse); rpc CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse); rpc ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) @@ -337,13 +340,16 @@ message CompareAndSetVersionStateResponse { } message ResolveLaunchDescriptorRequest { - string tenant_id = 1; + string canonical_tenant_id = 1; int64 game_template_id = 2; string control_plane_request_id = 3; optional string requested_script_patch_version = 4; optional int64 source_version_id = 5; optional int64 target_version_id = 6; optional string requested_runtime_flags_json = 7; + string world_slug = 8; + string authored_world_source_operation_id = 9; + string expected_authored_world_source_evidence_digest = 10; } message ResolveLaunchDescriptorResponse { @@ -351,6 +357,79 @@ message ResolveLaunchDescriptorResponse { shared.v1.ErrorDetail error = 2; } +message GetLaunchDescriptorRequest { + string request_id = 1; + string canonical_tenant_id = 2; + string world_slug = 3; + string control_plane_request_id = 4; + string expected_request_digest = 5; + string expected_result_digest = 6; +} + +message GetLaunchDescriptorResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + shared.v1.ErrorDetail error = 3; +} + +message GetCompleteLaunchBindingResponse { + string request_id = 1; + LaunchDescriptor launch_descriptor = 2; + AuthoredWorldReleaseAttestationEvidence release_attestation = 3; + shared.v1.ErrorDetail error = 4; +} + +message AuthoredWorldLaunchDescriptorEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string control_plane_request_id = 3; + string canonical_tenant_id = 4; + string world_slug = 5; + string authored_world_source_operation_id = 6; + string authored_world_source_evidence_digest = 7; + int64 game_template_id = 8; + optional string requested_script_patch_version = 9; + optional int64 source_version_id = 10; + optional int64 target_version_id = 11; + optional string requested_runtime_flags_json = 12; + string request_digest = 13; + string launch_descriptor_id = 14; + int64 version_id = 15; + optional string script_patch_version = 16; + string runtime_flags_json = 17; + string generation_config_revision = 18; + int64 version_state_epoch = 19; + int64 release_bundle_id = 20; + string published_release_bundle_ref = 21; + optional string remap_set_id = 22; + string result_digest = 23; +} + +message AuthoredWorldReleaseAttestationEvidence { + int32 schema_version = 1; + string target_namespace = 2; + string descriptor_result_digest = 3; + string canonical_tenant_id = 4; + string canonical_version_id = 5; + string world_slug = 6; + string authored_world_source_operation_id = 7; + string authored_world_source_evidence_digest = 8; + string launch_descriptor_id = 9; + string published_release_bundle_ref = 10; + int64 version_state_epoch = 11; + string publish_workflow_id = 12; + string commit_id = 13; + repeated ParticipantDigest participant_digests = 14; + string manifest_hash = 15; + int32 manifest_schema_version = 16; + repeated string required_manifest_asset_keys = 17; + repeated PublishedArtifactDigest artifact_digests = 18; + repeated string command_definitions = 19; + string generation_config_revision = 20; + string evidence_digest = 21; + optional bytes world_start_location_evidence = 22; +} + message CreateTemplateRemapSetRequest { string tenant_id = 1; int64 source_version_id = 2; @@ -495,7 +574,7 @@ message PublishedReleaseBundle { message LaunchDescriptor { string launch_descriptor_id = 1; - string tenant_id = 2; + string canonical_tenant_id = 2; int64 game_template_id = 3; string control_plane_request_id = 4; int64 version_id = 5; @@ -506,6 +585,7 @@ message LaunchDescriptor { int64 release_bundle_id = 10; string published_release_bundle_ref = 11; string remap_set_id = 12; + AuthoredWorldLaunchDescriptorEvidence authored_world_binding = 13; } message TemplateRemapSet { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java new file mode 100644 index 0000000000..0cfe9621fe --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClient.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.common.gamedesign; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; + +/** + * Explicit mTLS client for exact authored-world launch descriptor resolution and owner readback. + */ +public final class AuthoredWorldLaunchDescriptorClient + extends AbstractReloadingBlockingGrpcClient< + GameDesignServiceGrpc.GameDesignServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + private volatile boolean initialized; + private volatile boolean closed; + + public AuthoredWorldLaunchDescriptorClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties), + channelFactory, + AuthoredWorldLaunchDescriptorClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + /** Initializes only when an owning service explicitly starts this client. */ + public synchronized void init() throws SSLException, IOException { + if (closed) { + throw new IllegalStateException("Authored-world launch descriptor client is closed"); + } + if (initialized) { + return; + } + initReloadingClient(); + if (stub() == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client did not initialize a gRPC stub"); + } + initialized = true; + } + + /** Resolves a descriptor for exactly the supplied authored-world request tuple. */ + public AuthoredWorldLaunchDescriptorEvidence resolve( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .resolveLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid authored-world launch descriptor evidence", exception); + } + } + + /** Reads back the immutable result using a separate read request UUID and the complete tuple. */ + public AuthoredWorldLaunchDescriptorEvidence get( + AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest request) { + Objects.requireNonNull(request, "request"); + requireNamespace(request.expectedRequest().targetNamespace()); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getLaunchDescriptor(AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(request)); + try { + return AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(request, response); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid exact authored-world launch descriptor readback", + exception); + } + } + + /** Reads and validates the descriptor and separate release attestation as one exact pair. */ + public CompleteLaunchBindingEvidence getComplete(GetLaunchDescriptorRequest request) { + Objects.requireNonNull(request, "request"); + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = requireStub(); + var response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCompleteLaunchBinding(request); + try { + CompleteLaunchBindingEvidence evidence = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + requireNamespace(evidence.descriptor().targetNamespace()); + return evidence; + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "Game Design returned invalid complete authored-world launch binding evidence", + exception); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameDesignService(); + } + + @Override + protected String defaultTarget() { + return "game-design-service:6565"; + } + + @Override + protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub(ManagedChannel channel) { + String expectedGameDesignPeerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service"; + return GameDesignServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedGameDesignPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedGameDesignPeerUri)) + .withCompression("gzip"); + } + + @Override + public synchronized void close() throws IOException { + closed = true; + initialized = false; + super.close(); + } + + private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireStub() { + GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub = stub(); + if (closed || !initialized || currentStub == null) { + throw new IllegalStateException( + "Authored-world launch descriptor client is not initialized and available"); + } + return currentStub; + } + + private void requireNamespace(String targetNamespace) { + if (!workloadNamespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Launch descriptor request must use the configured workload namespace"); + } + } + + private static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties) { + if (tlsProperties == null) { + throw new IllegalArgumentException("gRPC mTLS configuration is required"); + } + if (tlsProperties.isPlaintext()) { + throw new IllegalArgumentException("Launch descriptor reads require workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), "private key"); + requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); + return tlsProperties; + } + + private static void requireReadableFile(String configuredPath, String label) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + String pathText = configuredPath.trim(); + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + "Launch descriptor reads require file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException exception) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be a readable file-backed path", exception); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + "Launch descriptor " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java new file mode 100644 index 0000000000..0aa9346ac9 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodec.java @@ -0,0 +1,440 @@ +package net.firedevops.firemud.common.gamedesign; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; + +/** Closed mapping and exact-readback validation for authored-world launch descriptor RPCs. */ +public final class AuthoredWorldLaunchDescriptorGrpcCodec { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + /** Exact owner read identity and the immutable resolve tuple whose result is being recovered. */ + public record GetRequest( + UUID requestId, + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + String expectedResultDigest) { + public GetRequest { + if (requestId == null || NIL_UUID.equals(requestId)) { + throw new IllegalArgumentException( + "A nonnil launch descriptor read request ID is required"); + } + Objects.requireNonNull(expectedRequest, "expectedRequest"); + if (requestId.equals(expectedRequest.authoredWorldSourceOperationId()) + || requestId.toString().equals(expectedRequest.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Launch descriptor read request ID must be distinct from the original request"); + } + if (expectedResultDigest == null || !SHA256.matcher(expectedResultDigest).matches()) { + throw new IllegalArgumentException( + "Expected launch descriptor result digest must be canonical SHA-256 text"); + } + } + } + + private AuthoredWorldLaunchDescriptorGrpcCodec() {} + + /** Encodes only the exact request fields owned by the immutable shared request value. */ + public static ResolveLaunchDescriptorRequest toResolveRequest( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + Objects.requireNonNull(request, "request"); + ResolveLaunchDescriptorRequest.Builder builder = + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(request.canonicalTenantId().toString()) + .setGameTemplateId(request.gameTemplateId()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setWorldSlug(request.worldSlug()) + .setAuthoredWorldSourceOperationId(request.authoredWorldSourceOperationId().toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest( + request.authoredWorldSourceEvidenceDigest()); + if (request.requestedScriptPatchVersionPresent()) { + builder.setRequestedScriptPatchVersion(request.requestedScriptPatchVersion()); + } + if (request.sourceVersionIdPresent()) { + builder.setSourceVersionId(request.sourceVersionId()); + } + if (request.targetVersionIdPresent()) { + builder.setTargetVersionId(request.targetVersionId()); + } + if (request.requestedRuntimeFlagsJsonPresent()) { + builder.setRequestedRuntimeFlagsJson(request.requestedRuntimeFlagsJson()); + } + return builder.build(); + } + + /** Encodes an exact persisted owner read, kept distinct from the original resolve identity. */ + public static GetLaunchDescriptorRequest toGetRequest(GetRequest request) { + Objects.requireNonNull(request, "request"); + AuthoredWorldLaunchDescriptorEvidence.Request expected = request.expectedRequest(); + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(request.requestId().toString()) + .setCanonicalTenantId(expected.canonicalTenantId().toString()) + .setWorldSlug(expected.worldSlug()) + .setControlPlaneRequestId(expected.controlPlaneRequestId()) + .setExpectedRequestDigest(expected.requestDigest()) + .setExpectedResultDigest(request.expectedResultDigest()) + .build(); + } + + /** Validates the complete response and flat descriptor duplicates against the exact request. */ + public static AuthoredWorldLaunchDescriptorEvidence fromResolveResponse( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, + ResolveLaunchDescriptorResponse response) { + Objects.requireNonNull(expectedRequest, "expectedRequest"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "ResolveLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected launch descriptor resolution"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Launch descriptor resolution returned no descriptor"); + } + return decodeDescriptor(expectedRequest, response.getLaunchDescriptor()); + } + + /** Validates an exact read echo, original request tuple, result digest, and duplicate fields. */ + public static AuthoredWorldLaunchDescriptorEvidence fromGetResponse( + GetRequest request, GetLaunchDescriptorResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(response, "GetLaunchDescriptor response"); + if (response.hasError()) { + throw new IllegalArgumentException("Game Design rejected the exact launch descriptor read"); + } + UUID echoedRequestId = parseCanonicalNonNilUuid(response.getRequestId(), "read request ID"); + if (!request.requestId().equals(echoedRequestId)) { + throw new IllegalArgumentException("Launch descriptor read request ID echo changed"); + } + if (!response.hasLaunchDescriptor()) { + throw new IllegalArgumentException("Exact launch descriptor read returned no descriptor"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + decodeDescriptor(request.expectedRequest(), response.getLaunchDescriptor()); + if (!request.expectedResultDigest().equals(evidence.resultDigest())) { + throw new IllegalArgumentException( + "Launch descriptor result digest does not match the exact read request"); + } + return evidence; + } + + /** + * Validates the complete owner response as one atomic descriptor and attestation pair. The + * request is the exact immutable read selector; neither component is accepted alone. + */ + public static CompleteLaunchBindingEvidence fromCompleteResponse( + GetLaunchDescriptorRequest request, GetCompleteLaunchBindingResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireNoUnknownFields(request, "GetCompleteLaunchBinding request"); + requireNoUnknownFields(response, "GetCompleteLaunchBinding response"); + if (response.hasError()) { + requireNoUnknownFields(response.getError(), "GetCompleteLaunchBinding error"); + throw new IllegalArgumentException("Game Design rejected the complete launch binding read"); + } + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId(), "read request ID"); + UUID echoedRequestId = + parseCanonicalNonNilUuid(response.getRequestId(), "read request ID echo"); + if (!readRequestId.equals(echoedRequestId)) { + throw new IllegalArgumentException("Complete launch binding read request ID echo changed"); + } + if (!response.hasLaunchDescriptor() || !response.hasReleaseAttestation()) { + throw new IllegalArgumentException( + "Complete launch binding read must return both descriptor and release attestation"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = + decodeDescriptor(response.getLaunchDescriptor()); + if (readRequestId.equals(descriptor.authoredWorldSourceOperationId()) + || readRequestId.toString().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "Complete launch binding read request ID must be distinct from the original request"); + } + if (!descriptor.canonicalTenantId().toString().equals(request.getCanonicalTenantId()) + || !descriptor.worldSlug().equals(request.getWorldSlug()) + || !descriptor.controlPlaneRequestId().equals(request.getControlPlaneRequestId()) + || !descriptor.requestDigest().equals(request.getExpectedRequestDigest()) + || !descriptor.resultDigest().equals(request.getExpectedResultDigest())) { + throw new IllegalArgumentException( + "Complete launch binding does not match the exact read selector"); + } + + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + decodeReleaseAttestation(response.getReleaseAttestation()); + try { + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Complete launch binding evidence is invalid", exception); + } + } + + /** Encodes the separate closed release attestation without changing descriptor/v1. */ + public static net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence + toReleaseAttestation(AuthoredWorldReleaseAttestationEvidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + evidence.requireValid(); + var builder = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setDescriptorResultDigest(evidence.descriptorResultDigest()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setCanonicalVersionId(evidence.canonicalVersionId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setPublishWorkflowId(evidence.publishWorkflowId()) + .setCommitId(evidence.commitId()) + .setManifestHash(evidence.manifestHash()) + .setManifestSchemaVersion(evidence.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(evidence.requiredManifestAssetKeys()) + .addAllCommandDefinitions(evidence.commandDefinitions()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setEvidenceDigest(evidence.evidenceDigest()); + if (evidence.worldStartLocationEvidence() != null) { + builder.setWorldStartLocationEvidence( + ByteString.copyFrom(evidence.worldStartLocationEvidence().canonicalBytes())); + } + for (AuthoredWorldReleaseAttestationEvidence.Participant participant : + evidence.participantDigests()) { + ParticipantDigest.Builder participantBuilder = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) { + participantBuilder.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + } + builder.addParticipantDigests(participantBuilder); + } + for (AuthoredWorldReleaseAttestationEvidence.Artifact artifact : evidence.artifactDigests()) { + builder.addArtifactDigests( + PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())); + } + return builder.build(); + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request expectedRequest, LaunchDescriptor descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = decodeDescriptor(descriptor); + if (!evidence.request().equals(expectedRequest)) { + throw new IllegalArgumentException( + "Launch descriptor does not match the exact authored-world resolve request"); + } + return evidence; + } + + private static AuthoredWorldLaunchDescriptorEvidence decodeDescriptor( + LaunchDescriptor descriptor) { + requireNoUnknownFields(descriptor, "LaunchDescriptor"); + if (!descriptor.hasAuthoredWorldBinding()) { + throw new IllegalArgumentException("Launch descriptor has no authored-world binding"); + } + var binding = descriptor.getAuthoredWorldBinding(); + requireNoUnknownFields(binding, "AuthoredWorldLaunchDescriptorEvidence"); + + AuthoredWorldLaunchDescriptorEvidence evidence; + try { + evidence = + new AuthoredWorldLaunchDescriptorEvidence( + binding.getSchemaVersion(), + binding.getTargetNamespace(), + binding.getControlPlaneRequestId(), + parseCanonicalNonNilUuid(binding.getCanonicalTenantId(), "canonical tenant ID"), + binding.getWorldSlug(), + parseCanonicalNonNilUuid( + binding.getAuthoredWorldSourceOperationId(), + "authored-world source operation ID"), + binding.getAuthoredWorldSourceEvidenceDigest(), + binding.getGameTemplateId(), + binding.hasRequestedScriptPatchVersion(), + binding.hasRequestedScriptPatchVersion() + ? binding.getRequestedScriptPatchVersion() + : null, + binding.hasSourceVersionId(), + binding.hasSourceVersionId() ? binding.getSourceVersionId() : null, + binding.hasTargetVersionId(), + binding.hasTargetVersionId() ? binding.getTargetVersionId() : null, + binding.hasRequestedRuntimeFlagsJson(), + binding.hasRequestedRuntimeFlagsJson() + ? binding.getRequestedRuntimeFlagsJson() + : null, + binding.getRequestDigest(), + binding.getLaunchDescriptorId(), + binding.getVersionId(), + binding.hasScriptPatchVersion(), + binding.hasScriptPatchVersion() ? binding.getScriptPatchVersion() : null, + binding.getRuntimeFlagsJson(), + binding.getGenerationConfigRevision(), + binding.getVersionStateEpoch(), + binding.getReleaseBundleId(), + binding.getPublishedReleaseBundleRef(), + binding.hasRemapSetId(), + binding.hasRemapSetId() ? binding.getRemapSetId() : null, + binding.getResultDigest()); + evidence.requireValid(); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Authored-world launch evidence is invalid", exception); + } + + requireFlatDuplicate( + descriptor.getLaunchDescriptorId(), evidence.launchDescriptorId(), "launchDescriptorId"); + requireFlatDuplicate( + descriptor.getCanonicalTenantId(), + evidence.canonicalTenantId().toString(), + "canonicalTenantId"); + requireFlatDuplicate( + descriptor.getGameTemplateId(), evidence.gameTemplateId(), "gameTemplateId"); + requireFlatDuplicate( + descriptor.getControlPlaneRequestId(), + evidence.controlPlaneRequestId(), + "controlPlaneRequestId"); + requireFlatDuplicate(descriptor.getVersionId(), evidence.versionId(), "versionId"); + requireFlatDuplicate( + descriptor.getScriptPatchVersion(), + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "", + "scriptPatchVersion"); + requireFlatDuplicate( + descriptor.getRuntimeFlagsJson(), evidence.runtimeFlagsJson(), "runtimeFlagsJson"); + requireFlatDuplicate( + descriptor.getGenerationConfigRevision(), + evidence.generationConfigRevision(), + "generationConfigRevision"); + requireFlatDuplicate( + descriptor.getVersionStateEpoch(), evidence.versionStateEpoch(), "versionStateEpoch"); + requireFlatDuplicate( + descriptor.getReleaseBundleId(), evidence.releaseBundleId(), "releaseBundleId"); + requireFlatDuplicate( + descriptor.getPublishedReleaseBundleRef(), + evidence.publishedReleaseBundleRef(), + "publishedReleaseBundleRef"); + requireFlatDuplicate( + descriptor.getRemapSetId(), + evidence.remapSetIdPresent() ? evidence.remapSetId() : "", + "remapSetId"); + return evidence; + } + + private static AuthoredWorldReleaseAttestationEvidence decodeReleaseAttestation( + net.firedevops.firemud.gamedesign.v1.AuthoredWorldReleaseAttestationEvidence wire) { + requireNoUnknownFields(wire, "AuthoredWorldReleaseAttestationEvidence"); + List participants = + new java.util.ArrayList<>(wire.getParticipantDigestsCount()); + for (ParticipantDigest participant : wire.getParticipantDigestsList()) { + requireNoUnknownFields(participant, "ParticipantDigest"); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.getParticipantKey(), + participant.getScopeValue(), + false, + null, + participant.getAppliedCommitId(), + participant.getContentDigest(), + participant.getDigestSchemaVersion(), + participant.hasAbilitySchemaDigest(), + participant.hasAbilitySchemaDigest() ? participant.getAbilitySchemaDigest() : null)); + } + List artifacts = + new java.util.ArrayList<>(wire.getArtifactDigestsCount()); + for (PublishedArtifactDigest artifact : wire.getArtifactDigestsList()) { + requireNoUnknownFields(artifact, "PublishedArtifactDigest"); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + artifact.getUsageKey(), + artifact.getArtifactKind(), + artifact.getImmutableObjectKey(), + artifact.getContentDigest(), + artifact.getContentType(), + artifact.getArtifactSchemaVersion())); + } + try { + return new AuthoredWorldReleaseAttestationEvidence( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + wire.getDescriptorResultDigest(), + parseCanonicalNonNilUuid(wire.getCanonicalTenantId(), "canonical tenant ID"), + parseCanonicalNonNilUuid(wire.getCanonicalVersionId(), "canonical version ID"), + wire.getWorldSlug(), + parseCanonicalNonNilUuid( + wire.getAuthoredWorldSourceOperationId(), "authored-world source operation ID"), + wire.getAuthoredWorldSourceEvidenceDigest(), + wire.getLaunchDescriptorId(), + wire.getPublishedReleaseBundleRef(), + wire.getVersionStateEpoch(), + wire.getPublishWorkflowId(), + wire.getCommitId(), + participants, + wire.getManifestHash(), + wire.getManifestSchemaVersion(), + wire.getRequiredManifestAssetKeysList(), + artifacts, + wire.getCommandDefinitionsList(), + wire.getGenerationConfigRevision(), + wire.getEvidenceDigest(), + wire.hasWorldStartLocationEvidence() + ? WorldPublishedStartLocationEvidence.fromStored( + wire.getWorldStartLocationEvidence().toByteArray()) + : null); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Release-attestation evidence is invalid", exception); + } + } + + private static void requireNoUnknownFields(Message message, String label) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException(label + " contains unsupported fields"); + } + } + + private static UUID parseCanonicalNonNilUuid(String value, String label) { + if (value == null) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required", exception); + } + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical nonnil " + label + " is required"); + } + return parsed; + } + + private static void requireFlatDuplicate(String actual, String expected, String field) { + if (!Objects.equals(actual, expected)) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } + + private static void requireFlatDuplicate(long actual, long expected, String field) { + if (actual != expected) { + throw new IllegalArgumentException( + "Flat launch descriptor " + field + " does not match evidence"); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java new file mode 100644 index 0000000000..3c39fbde18 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorClientTest.java @@ -0,0 +1,178 @@ +package net.firedevops.firemud.common.gamedesign; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.UUID; +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.gamedesign.v1.GetLaunchDescriptorRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AuthoredWorldLaunchDescriptorClientTest { + private static final String NAMESPACE = "test"; + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + + @Test + void rejectsPlaintextMissingClasspathAndUnreadableTlsMaterialBeforeChannelCreation( + @TempDir Path directory) throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + + CommonGrpcClientProperties plaintext = fileBackedMtls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy(() -> newClient(plaintext, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + assertThatThrownBy(() -> newClient(new CommonGrpcClientProperties(), channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties classpath = fileBackedMtls(directory); + classpath.setCaCert("classpath:certs/ca.crt"); + assertThatThrownBy(() -> newClient(classpath, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("file-backed"); + + CommonGrpcClientProperties missingFiles = new CommonGrpcClientProperties(); + missingFiles.setCertChain(directory.resolve("missing-client.crt").toString()); + missingFiles.setPrivateKey(directory.resolve("missing-client.key").toString()); + missingFiles.setCaCert(directory.resolve("missing-ca.crt").toString()); + assertThatThrownBy(() -> newClient(missingFiles, channelFactory)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("existing readable file"); + + verifyNoInteractions(channelFactory); + } + + @Test + void deniesResolveAndReadUntilExplicitInitializationAndAfterClose(@TempDir Path directory) + throws Exception { + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + AuthoredWorldLaunchDescriptorClient client = + newClient(fileBackedMtls(directory), channelFactory); + var request = request(NAMESPACE); + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, "sha256:" + "b".repeat(64)); + var completeRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(TENANT_ID.toString()) + .setWorldSlug("copper-coast") + .setControlPlaneRequestId("launch-operation-7") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); + + assertThatThrownBy(() -> client.resolve(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.get(getRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + assertThatThrownBy(() -> client.getComplete(completeRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + + client.close(); + assertThatThrownBy(() -> client.resolve(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not initialized and available"); + verifyNoInteractions(channelFactory); + } + + @Test + void initializesConfiguredTargetWhenFileBackedTlsFilesExist(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("game-design.internal:6565"); + CommonGrpcClientProperties tls = fileBackedMtls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + ManagedChannel channel = mock(ManagedChannel.class); + when(channelFactory.buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true))) + .thenReturn(channel); + AuthoredWorldLaunchDescriptorClient client = + new AuthoredWorldLaunchDescriptorClient(endpoints, tls, channelFactory, NAMESPACE); + + try { + // The mocked channel factory covers explicit target wiring only; socket peer proof is + // separate. + client.init(); + verify(channelFactory) + .buildChannel( + eq("game-design.internal:6565"), + eq(6565), + any(CommonGrpcClientProperties.class), + eq(true)); + } finally { + client.close(); + } + } + + @Test + void rejectsARequestOutsideTheConfiguredNamespace(@TempDir Path directory) throws Exception { + AuthoredWorldLaunchDescriptorClient client = + newClient(fileBackedMtls(directory), mock(GrpcChannelFactory.class)); + try { + assertThatThrownBy(() -> client.resolve(request("other"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + } finally { + client.close(); + } + } + + private static AuthoredWorldLaunchDescriptorClient newClient( + CommonGrpcClientProperties tls, GrpcChannelFactory channelFactory) { + return new AuthoredWorldLaunchDescriptorClient( + new ServiceEndpointsProperties(), tls, channelFactory, NAMESPACE); + } + + private static CommonGrpcClientProperties fileBackedMtls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private key").toString()); + tls.setCaCert( + Files.writeString(directory.resolve("server-ca.crt"), "CA certificate").toString()); + return tls; + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request(String namespace) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + "launch-operation-7", + TENANT_ID, + "copper-coast", + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java new file mode 100644 index 0000000000..fdbd2ad25e --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -0,0 +1,663 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.UnknownFieldSet; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +class AuthoredWorldLaunchDescriptorGrpcCodecTest { + @Test + void v2CompleteReadPreservesWorldEvidenceAndDeniesOmittedMalformedAndSubstitutedBytes() + throws Exception { + var selector = AuthoredWorldReleaseAttestationSelectorTest.selectorEvidence(); + var authored = AuthoredWorldReleaseAttestationSelectorTest.descriptor(selector); + var release = AuthoredWorldReleaseAttestationSelectorTest.release(authored, selector); + var request = completeRequest(authored); + var response = completeResponse(request, authored, release); + assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) + .isEqualTo(new CompleteLaunchBindingEvidence(authored, release)); + for (var invalid : + List.of( + response.getReleaseAttestation().toBuilder().clearWorldStartLocationEvidence().build(), + response.getReleaseAttestation().toBuilder().setSchemaVersion(1).build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(com.google.protobuf.ByteString.EMPTY) + .build(), + response.getReleaseAttestation().toBuilder() + .setWorldStartLocationEvidence(com.google.protobuf.ByteString.copyFromUtf8("{} ")) + .build())) { + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, response.toBuilder().setReleaseAttestation(invalid).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + response.toBuilder() + .setReleaseAttestation( + response.getReleaseAttestation().toBuilder() + .setUnknownFields(unknownFields())) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static final UUID TENANT_ID = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID READ_REQUEST_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final UUID WRONG_READ_REQUEST_ID = + UUID.fromString("42345678-1234-4234-8234-123456789abc"); + private static final UUID VERSION_UUID = UUID.fromString("52345678-1234-4234-8234-123456789abc"); + + @Test + void resolvesAndReadsBackSharedDigestVectorWithExactOptionalPresence() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("test", "copper-coast", false); + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence = + evidence(request); + + assertThat(request.requestDigest()) + .isEqualTo("sha256:ac6fc51a4b81185a33cfe9c84df69e05537a69415a6d8b8fb478a946221e7111"); + assertThat(evidence.resultDigest()) + .isEqualTo("sha256:701c68797b898b696cac24d48dcff4fe25c0856f15965ff7e8b219f7c57acd11"); + + var resolveWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(request); + assertThat(resolveWire.hasRequestedScriptPatchVersion()).isTrue(); + assertThat(resolveWire.hasSourceVersionId()).isFalse(); + assertThat(resolveWire.hasTargetVersionId()).isFalse(); + assertThat(resolveWire.hasRequestedRuntimeFlagsJson()).isFalse(); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, resolveResponse(evidence))) + .isEqualTo(evidence); + + var emptyFlagsRequest = request("test", "copper-coast", true); + var emptyFlagsWire = AuthoredWorldLaunchDescriptorGrpcCodec.toResolveRequest(emptyFlagsRequest); + assertThat(emptyFlagsWire.hasRequestedRuntimeFlagsJson()).isTrue(); + assertThat(emptyFlagsWire.getRequestedRuntimeFlagsJson()).isEmpty(); + var emptyFlagsEvidence = evidence(emptyFlagsRequest); + var emptyFlagsReadback = + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + emptyFlagsRequest, resolveResponse(emptyFlagsEvidence)); + assertThat(emptyFlagsReadback.requestedRuntimeFlagsJsonPresent()).isTrue(); + assertThat(emptyFlagsReadback.requestedRuntimeFlagsJson()).isEmpty(); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + var getWire = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest); + assertThat(getWire.getRequestId()).isEqualTo(READ_REQUEST_ID.toString()); + assertThat(getWire.getExpectedRequestDigest()).isEqualTo(request.requestDigest()); + assertThat(getWire.getExpectedResultDigest()).isEqualTo(evidence.resultDigest()); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, getResponse(READ_REQUEST_ID.toString(), evidence))) + .isEqualTo(evidence); + } + + @Test + void rejectsAChangedRequestFieldAndWrongNamespace() { + var expected = request("test", "copper-coast", false); + var changedWorld = evidence(request("test", "copper-shore", false)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, resolveResponse(changedWorld))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + + var otherNamespace = evidence(request("other", "copper-coast", false)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, resolveResponse(otherNamespace))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact authored-world resolve request"); + } + + @Test + void rejectsEveryChangedFlatDescriptorDuplicate() { + var evidence = evidence(request("test", "copper-coast", false)); + LaunchDescriptor descriptor = descriptor(evidence); + + assertFlatDuplicateRejected(descriptor.toBuilder().setLaunchDescriptorId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setCanonicalTenantId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setGameTemplateId(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setControlPlaneRequestId("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setVersionId(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setScriptPatchVersion("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setRuntimeFlagsJson("other").build()); + assertFlatDuplicateRejected( + descriptor.toBuilder().setGenerationConfigRevision("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setVersionStateEpoch(20L).build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setReleaseBundleId(20L).build()); + assertFlatDuplicateRejected( + descriptor.toBuilder().setPublishedReleaseBundleRef("other").build()); + assertFlatDuplicateRejected(descriptor.toBuilder().setRemapSetId("other").build()); + } + + @Test + void rejectsMissingEvidenceUnknownFieldsAndUnsupportedSchema() { + var request = request("test", "copper-coast", false); + var evidence = evidence(request); + LaunchDescriptor withoutBinding = + descriptor(evidence).toBuilder().clearAuthoredWorldBinding().build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(withoutBinding) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("no authored-world binding"); + + var unknown = unknownFields(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor(evidence)) + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + descriptor(evidence).toBuilder().setUnknownFields(unknown)) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setLaunchDescriptor(descriptor(evidence)) + .setUnknownFields(unknown) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setUnknownFields(unknown))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + var unsupportedSchema = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder().setSchemaVersion(2)) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(unsupportedSchema) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + } + + @Test + void rejectsConflictingDigestsAndNonmatchingReadEchoOrResult() { + var request = request("test", "copper-coast", false); + var evidence = evidence(request); + var invalidRequestDigest = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setRequestDigest("sha256:" + "0".repeat(64))) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(invalidRequestDigest) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + + var invalidResultDigest = + descriptor(evidence).toBuilder() + .setAuthoredWorldBinding( + descriptor(evidence).getAuthoredWorldBinding().toBuilder() + .setResultDigest("sha256:" + "0".repeat(64))) + .build(); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + request, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(invalidResultDigest) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + + var getRequest = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, evidence.resultDigest()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, getResponse(WRONG_READ_REQUEST_ID.toString(), evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("echo changed"); + var wrongResult = + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, request, "sha256:" + "0".repeat(64)); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + wrongResult, getResponse(READ_REQUEST_ID.toString(), evidence))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("result digest"); + } + + @Test + void requiresDistinctNonnilReadRequestUuid() { + var request = request("test", "copper-coast", false); + assertThatThrownBy( + () -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + new UUID(0L, 0L), request, evidence(request).resultDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("nonnil"); + assertThatThrownBy( + () -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + SOURCE_OPERATION_ID, request, evidence(request).resultDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("distinct"); + } + + @Test + void completeReadRoundTripsTheAtomicPairAndPreservesOptionalAbilityDigestPresence() { + var descriptor = evidence(request("test", "copper-coast", false)); + var release = releaseAttestation(descriptor); + var request = completeRequest(descriptor); + var response = completeResponse(request, descriptor, release); + + CompleteLaunchBindingEvidence pair = + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response); + var encoded = + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(pair.releaseAttestation()); + + assertThat(pair.descriptor()).isEqualTo(descriptor); + assertThat(pair.releaseAttestation()).isEqualTo(release); + assertThat(encoded.getParticipantDigests(0).hasAbilitySchemaDigest()).isFalse(); + assertThat(encoded.getParticipantDigests(2).hasAbilitySchemaDigest()).isTrue(); + assertThat(encoded.getParticipantDigests(2).getAbilitySchemaDigest()) + .isEqualTo("sha256:" + "f".repeat(64)); + assertThat(encoded.getArtifactDigests(0).getImmutableObjectKey()) + .isEqualTo(release.artifactDigests().get(0).immutableObjectKey()); + } + + @Test + void completeReadRejectsMissingConflictingAndUnknownEvidenceAtEveryMessageLevel() { + var descriptor = evidence(request("test", "copper-coast", false)); + var release = releaseAttestation(descriptor); + var request = completeRequest(descriptor); + var good = completeResponse(request, descriptor, release); + var unknown = unknownFields(); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setRequestId(WRONG_READ_REQUEST_ID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("echo changed"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request.toBuilder().setWorldSlug("copper-shore").build(), good)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact read selector"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, good.toBuilder().clearReleaseAttestation().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("both descriptor and release attestation"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, good.toBuilder().clearLaunchDescriptor().build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("both descriptor and release attestation"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setError(ErrorDetail.newBuilder().setCode("DENIED")).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("rejected"); + + assertCompleteUnknownRejected(request.toBuilder().setUnknownFields(unknown).build(), good); + assertCompleteUnknownRejected(request, good.toBuilder().setUnknownFields(unknown).build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setLaunchDescriptor(descriptor(descriptor).toBuilder().setUnknownFields(unknown)) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setLaunchDescriptor( + descriptor(descriptor).toBuilder() + .setAuthoredWorldBinding( + descriptor(descriptor).getAuthoredWorldBinding().toBuilder() + .setUnknownFields(unknown))) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder().setUnknownFields(unknown)) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 0, + good.getReleaseAttestation().getParticipantDigests(0).toBuilder() + .setUnknownFields(unknown))) + .build()); + assertCompleteUnknownRejected( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setArtifactDigests( + 0, + good.getReleaseAttestation().getArtifactDigests(0).toBuilder() + .setUnknownFields(unknown))) + .build()); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setError( + ErrorDetail.newBuilder().setUnknownFields(unknown).setCode("DENIED")) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setEvidenceDigest("sha256:" + "0".repeat(64))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("invalid"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 0, + good + .getReleaseAttestation() + .getParticipantDigests(0) + .toBuilder() + .setDigestSchemaVersion(999))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Release-attestation evidence is invalid") + .hasRootCauseMessage("Participant digest schema is unsupported for its owner"); + } + + private static void assertFlatDuplicateRejected(LaunchDescriptor descriptor) { + var expected = request("test", "copper-coast", false); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + expected, + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match evidence"); + } + + private static void assertCompleteUnknownRejected( + GetLaunchDescriptorRequest request, GetCompleteLaunchBindingResponse response) { + assertThatThrownBy( + () -> AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unsupported fields"); + } + + private static GetLaunchDescriptorRequest completeRequest( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(READ_REQUEST_ID.toString()) + .setCanonicalTenantId(descriptor.canonicalTenantId().toString()) + .setWorldSlug(descriptor.worldSlug()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setExpectedRequestDigest(descriptor.requestDigest()) + .setExpectedResultDigest(descriptor.resultDigest()) + .build(); + } + + private static GetCompleteLaunchBindingResponse completeResponse( + GetLaunchDescriptorRequest request, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence release) { + return GetCompleteLaunchBindingResponse.newBuilder() + .setRequestId(request.getRequestId()) + .setLaunchDescriptor(descriptor(descriptor)) + .setReleaseAttestation(AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(release)) + .build(); + } + + private static AuthoredWorldReleaseAttestationEvidence releaseAttestation( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String commitId = "commit-雪"; + List participants = + new java.util.ArrayList<>(); + int index = 0; + for (String key : AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()) { + boolean ability = "GAME_LOGIC".equals(key); + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + key, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + String.valueOf((char) ('a' + index++)).repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(key), + ability, + ability ? "sha256:" + "f".repeat(64) : null)); + } + String artifactDigest = "sha256:" + "e".repeat(64); + var artifact = + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world/雪", + "WORLD_CONTENT", + "artifacts/sha256/" + "e".repeat(64), + artifactDigest, + "application/octet-stream", + 1); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + VERSION_UUID, + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant-key:private-workflow:雪", + commitId, + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(artifact.usageKey()), + List.of(artifact), + List.of("say 雪"), + descriptor.generationConfigRevision()); + } + + private static AuthoredWorldLaunchDescriptorEvidence.Request request( + String namespace, String worldSlug, boolean runtimeFlagsPresent) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + namespace, + "cp-α", + TENANT_ID, + worldSlug, + SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 19L, + true, + "pätch-🦊", + false, + null, + false, + null, + runtimeFlagsPresent, + runtimeFlagsPresent ? "" : null); + } + + private static net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + evidence(AuthoredWorldLaunchDescriptorEvidence.Request request) { + return net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-vector-1", + Long.MAX_VALUE, + true, + "pätch-🦊", + "{\"welcome\":\"雪\"}", + "gen-rév-🧭", + Long.MAX_VALUE, + Long.MAX_VALUE, + "release-bundle:12345678-1234-4234-8234-123456789abc:9223372036854775807:9223372036854775807", + false, + null); + } + + private static ResolveLaunchDescriptorResponse resolveResponse( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + return ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor(evidence)) + .build(); + } + + private static GetLaunchDescriptorResponse getResponse( + String requestId, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + return GetLaunchDescriptorResponse.newBuilder() + .setRequestId(requestId) + .setLaunchDescriptor(descriptor(evidence)) + .build(); + } + + private static LaunchDescriptor descriptor( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence evidence) { + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.Builder binding = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(evidence.gameTemplateId()) + .setRequestDigest(evidence.requestDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setVersionId(evidence.versionId()) + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setResultDigest(evidence.resultDigest()); + if (evidence.requestedScriptPatchVersionPresent()) { + binding.setRequestedScriptPatchVersion(evidence.requestedScriptPatchVersion()); + } + if (evidence.sourceVersionIdPresent()) { + binding.setSourceVersionId(evidence.sourceVersionId()); + } + if (evidence.targetVersionIdPresent()) { + binding.setTargetVersionId(evidence.targetVersionId()); + } + if (evidence.requestedRuntimeFlagsJsonPresent()) { + binding.setRequestedRuntimeFlagsJson(evidence.requestedRuntimeFlagsJson()); + } + if (evidence.scriptPatchVersionPresent()) { + binding.setScriptPatchVersion(evidence.scriptPatchVersion()); + } + if (evidence.remapSetIdPresent()) { + binding.setRemapSetId(evidence.remapSetId()); + } + return LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setGameTemplateId(evidence.gameTemplateId()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setVersionId(evidence.versionId()) + .setScriptPatchVersion( + evidence.scriptPatchVersionPresent() ? evidence.scriptPatchVersion() : "") + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setRemapSetId(evidence.remapSetIdPresent() ? evidence.remapSetId() : "") + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java new file mode 100644 index 0000000000..e012bac30e --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java @@ -0,0 +1,15 @@ +package net.firedevops.firemud.gamedesign.dto; + +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; + +/** The closed descriptor and its independently validated full release attestation. */ +public record CompleteLaunchBindingDto( + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldReleaseAttestationEvidence releaseAttestation) { + public CompleteLaunchBindingDto { + Objects.requireNonNull(descriptor, "descriptor").requireValid(); + Objects.requireNonNull(releaseAttestation, "releaseAttestation").requireValid(descriptor); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java index 251dc5129e..363db4bd74 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/ResolvedLaunchDescriptorDto.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.gamedesign.dto; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; + public record ResolvedLaunchDescriptorDto( String launchDescriptorId, - String tenantId, + String canonicalTenantId, long gameTemplateId, String controlPlaneRequestId, long versionId, @@ -12,31 +14,5 @@ public record ResolvedLaunchDescriptorDto( long versionStateEpoch, long releaseBundleId, String publishedReleaseBundleRef, - String remapSetId) { - public ResolvedLaunchDescriptorDto( - String launchDescriptorId, - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - long versionId, - String scriptPatchVersion, - String runtimeFlagsJson, - String generationConfigRevision, - long versionStateEpoch, - long releaseBundleId, - String publishedReleaseBundleRef) { - this( - launchDescriptorId, - tenantId, - gameTemplateId, - controlPlaneRequestId, - versionId, - scriptPatchVersion, - runtimeFlagsJson, - generationConfigRevision, - versionStateEpoch, - releaseBundleId, - publishedReleaseBundleRef, - null); - } -} + String remapSetId, + AuthoredWorldLaunchDescriptorEvidence authoredWorldBinding) {} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java new file mode 100644 index 0000000000..a929542f41 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.gamedesign.service; + +import java.util.UUID; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; + +public interface CompleteLaunchBindingService { + CompleteLaunchBindingDto getCompleteLaunchBinding( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java index 6403542e21..cf337ee6e8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/LaunchDescriptorService.java @@ -1,14 +1,26 @@ package net.firedevops.firemud.gamedesign.service; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; public interface LaunchDescriptorService { ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - String tenantId, - long gameTemplateId, + AuthoredWorldLaunchDescriptorEvidence.Request request); + + ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest); + + ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson); + String expectedRequestDigest, + String expectedResultDigest); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java new file mode 100644 index 0000000000..d27efee5cf --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -0,0 +1,489 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.annotation.Timed; +import java.util.ArrayList; +import java.util.List; +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.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +/** Reads the already committed immutable launch descriptor and complete release evidence. */ +@Service +public class CompleteLaunchBindingServiceImpl implements CompleteLaunchBindingService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final int SUPPORTED_MANIFEST_SCHEMA_VERSION = 1; + private static final int SUPPORTED_ARTIFACT_SCHEMA_VERSION = 1; + + private final LaunchDescriptorService launchDescriptorService; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + private final PublishedReleaseBundleService publishedReleaseBundleService; + private final VersionRepository versionRepository; + + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected Spring collaborators are internal; construction acquires no resources and this service has no finalizer.") + public CompleteLaunchBindingServiceImpl( + LaunchDescriptorService launchDescriptorService, + GameAuthoredWorldSourceRepository authoredWorldSourceRepository, + PublishedReleaseBundleService publishedReleaseBundleService, + VersionRepository versionRepository) { + this.launchDescriptorService = + Objects.requireNonNull(launchDescriptorService, "launchDescriptorService"); + this.authoredWorldSourceRepository = + Objects.requireNonNull(authoredWorldSourceRepository, "authoredWorldSourceRepository"); + this.publishedReleaseBundleService = + Objects.requireNonNull(publishedReleaseBundleService, "publishedReleaseBundleService"); + this.versionRepository = Objects.requireNonNull(versionRepository, "versionRepository"); + } + + @Override + @Transactional( + propagation = Propagation.REQUIRES_NEW, + readOnly = true, + isolation = Isolation.REPEATABLE_READ) + @Timed(value = "gamedesign.completeLaunchBinding.read") + public CompleteLaunchBindingDto getCompleteLaunchBinding( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + ResolvedLaunchDescriptorDto resolved = + launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + AuthoredWorldLaunchDescriptorEvidence descriptor = + requireDescriptorMatchesSelector( + resolved, + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + + AuthoredWorldVersionStateSnapshot sourceSnapshot = + authoredWorldSourceRepository + .readVersionStateSnapshot( + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.versionId()) + .orElseThrow( + () -> + deny( + "AUTHORED_WORLD_SOURCE_NOT_FOUND", + "exact committed source or descriptor version is missing")); + AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); + requireSourceMatchesDescriptor(source, descriptor, canonicalTenantId, worldSlug); + if (sourceSnapshot.versionState() == null + || sourceSnapshot.versionStateEpoch() <= 0 + || sourceSnapshot.versionStateEpoch() < descriptor.versionStateEpoch()) { + throw deny("VERSION_STATE_INVALID", "same-snapshot Version state evidence is incomplete"); + } + // The current snapshot state is provenance/current-state context. The immutable descriptor + // epoch below remains the historical release binding and is not an activation decision. + + PublishedReleaseBundleDto bundle; + try { + bundle = + publishedReleaseBundleService.getPublishedReleaseBundle( + source.sourceGameTenantKey(), descriptor.versionId()); + } catch (PublishedReleaseBundleNotFoundException missing) { + throw deny( + "RELEASE_BUNDLE_NOT_FOUND", "the descriptor's committed release is missing", missing); + } + requireExactBundleBinding(bundle, source, descriptor, sourceSnapshot.canonicalVersionId()); + Version canonicalVersion = requireCanonicalVersion(bundle, source, descriptor, sourceSnapshot); + requireFullVersion(canonicalVersion, bundle); + + List participants = + requireParticipantEvidence(bundle, descriptor.versionId()); + String commitId = participants.getFirst().appliedCommitId(); + List artifacts = + requireManifestAndArtifactEvidence(bundle); + + AuthoredWorldReleaseAttestationEvidence releaseAttestation; + if ("v2".equals(bundle.attestationSchemaVersion())) { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.worldPublishedStartLocationEvidence()); + } else { + releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + source.canonicalTenantId(), + canonicalVersion.getCanonicalVersionId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + bundle.publishWorkflowId(), + commitId, + participants, + bundle.manifestHash(), + bundle.manifestSchemaVersion(), + bundle.requiredManifestAssetKeys(), + artifacts, + bundle.commandDefinitions(), + bundle.generationConfigRevision()); + } + releaseAttestation.requireValid(descriptor); + return new CompleteLaunchBindingDto(descriptor, releaseAttestation); + } + + private AuthoredWorldLaunchDescriptorEvidence requireDescriptorMatchesSelector( + ResolvedLaunchDescriptorDto resolved, + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw deny("INVALID_READ_REQUEST", "readRequestId must be a canonical non-nil UUID"); + } + if (resolved == null || resolved.authoredWorldBinding() == null) { + throw deny("LAUNCH_DESCRIPTOR_NOT_FOUND", "the exact committed descriptor is missing"); + } + AuthoredWorldLaunchDescriptorEvidence descriptor = resolved.authoredWorldBinding(); + try { + descriptor.requireValid(); + } catch (RuntimeException invalid) { + throw deny("LAUNCH_DESCRIPTOR_CONFLICT", "the exact descriptor evidence is invalid", invalid); + } + if (!Objects.equals(workloadNamespace, descriptor.targetNamespace()) + || !Objects.equals(canonicalTenantId, descriptor.canonicalTenantId()) + || !Objects.equals(worldSlug, descriptor.worldSlug()) + || !Objects.equals(controlPlaneRequestId, descriptor.controlPlaneRequestId()) + || !Objects.equals(expectedRequestDigest, descriptor.requestDigest()) + || !Objects.equals(expectedResultDigest, descriptor.resultDigest()) + || !Objects.equals(resolved.launchDescriptorId(), descriptor.launchDescriptorId()) + || !Objects.equals(resolved.canonicalTenantId(), descriptor.canonicalTenantId().toString()) + || !Objects.equals(resolved.controlPlaneRequestId(), descriptor.controlPlaneRequestId()) + || resolved.gameTemplateId() != descriptor.gameTemplateId() + || resolved.versionId() != descriptor.versionId() + || !Objects.equals(resolved.scriptPatchVersion(), descriptor.scriptPatchVersion()) + || !Objects.equals(resolved.runtimeFlagsJson(), descriptor.runtimeFlagsJson()) + || !Objects.equals( + resolved.generationConfigRevision(), descriptor.generationConfigRevision()) + || resolved.versionStateEpoch() != descriptor.versionStateEpoch() + || resolved.releaseBundleId() != descriptor.releaseBundleId() + || !Objects.equals( + resolved.publishedReleaseBundleRef(), descriptor.publishedReleaseBundleRef()) + || !Objects.equals(resolved.remapSetId(), descriptor.remapSetId())) { + throw deny( + "LAUNCH_DESCRIPTOR_CONFLICT", + "the resolved descriptor does not match the exact read selector and evidence"); + } + return descriptor; + } + + private void requireSourceMatchesDescriptor( + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID canonicalTenantId, + String worldSlug) { + if (source == null + || !Objects.equals(workloadNamespace, source.targetNamespace()) + || !Objects.equals(canonicalTenantId, source.canonicalTenantId()) + || !Objects.equals(worldSlug, source.worldSlug()) + || !Objects.equals(descriptor.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(descriptor.worldSlug(), source.worldSlug()) + || !Objects.equals(descriptor.authoredWorldSourceOperationId(), source.operationId()) + || !Objects.equals(descriptor.authoredWorldSourceEvidenceDigest(), source.evidenceDigest()) + || source.sourceGameRowId() <= 0 + || source.sourceGameTenantKey() == null + || source.sourceGameTenantKey().isBlank() + || source.provenanceKind() == null + || source.provenanceKind().isBlank()) { + throw deny("AUTHORED_WORLD_SOURCE_CHANGED", "source evidence does not match the descriptor"); + } + } + + private void requireExactBundleBinding( + PublishedReleaseBundleDto bundle, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID snapshotCanonicalVersionId) { + if (bundle == null + || bundle.id() == null + || bundle.id() <= 0 + || bundle.versionId() == null + || bundle.versionId() <= 0 + || bundle.versionNumber() <= 0 + || bundle.canonicalTenantId() == null + || bundle.canonicalVersionId() == null + || NIL_UUID.equals(bundle.canonicalTenantId()) + || NIL_UUID.equals(bundle.canonicalVersionId()) + || snapshotCanonicalVersionId == null + || NIL_UUID.equals(snapshotCanonicalVersionId) + || !Objects.equals(snapshotCanonicalVersionId, bundle.canonicalVersionId()) + || !("v1".equals(bundle.attestationSchemaVersion()) + && bundle.worldPublishedStartLocationEvidence() == null + || "v2".equals(bundle.attestationSchemaVersion()) + && bundle.worldPublishedStartLocationEvidence() != null) + || !Objects.equals(bundle.id(), descriptor.releaseBundleId()) + || !Objects.equals(bundle.versionId(), descriptor.versionId()) + || !Objects.equals(bundle.tenantId(), source.sourceGameTenantKey()) + || !Objects.equals(bundle.canonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(bundle.generationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals( + bundle.publishedReleaseBundleRef(), descriptor.publishedReleaseBundleRef()) + || bundle.publishWorkflowId() == null + || bundle.publishWorkflowId().isBlank()) { + throw deny( + "RELEASE_ATTESTATION_MISMATCH", + "release bundle identity does not match the exact descriptor and source"); + } + } + + private Version requireCanonicalVersion( + PublishedReleaseBundleDto bundle, + AuthoredWorldSourceEvidence source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + AuthoredWorldVersionStateSnapshot sourceSnapshot) { + Version version = + versionRepository + .findByCanonicalTenantIdAndCanonicalVersionId( + bundle.canonicalTenantId(), bundle.canonicalVersionId()) + .orElseThrow( + () -> + deny( + "CANONICAL_VERSION_NOT_FOUND", + "release canonical Version identity has no exact persisted owner source")); + if (!Objects.equals(version.getId(), descriptor.versionId()) + || !Objects.equals(version.getTenantId(), source.sourceGameTenantKey()) + || !Objects.equals(version.getCanonicalTenantId(), source.canonicalTenantId()) + || !Objects.equals(version.getCanonicalVersionId(), bundle.canonicalVersionId()) + || !Objects.equals(version.getCanonicalVersionId(), sourceSnapshot.canonicalVersionId()) + || !Objects.equals(version.getIdentitySourceGameRowId(), source.sourceGameRowId()) + || !Objects.equals(version.getIdentitySourceGameTenantKey(), source.sourceGameTenantKey()) + || !Objects.equals(version.getIdentitySourceProvenanceKind(), source.provenanceKind()) + || !Objects.equals(version.getVersionNumber(), bundle.versionNumber()) + || version.getVersionState() != sourceSnapshot.versionState() + || !Objects.equals(version.getVersionStateEpoch(), sourceSnapshot.versionStateEpoch())) { + throw deny( + "CANONICAL_VERSION_MISMATCH", + "persisted Version UUID and Game source provenance do not match this release"); + } + return version; + } + + private void requireFullVersion(Version version, PublishedReleaseBundleDto bundle) { + if (version.isScriptOnly() + || version.getBaseVersionId() != null + || version.getScriptPatchVersion() != null + || bundle.scriptOnly() + || bundle.scriptPatchVersion() != null) { + throw deny( + "RELEASE_ATTESTATION_MISMATCH", + "a script-only publication cannot attest a full-Version launch descriptor"); + } + } + + private List requireParticipantEvidence( + PublishedReleaseBundleDto bundle, long versionId) { + List observed = bundle.participantDigests(); + List requiredParticipantOrder = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder(); + if (observed == null || observed.size() != requiredParticipantOrder.size()) { + throw deny( + "PARTICIPANT_EVIDENCE_INCOMPLETE", "exactly five full-Version owners are required"); + } + List participants = + new ArrayList<>(requiredParticipantOrder.size()); + String expectedScope = Long.toString(versionId); + String appliedCommitId = null; + for (int index = 0; index < requiredParticipantOrder.size(); index++) { + String expectedParticipantKey = requiredParticipantOrder.get(index); + int supportedDigestSchemaVersion = + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + expectedParticipantKey); + PublishParticipantDigestDto digest = observed.get(index); + if (digest == null + || !expectedParticipantKey.equals(digest.participantKey()) + || !expectedScope.equals(digest.scopeValue()) + || digest.baseVersionId() != null + || !digest.succeeded() + || (digest.errorMessage() != null && !digest.errorMessage().isBlank()) + || !isParticipantContentDigest(digest.contentDigest()) + || digest.digestSchemaVersion() == null + || digest.digestSchemaVersion() != supportedDigestSchemaVersion + || digest.appliedCommitId() == null + || digest.appliedCommitId().isBlank()) { + throw deny( + "PARTICIPANT_EVIDENCE_INVALID", + "full-Version participant evidence is missing, failed, unsupported, or out of order"); + } + if (appliedCommitId == null) { + appliedCommitId = digest.appliedCommitId(); + } else if (!appliedCommitId.equals(digest.appliedCommitId())) { + throw deny("PARTICIPANT_COMMIT_MISMATCH", "full-Version owners attest different commits"); + } + boolean abilityPresent = digest.abilitySchemaDigest() != null; + if ("GAME_LOGIC".equals(expectedParticipantKey)) { + if (!abilityPresent || !isDigest(digest.abilitySchemaDigest())) { + throw deny( + "ABILITY_SCHEMA_EVIDENCE_MISSING", + "Game Logic must provide its dedicated ability-schema digest"); + } + } else if (abilityPresent) { + throw deny( + "ABILITY_SCHEMA_EVIDENCE_OWNER_MISMATCH", + "only Game Logic may provide the ability-schema digest"); + } + participants.add( + new AuthoredWorldReleaseAttestationEvidence.Participant( + digest.participantKey(), + digest.scopeValue(), + false, + null, + digest.appliedCommitId(), + digest.contentDigest(), + digest.digestSchemaVersion(), + abilityPresent, + digest.abilitySchemaDigest())); + } + if (appliedCommitId == null || appliedCommitId.isBlank()) { + throw deny("PARTICIPANT_COMMIT_MISSING", "full-Version commit identity is missing"); + } + return List.copyOf(participants); + } + + private List requireManifestAndArtifactEvidence( + PublishedReleaseBundleDto bundle) { + if (!isDigest(bundle.manifestHash()) + || bundle.manifestSchemaVersion() == null + || bundle.manifestSchemaVersion() != SUPPORTED_MANIFEST_SCHEMA_VERSION + || bundle.requiredManifestAssetKeys() == null + || bundle.artifactDigests() == null + || bundle.commandDefinitions() == null + || bundle.commandDefinitions().stream().anyMatch(value -> value == null || value.isBlank()) + || bundle.generationConfigRevision() == null + || bundle.generationConfigRevision().isBlank()) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INCOMPLETE", + "manifest, required-key, actual-artifact, command, or generation proof is missing"); + } + List requiredKeys = bundle.requiredManifestAssetKeys(); + for (int index = 0; index < requiredKeys.size(); index++) { + String key = requiredKeys.get(index); + if (key == null + || key.isBlank() + || (index > 0 + && PublishedArtifactDigest.compareUsageKeysUtf8(requiredKeys.get(index - 1), key) + >= 0)) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INVALID", + "required manifest asset keys must be unique and in unsigned UTF-8 order"); + } + } + List observedArtifacts = bundle.artifactDigests(); + List artifacts = + new ArrayList<>(observedArtifacts.size()); + String previousUsageKey = null; + for (PublishedArtifactDigest artifact : observedArtifacts) { + if (artifact == null + || artifact.artifactSchemaVersion() != SUPPORTED_ARTIFACT_SCHEMA_VERSION + || (previousUsageKey != null + && PublishedArtifactDigest.compareUsageKeysUtf8(previousUsageKey, artifact.usageKey()) + >= 0)) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_INVALID", + "artifact entries must be unique and in unsigned UTF-8 usage-key order"); + } + previousUsageKey = artifact.usageKey(); + artifacts.add( + new AuthoredWorldReleaseAttestationEvidence.Artifact( + artifact.usageKey(), + artifact.artifactKind(), + artifact.immutableObjectKey(), + artifact.contentDigest(), + artifact.contentType(), + artifact.artifactSchemaVersion())); + } + for (String requiredKey : requiredKeys) { + long matches = + observedArtifacts.stream() + .filter(artifact -> requiredKey.equals(artifact.usageKey())) + .count(); + if (matches != 1) { + throw deny( + "MANIFEST_ARTIFACT_EVIDENCE_MISMATCH", + "each required manifest key must select exactly one actual-byte artifact proof"); + } + } + return List.copyOf(artifacts); + } + + private boolean isDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private boolean isParticipantContentDigest(String value) { + return value != null && value.matches("[0-9a-f]{64}"); + } + + private IllegalArgumentException deny(String code, String detail) { + return new IllegalArgumentException("COMPLETE_LAUNCH_BINDING_" + code + ": " + detail); + } + + private IllegalArgumentException deny(String code, String detail, Throwable cause) { + return new IllegalArgumentException("COMPLETE_LAUNCH_BINDING_" + code + ": " + detail, cause); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java new file mode 100644 index 0000000000..5bc425144a --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/FrozenLaunchDescriptorDenialException.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +/** A deterministic launch business denial whose exact request outcome is stored by the owner. */ +final class FrozenLaunchDescriptorDenialException extends IllegalArgumentException { + private final String failureCode; + + static FrozenLaunchDescriptorDenialException create(String failureCode, String detail) { + return new FrozenLaunchDescriptorDenialException(failureCode, failureCode + ": " + detail); + } + + private FrozenLaunchDescriptorDenialException(String failureCode, String message) { + super(message); + this.failureCode = failureCode; + } + + static FrozenLaunchDescriptorDenialException fromStored(String failureCode, String message) { + return new FrozenLaunchDescriptorDenialException(failureCode, message); + } + + String failureCode() { + return failureCode; + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 24087faa9f..4f961b469a 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -8,12 +8,16 @@ import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.List; +import java.util.UUID; import lombok.RequiredArgsConstructor; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; 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.common.settings.GameDesignSettingsProtoMapper; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; import net.firedevops.firemud.gamedesign.dto.HelpTopicDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; @@ -23,6 +27,7 @@ import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; @@ -52,8 +57,11 @@ import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsRequest; import net.firedevops.firemud.gamedesign.v1.FinalizePurgeVersionAssetsResponse; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; @@ -117,6 +125,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.grpc.server.service.GrpcService; @GrpcService @@ -127,12 +136,16 @@ public class GameDesignGrpcService extends GameDesignServiceGrpc.GameDesignServi private final RevisionService revisionService; private final VersionService versionService; private final LaunchDescriptorService launchDescriptorService; + private final CompleteLaunchBindingService completeLaunchBindingService; private final TemplateRemapSetService templateRemapSetService; private final VersionAssetArtifactService versionAssetArtifactService; private final SettingsAuthorityService settingsAuthorityService; private final GameAuthoredHelpTopicService gameAuthoredHelpTopicService; private final TemporalVersionPublishWorkflowMetadataResolver publishWorkflowMetadataResolver; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "MeterRegistry is injected and not exposed") @@ -857,36 +870,38 @@ public void resolveLaunchDescriptor( StreamObserver responseObserver) { ResolveLaunchDescriptorResponse.Builder builder = ResolveLaunchDescriptorResponse.newBuilder(); try { - requireLaunchAttestationReadAccess(); - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - request.getTenantId(), - request.getGameTemplateId(), + requireLaunchDescriptorResolveAccess(); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + UUID sourceOperationId = + parseCanonicalNonNilUuid(request.getAuthoredWorldSourceOperationId()); + if (canonicalTenantId == null + || sourceOperationId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed canonical authored-world request is required"); + } + AuthoredWorldLaunchDescriptorEvidence.Request bindingRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + workloadNamespace, request.getControlPlaneRequestId(), + canonicalTenantId, + request.getWorldSlug(), + sourceOperationId, + request.getExpectedAuthoredWorldSourceEvidenceDigest(), + request.getGameTemplateId(), + request.hasRequestedScriptPatchVersion(), request.hasRequestedScriptPatchVersion() ? request.getRequestedScriptPatchVersion() : null, + request.hasSourceVersionId(), request.hasSourceVersionId() ? request.getSourceVersionId() : null, + request.hasTargetVersionId(), request.hasTargetVersionId() ? request.getTargetVersionId() : null, + request.hasRequestedRuntimeFlagsJson(), request.hasRequestedRuntimeFlagsJson() ? request.getRequestedRuntimeFlagsJson() : null); - builder.setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setTenantId(descriptor.tenantId()) - .setGameTemplateId(descriptor.gameTemplateId()) - .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setVersionId(descriptor.versionId()) - .setScriptPatchVersion( - descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) - .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) - .setGenerationConfigRevision(descriptor.generationConfigRevision()) - .setVersionStateEpoch(descriptor.versionStateEpoch()) - .setReleaseBundleId(descriptor.releaseBundleId()) - .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) - .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) - .build()); + var descriptor = launchDescriptorService.resolveLaunchDescriptor(bindingRequest); + builder.setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -909,7 +924,7 @@ public void resolveLaunchDescriptor( meterRegistry, logger, "ResolveLaunchDescriptor", - launchDescriptorErrorCode(ex.getMessage(), false), + launchDescriptorErrorCode(ex.getMessage(), true), ex.getMessage())); } catch (Exception ex) { builder.setError( @@ -919,6 +934,130 @@ public void resolveLaunchDescriptor( responseObserver.onCompleted(); } + @Override + @Timed(value = "gamedesignGrpc.getLaunchDescriptor") + public void getLaunchDescriptor( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetLaunchDescriptorResponse.Builder builder = GetLaunchDescriptorResponse.newBuilder(); + try { + requireLaunchDescriptorReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Canonical exact launch descriptor read is required"); + } + var descriptor = + launchDescriptorService.getLaunchDescriptor( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(toProtoLaunchDescriptor(descriptor)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, logger, "GetLaunchDescriptor", "PERMISSION_DENIED", ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetLaunchDescriptor", + launchDescriptorErrorCode(ex.getMessage(), true), + ex.getMessage())); + } catch (Exception ex) { + builder.setError(GrpcAppErrors.internal(meterRegistry, logger, "GetLaunchDescriptor", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "gamedesignGrpc.getCompleteLaunchBinding") + public void getCompleteLaunchBinding( + GetLaunchDescriptorRequest request, + StreamObserver responseObserver) { + GetCompleteLaunchBindingResponse.Builder builder = + GetCompleteLaunchBindingResponse.newBuilder(); + try { + requireCompleteLaunchBindingReadAccess(); + UUID readRequestId = parseCanonicalNonNilUuid(request.getRequestId()); + UUID canonicalTenantId = parseCanonicalNonNilUuid(request.getCanonicalTenantId()); + if (readRequestId == null + || canonicalTenantId == null + || request.getWorldSlug().isBlank() + || request.getControlPlaneRequestId().isBlank() + || request.getExpectedRequestDigest().isBlank() + || request.getExpectedResultDigest().isBlank() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException( + "Canonical exact complete launch binding read is required"); + } + CompleteLaunchBindingDto binding = + completeLaunchBindingService.getCompleteLaunchBinding( + readRequestId, + canonicalTenantId, + request.getWorldSlug(), + request.getControlPlaneRequestId(), + request.getExpectedRequestDigest(), + request.getExpectedResultDigest()); + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence = binding.descriptor(); + var descriptorDto = + new net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto( + descriptorEvidence.launchDescriptorId(), + descriptorEvidence.canonicalTenantId().toString(), + descriptorEvidence.gameTemplateId(), + descriptorEvidence.controlPlaneRequestId(), + descriptorEvidence.versionId(), + descriptorEvidence.scriptPatchVersionPresent() + ? descriptorEvidence.scriptPatchVersion() + : null, + descriptorEvidence.runtimeFlagsJson(), + descriptorEvidence.generationConfigRevision(), + descriptorEvidence.versionStateEpoch(), + descriptorEvidence.releaseBundleId(), + descriptorEvidence.publishedReleaseBundleRef(), + descriptorEvidence.remapSetIdPresent() ? descriptorEvidence.remapSetId() : null, + descriptorEvidence); + var protoDescriptor = toProtoLaunchDescriptor(descriptorDto); + var protoReleaseAttestation = + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec + .toReleaseAttestation(binding.releaseAttestation()); + builder + .setRequestId(readRequestId.toString()) + .setLaunchDescriptor(protoDescriptor) + .setReleaseAttestation(protoReleaseAttestation); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + "PERMISSION_DENIED", + ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "GetCompleteLaunchBinding", + completeLaunchBindingErrorCode(ex.getMessage()), + ex.getMessage())); + } catch (Exception ex) { + builder.setError( + GrpcAppErrors.internal(meterRegistry, logger, "GetCompleteLaunchBinding", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "gamedesignGrpc.createTemplateRemapSet") public void createTemplateRemapSet( @@ -1968,9 +2107,141 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu return prefix; } } + if (message.startsWith("AUTHORED_WORLD_SOURCE_NOT_FOUND") + || message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { + return "NOT_FOUND"; + } + if (message.startsWith("AUTHORED_WORLD_SOURCE_") + || message.startsWith("LAUNCH_DESCRIPTOR_")) { + return "FAILED_PRECONDITION"; + } return "INVALID_ARGUMENT"; } + private String completeLaunchBindingErrorCode(String message) { + if (message != null && message.startsWith("COMPLETE_LAUNCH_BINDING_")) { + int delimiter = message.indexOf(':'); + if (delimiter > 0) { + return message.substring(0, delimiter); + } + } + return launchDescriptorErrorCode(message, true); + } + + private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescriptor( + net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto descriptor) { + AuthoredWorldLaunchDescriptorEvidence evidence = descriptor.authoredWorldBinding(); + if (evidence == null) { + throw new IllegalStateException("Bound authored-world launch evidence is required"); + } + evidence.requireValid(); + var binding = + net.firedevops.firemud.gamedesign.v1.AuthoredWorldLaunchDescriptorEvidence.newBuilder() + .setSchemaVersion(evidence.schemaVersion()) + .setTargetNamespace(evidence.targetNamespace()) + .setControlPlaneRequestId(evidence.controlPlaneRequestId()) + .setCanonicalTenantId(evidence.canonicalTenantId().toString()) + .setWorldSlug(evidence.worldSlug()) + .setAuthoredWorldSourceOperationId(evidence.authoredWorldSourceOperationId().toString()) + .setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()) + .setGameTemplateId(evidence.gameTemplateId()) + .setRequestDigest(evidence.requestDigest()) + .setLaunchDescriptorId(evidence.launchDescriptorId()) + .setVersionId(evidence.versionId()) + .setRuntimeFlagsJson(evidence.runtimeFlagsJson()) + .setGenerationConfigRevision(evidence.generationConfigRevision()) + .setVersionStateEpoch(evidence.versionStateEpoch()) + .setReleaseBundleId(evidence.releaseBundleId()) + .setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()) + .setResultDigest(evidence.resultDigest()); + if (evidence.requestedScriptPatchVersionPresent()) { + binding.setRequestedScriptPatchVersion(evidence.requestedScriptPatchVersion()); + } + if (evidence.sourceVersionIdPresent()) { + binding.setSourceVersionId(evidence.sourceVersionId()); + } + if (evidence.targetVersionIdPresent()) { + binding.setTargetVersionId(evidence.targetVersionId()); + } + if (evidence.requestedRuntimeFlagsJsonPresent()) { + binding.setRequestedRuntimeFlagsJson(evidence.requestedRuntimeFlagsJson()); + } + if (evidence.scriptPatchVersionPresent()) { + binding.setScriptPatchVersion(evidence.scriptPatchVersion()); + } + if (evidence.remapSetIdPresent()) { + binding.setRemapSetId(evidence.remapSetId()); + } + return net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId(descriptor.launchDescriptorId()) + .setCanonicalTenantId(descriptor.tenantId()) + .setGameTemplateId(descriptor.gameTemplateId()) + .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setVersionId(descriptor.versionId()) + .setScriptPatchVersion( + descriptor.scriptPatchVersion() == null ? "" : descriptor.scriptPatchVersion()) + .setRuntimeFlagsJson(descriptor.runtimeFlagsJson()) + .setGenerationConfigRevision(descriptor.generationConfigRevision()) + .setVersionStateEpoch(descriptor.versionStateEpoch()) + .setReleaseBundleId(descriptor.releaseBundleId()) + .setPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()) + .setRemapSetId(descriptor.remapSetId() == null ? "" : descriptor.remapSetId()) + .setAuthoredWorldBinding(binding.build()) + .build(); + } + + private UUID parseCanonicalNonNilUuid(String value) { + if (value == null) { + return null; + } + try { + UUID parsed = UUID.fromString(value); + return parsed.toString().equals(value) && !parsed.equals(new UUID(0L, 0L)) ? parsed : null; + } catch (IllegalArgumentException exception) { + return null; + } + } + + private void requireLaunchDescriptorResolveAccess() { + requireExactWorkloadPeer("game-session-service"); + } + + private void requireLaunchDescriptorReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session or World Management workload identity is required"); + } + } + + private void requireCompleteLaunchBindingReadAccess() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !(peer.isService("game-session-service") + || peer.isService("world-management-service") + || peer.isService("entity-management-service"))) { + throw new AdminAuthorizationException( + "Exact same-namespace Game Session, World Management, or Entity Management workload identity is required"); + } + } + + private void requireExactWorkloadPeer(String service) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || peer == null + || !workloadNamespace.equals(peer.namespace()) + || !peer.isService(service)) { + throw new AdminAuthorizationException( + "Exact same-namespace workload identity is required for launch descriptor resolution"); + } + } + private String remapSetErrorCode(String message) { if (message == null || message.isBlank()) { return "INVALID_ARGUMENT"; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 5b2c3139bb..f295ad77fc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -1,20 +1,23 @@ package net.firedevops.firemud.gamedesign.service.impl; import io.micrometer.core.annotation.Timed; -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.LinkedHashMap; -import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.UUID; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.common.LoggingUtil; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -22,249 +25,666 @@ import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; -import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import tools.jackson.core.exc.StreamReadException; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; @Service @RequiredArgsConstructor public class LaunchDescriptorServiceImpl implements LaunchDescriptorService { - private static final Logger logger = LoggingUtil.getLogger(LaunchDescriptorServiceImpl.class); - + private static final UUID NIL_UUID = new UUID(0L, 0L); private final GameTemplateRepository gameTemplateRepository; private final LaunchDescriptorRepository launchDescriptorRepository; private final VersionRepository versionRepository; private final PublishedReleaseBundleService publishedReleaseBundleService; private final TemplateRemapSetService templateRemapSetService; + private final GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private final ObjectMapper objectMapper; + @Value("${firemud.grpc.workload-namespace:}") + private String workloadNamespace; + @Override - @Transactional + @Transactional(noRollbackFor = FrozenLaunchDescriptorDenialException.class) @Timed(value = "gamedesign.launchDescriptor.resolve") public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + AuthoredWorldLaunchDescriptorEvidence.Request request) { + requireConfiguredNamespace(request.targetNamespace()); + launchDescriptorRepository.lockBoundRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + String requestJson = writeJson(request); + + Optional stored = + launchDescriptorRepository.findBoundByRequest( + workloadNamespace, request.canonicalTenantId(), request.controlPlaneRequestId()); + if (stored.isPresent()) { + LaunchDescriptor descriptor = stored.orElseThrow(); + requireStoredRequestMatches(descriptor, request, requestJson); + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { + throwStoredFailure( + descriptor, request, requestJson, sourceJson, source.sourceGameTenantKey()); + } + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); + } + return readStored(descriptor, request, requestJson, sourceJson); + } + AuthoredWorldSourceEvidence source = readExactSource(request); + String sourceJson = writeJson(source); + if (launchDescriptorRepository + .findByPrivateRequest(source.sourceGameTenantKey(), request.controlPlaneRequestId()) + .isPresent()) { throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId is required"); + "LAUNCH_DESCRIPTOR_CONFLICT: retained private-owner request history is unbound or bound to another canonical identity"); + } + + try { + return resolveNewLaunchDescriptor(request, source, requestJson, sourceJson); + } catch (FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor failure = frozenFailure(request, source, requestJson, sourceJson, denial); + LaunchDescriptor persisted = launchDescriptorRepository.insertImmutable(failure); + throwStoredFailure(persisted, request, requestJson, sourceJson, source.sourceGameTenantKey()); + throw new IllegalStateException("Persisted deterministic launch denial was not returned"); } + } + + private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson) { GameTemplateLaunchConfigView template = gameTemplateRepository - .findLaunchConfigByTenantIdAndId(tenantId, gameTemplateId) + .findLaunchConfigByTenantIdAndId(source.sourceGameTenantKey(), request.gameTemplateId()) + .filter(row -> row.getId() == request.gameTemplateId()) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: game template not found")); - String requestHash = - hashRequest( - tenantId, - gameTemplateId, - controlPlaneRequestId, - requestedScriptPatchVersion, - sourceVersionId, - targetVersionId, - requestedRuntimeFlagsJson); - var existing = - launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - tenantId, gameTemplateId, controlPlaneRequestId); - if (existing.isPresent()) { - if (!existing.get().getRequestHash().equals(requestHash)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: controlPlaneRequestId already resolved with different inputs"); - } - return toDto(existing.get()); - } + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "template is not owned by the source game")); if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { - throw new IllegalArgumentException( - "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + throw denial( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", "template reference phase is not enforced"); } - Long resolvedVersionId = - targetVersionId != null ? targetVersionId : template.getDefaultVersionId(); - if (resolvedVersionId == null || resolvedVersionId <= 0L) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template defaultVersionId is required"); + Long versionId = + request.targetVersionIdPresent() + ? request.targetVersionId() + : template.getDefaultVersionId(); + if (versionId == null || versionId <= 0) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "template defaultVersionId is required"); } VersionDto version = versionRepository - .findById(resolvedVersionId) - .filter(found -> found.getTenantId().equals(tenantId)) + .findById(versionId) + .filter(row -> row.getId().equals(versionId)) + .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) .map( - found -> + row -> new VersionDto( - found.getId(), - found.getTenantId(), - found.getVersionNumber(), - found.getVersionState(), - found.getVersionStateEpoch(), - found.getScriptPatchVersion(), - found.getBaseVersionId(), - found.isScriptOnly(), - found.getNotes(), - found.getCreatedAt(), - found.getUpdatedAt())) + row.getId(), + row.getTenantId(), + row.getVersionNumber(), + row.getVersionState(), + row.getVersionStateEpoch(), + row.getScriptPatchVersion(), + row.getBaseVersionId(), + row.isScriptOnly(), + row.getNotes(), + row.getCreatedAt(), + row.getUpdatedAt())) .orElseThrow( () -> - new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: target version not found")); + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "target version is not owned by the source game")); if (version.versionState() != VersionLifecycleState.PUBLISHED && version.versionState() != VersionLifecycleState.ACTIVE) { - throw new IllegalArgumentException( - "VERSION_STATE_EPOCH_STALE: resolved version is not activation-eligible"); + throw denial("VERSION_STATE_EPOCH_STALE", "resolved version is not activation-eligible"); } - String resolvedScriptPatchVersion = - resolveScriptPatchVersion(template, requestedScriptPatchVersion, version); - String resolvedRuntimeFlagsJson = resolveRuntimeFlagsJson(template, requestedRuntimeFlagsJson); + requireReadyScriptPatch( + request.requestedScriptPatchVersionPresent() + ? request.requestedScriptPatchVersion() + : null); + requireReadyScriptPatch(template.getDefaultScriptPatchVersion()); + requireReadyScriptPatch(version.scriptPatchVersion()); + String scriptPatch = resolveScriptPatchVersion(template, request, version); + String runtimeFlags = resolveRuntimeFlagsJson(template, request); + String remapSetId = null; - if (sourceVersionId != null && !sourceVersionId.equals(resolvedVersionId)) { - TemplateRemapSetDto remapSet = + if (request.sourceVersionIdPresent() && !request.sourceVersionId().equals(versionId)) { + TemplateRemapSetDto remap = templateRemapSetService - .findApprovedTemplateRemapSet(tenantId, sourceVersionId, resolvedVersionId) + .findApprovedTemplateRemapSet( + source.sourceGameTenantKey(), request.sourceVersionId(), versionId) .orElseThrow( () -> - new IllegalArgumentException( - "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); - remapSetId = remapSet.remapSetId(); + denial( + "LAUNCH_REMAP_REQUIRED", + "replacement-instance launch requires an approved remapSetId")); + remapSetId = remap.remapSetId(); + } + PublishedReleaseBundleDto bundle = + requirePublishedReleaseBundle(source.sourceGameTenantKey(), versionId); + if (!source.sourceGameTenantKey().equals(bundle.tenantId()) + || !Objects.equals(bundle.versionId(), versionId)) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "release bundle is not owned by the resolved source version"); + } + try { + PublishedReleaseBundleContract.requireSupportedSchemaForLaunchDescriptor(bundle); + } catch (IllegalArgumentException invalid) { + if (invalid.getMessage() != null + && invalid + .getMessage() + .startsWith(PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED + ":")) { + throw denial( + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED, + "unsupported published release bundle attestation schema " + + bundle.attestationSchemaVersion()); + } + throw invalid; } - var bundle = requirePublishedReleaseBundle(tenantId, resolvedVersionId); - PublishedReleaseBundleContract.requireSupportedSchemaForLaunch(bundle); + if (bundle.publishedReleaseBundleRef() == null + || bundle.publishedReleaseBundleRef().isBlank()) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "published release bundle has no persisted opaque reference"); + } + + String descriptorId = "ld-" + UUID.randomUUID(); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptorId, + versionId, + scriptPatch != null, + scriptPatch, + runtimeFlags, + bundle.generationConfigRevision(), + version.versionStateEpoch(), + bundle.id(), + bundle.publishedReleaseBundleRef(), + remapSetId != null, + remapSetId); LaunchDescriptor descriptor = new LaunchDescriptor(); - descriptor.setLaunchDescriptorId("ld-" + UUID.randomUUID()); - descriptor.setTenantId(tenantId); - descriptor.setGameTemplateId(gameTemplateId); - descriptor.setControlPlaneRequestId(controlPlaneRequestId); - descriptor.setRequestHash(requestHash); - descriptor.setVersionId(resolvedVersionId); - descriptor.setScriptPatchVersion(resolvedScriptPatchVersion); - descriptor.setRuntimeFlagsJson(resolvedRuntimeFlagsJson); + descriptor.setLaunchDescriptorId(descriptorId); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(versionId); + descriptor.setScriptPatchVersion(scriptPatch); + descriptor.setRuntimeFlagsJson(runtimeFlags); descriptor.setGenerationConfigRevision(bundle.generationConfigRevision()); descriptor.setVersionStateEpoch(version.versionStateEpoch()); descriptor.setReleaseBundleId(bundle.id()); - descriptor.setPublishedReleaseBundleRef( - releaseBundleRef(tenantId, bundle.id(), resolvedVersionId)); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); descriptor.setRemapSetId(remapSetId); - logger.info( - "Resolved launch descriptor tenant={} template={} controlPlaneRequestId={} version={} remapSetId={}", - tenantId, - gameTemplateId, - controlPlaneRequestId, - resolvedVersionId, - remapSetId); - return toDto(launchDescriptorRepository.save(descriptor)); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + return readStored( + launchDescriptorRepository.insertImmutable(descriptor), request, requestJson, sourceJson); + } + + @Override + @Transactional(readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.read") + public ResolvedLaunchDescriptorDto getLaunchDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + AuthoredWorldSourceEvidence source = readExactSource(storedRequest); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + @Override + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + @Timed(value = "gamedesign.launchDescriptor.readOwnerSnapshot") + public ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + requireOwnerSnapshot(); + DescriptorReadContext context = + findExactSuccessfulDescriptor( + readRequestId, + canonicalTenantId, + worldSlug, + controlPlaneRequestId, + expectedRequestDigest, + expectedResultDigest); + LaunchDescriptor descriptor = context.descriptor(); + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = context.request(); + var sourceSnapshot = + authoredWorldSourceRepository + .readVersionStateSnapshot( + workloadNamespace, + readRequestId, + canonicalTenantId, + worldSlug, + storedRequest.authoredWorldSourceOperationId(), + storedRequest.authoredWorldSourceEvidenceDigest(), + Objects.requireNonNull(descriptor.getVersionId(), "descriptor versionId")) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source or version is missing")); + AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); + requireExactSource(storedRequest, source); + String sourceJson = writeJson(source); + if (!sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !Objects.equals(source.sourceGameTenantKey(), descriptor.getTenantId())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: committed source differs from descriptor history"); + } + return readStored( + descriptor, + storedRequest, + descriptor.getOriginalRequestJson(), + descriptor.getSourceEvidenceJson()); + } + + private DescriptorReadContext findExactSuccessfulDescriptor( + UUID readRequestId, + UUID canonicalTenantId, + String worldSlug, + String controlPlaneRequestId, + String expectedRequestDigest, + String expectedResultDigest) { + if (readRequestId == null || NIL_UUID.equals(readRequestId)) { + throw new IllegalArgumentException("Canonical nonnil read request ID is required"); + } + requireConfiguredNamespace(workloadNamespace); + AuthoredWorldSourceDigest.validateReadSelector(workloadNamespace, canonicalTenantId, worldSlug); + if (controlPlaneRequestId == null + || controlPlaneRequestId.isBlank() + || !GameTenantCreationDigest.isDigest(expectedRequestDigest) + || !GameTenantCreationDigest.isDigest(expectedResultDigest)) { + throw new IllegalArgumentException("Exact descriptor read selector and digests are required"); + } + LaunchDescriptor descriptor = + launchDescriptorRepository + .findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId) + .orElseThrow( + () -> + new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NOT_FOUND: no descriptor exists for the exact request")); + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: request outcome is not a successful descriptor"); + } + if (descriptor.getDescriptorSchemaVersion() == null) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: retained descriptor history has no authored-world binding"); + } + if (!worldSlug.equals(descriptor.getWorldSlug()) + || !canonicalTenantId.toString().equals(descriptor.getCanonicalTenantId()) + || !expectedRequestDigest.equals(descriptor.getRequestDigest()) + || !expectedResultDigest.equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match"); + } + AuthoredWorldLaunchDescriptorEvidence.Request storedRequest = + readRequest(descriptor.getOriginalRequestJson()); + return new DescriptorReadContext(descriptor, storedRequest); + } + + private AuthoredWorldSourceEvidence readExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + AuthoredWorldSourceEvidence source = + authoredWorldSourceRepository + .read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); + requireExactSource(request, source); + return source; + } + + private void requireExactSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { + if (!workloadNamespace.equals(source.targetNamespace()) + || !request.canonicalTenantId().equals(source.canonicalTenantId()) + || !request.worldSlug().equals(source.worldSlug()) + || !request.authoredWorldSourceOperationId().equals(source.operationId()) + || !request.authoredWorldSourceEvidenceDigest().equals(source.evidenceDigest())) { + throw new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_CHANGED: source evidence does not match the exact request"); + } + } + + private void requireOwnerSnapshot() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(TransactionDefinition.ISOLATION_REPEATABLE_READ) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException( + "Launch descriptor snapshot read requires a read-only REPEATABLE_READ owner snapshot"); + } + } + + private record DescriptorReadContext( + LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request) {} + + private ResolvedLaunchDescriptorDto readStored( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson) { + if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + || descriptor.getFailureCode() != null + || descriptor.getFailureMessage() != null + || descriptor.getDescriptorSchemaVersion() == null + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || request.gameTemplateId() != descriptor.getGameTemplateId() + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !request.requestDigest().equals(descriptor.getRequestDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request"); + } + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion() != null, + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getVersionStateEpoch(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getRemapSetId() != null, + descriptor.getRemapSetId()); + evidence.requireValid(); + if (!evidence.resultDigest().equals(descriptor.getResultDigest())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent"); + } + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private LaunchDescriptor frozenFailure( + AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, + String requestJson, + String sourceJson, + FrozenLaunchDescriptorDenialException denial) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setTenantId(source.sourceGameTenantKey()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(request.requestDigest()); + descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + descriptor.setTargetNamespace(workloadNamespace); + descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); + descriptor.setWorldSlug(request.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + request.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(request.requestDigest()); + descriptor.setOriginalRequestJson(requestJson); + descriptor.setSourceEvidenceJson(sourceJson); + descriptor.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + descriptor.setFailureCode(denial.failureCode()); + descriptor.setFailureMessage(denial.getMessage()); + return descriptor; + } + + private void requireStoredRequestMatches( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson) { + if (!workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input"); + } + } + + private void throwStoredFailure( + LaunchDescriptor descriptor, + AuthoredWorldLaunchDescriptorEvidence.Request request, + String requestJson, + String sourceJson, + String sourceGameTenantKey) { + if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + || !Objects.equals( + descriptor.getDescriptorSchemaVersion(), + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) + || !workloadNamespace.equals(descriptor.getTargetNamespace()) + || !request.canonicalTenantId().toString().equals(descriptor.getCanonicalTenantId()) + || !request.worldSlug().equals(descriptor.getWorldSlug()) + || !request + .authoredWorldSourceOperationId() + .toString() + .equals(descriptor.getAuthoredWorldSourceOperationId()) + || !request + .authoredWorldSourceEvidenceDigest() + .equals(descriptor.getAuthoredWorldSourceEvidenceDigest()) + || !request.controlPlaneRequestId().equals(descriptor.getControlPlaneRequestId()) + || !request.requestDigest().equals(descriptor.getRequestDigest()) + || !request.requestDigest().equals(descriptor.getRequestHash()) + || !requestJson.equals(descriptor.getOriginalRequestJson()) + || !sourceJson.equals(descriptor.getSourceEvidenceJson()) + || !sourceGameTenantKey.equals(descriptor.getTenantId()) + || descriptor.getLaunchDescriptorId() != null + || descriptor.getGameTemplateId() != null + || descriptor.getVersionId() != null + || descriptor.getScriptPatchVersion() != null + || descriptor.getRuntimeFlagsJson() != null + || descriptor.getGenerationConfigRevision() != null + || descriptor.getVersionStateEpoch() != null + || descriptor.getReleaseBundleId() != null + || descriptor.getPublishedReleaseBundleRef() != null + || descriptor.getRemapSetId() != null + || descriptor.getResultDigest() != null + || !isPersistableFailureCode(descriptor.getFailureCode()) + || descriptor.getFailureMessage() == null + || descriptor.getFailureMessage().isBlank()) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_CONFLICT: stored failure is not the exact immutable request outcome"); + } + throw FrozenLaunchDescriptorDenialException.fromStored( + descriptor.getFailureCode(), descriptor.getFailureMessage()); + } + + private boolean isPersistableFailureCode(String failureCode) { + return switch (failureCode == null ? "" : failureCode) { + case "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", + "INVALID_TEMPLATE_CONFIGURATION", + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "SCRIPT_PATCH_NOT_READY", + "RELEASE_BUNDLE_NOT_FOUND", + "RELEASE_ATTESTATION_MISMATCH", + "VERSION_STATE_EPOCH_STALE", + "LAUNCH_REMAP_REQUIRED", + PublishedReleaseBundleContract.SCHEMA_VERSION_UNSUPPORTED -> + true; + default -> false; + }; + } + + private static FrozenLaunchDescriptorDenialException denial(String code, String detail) { + return FrozenLaunchDescriptorDenialException.create(code, detail); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request readRequest(String json) { + if (json == null) { + throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_UNBOUND: original request is missing"); + } + try { + AuthoredWorldLaunchDescriptorEvidence.Request request = + objectMapper.readValue(json, AuthoredWorldLaunchDescriptorEvidence.Request.class); + if (!writeJson(request).equals(json)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is not the closed owner encoding"); + } + return request; + } catch (Exception exception) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_UNBOUND: original request is unreadable", exception); + } + } + + private String writeJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException( + "Launch descriptor evidence could not be serialized", exception); + } + } + + private void requireConfiguredNamespace(String requestNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !workloadNamespace.equals(requestNamespace)) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NAMESPACE_MISMATCH: configured workload namespace is required"); + } } private String resolveScriptPatchVersion( GameTemplateLaunchConfigView template, - String requestedScriptPatchVersion, + AuthoredWorldLaunchDescriptorEvidence.Request request, VersionDto version) { String templateDefault = normalizeBlank(template.getDefaultScriptPatchVersion()); - String requested = normalizeBlank(requestedScriptPatchVersion); + String requested = + request.requestedScriptPatchVersionPresent() + ? normalizeBlank(request.requestedScriptPatchVersion()) + : null; if (templateDefault != null && requested != null && !templateDefault.equals(requested)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_OVERRIDE_CONFLICT: requested script patch conflicts with template default"); + throw denial( + "SCRIPT_PATCH_OVERRIDE_CONFLICT", + "requested script patch conflicts with template default"); } String resolved = requested != null ? requested : templateDefault; if (resolved != null && version.scriptPatchVersion() != null && !version.scriptPatchVersion().isBlank() && !version.scriptPatchVersion().equals(resolved)) { - throw new IllegalArgumentException( - "SCRIPT_PATCH_NOT_READY: requested script patch is not published for the resolved version"); + throw denial( + "SCRIPT_PATCH_NOT_READY", + "requested script patch is not published for the resolved version"); } return resolved; } private String resolveRuntimeFlagsJson( - GameTemplateLaunchConfigView template, String requestedRuntimeFlagsJson) { + GameTemplateLaunchConfigView template, + AuthoredWorldLaunchDescriptorEvidence.Request request) { String templateFlags = normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null ? "{}" : template.getDefaultRuntimeFlagsJson(); - String requested = normalizeBlank(requestedRuntimeFlagsJson); + String requested = + request.requestedRuntimeFlagsJsonPresent() + ? normalizeBlank(request.requestedRuntimeFlagsJson()) + : null; if (requested == null) { return templateFlags; } if (!"{}".equals(templateFlags)) { - throw new IllegalArgumentException( - "INVALID_TEMPLATE_CONFIGURATION: template-owned runtime flags cannot be overridden"); + throw denial( + "INVALID_TEMPLATE_CONFIGURATION", "template-owned runtime flags cannot be overridden"); } return requested; } - private net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto - requirePublishedReleaseBundle(String tenantId, long resolvedVersionId) { - try { - return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, resolvedVersionId); - } catch (PublishedReleaseBundleNotFoundException ex) { - throw new IllegalArgumentException( - "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version"); + private void requireReadyScriptPatch(String scriptPatchVersion) { + if (scriptPatchVersion != null && !scriptPatchVersion.isBlank()) { + throw denial( + "SCRIPT_PATCH_NOT_READY", + "exact published-for-base and Automation READY evidence is unavailable"); } } - private ResolvedLaunchDescriptorDto toDto(LaunchDescriptor descriptor) { - return new ResolvedLaunchDescriptorDto( - descriptor.getLaunchDescriptorId(), - descriptor.getTenantId(), - descriptor.getGameTemplateId(), - descriptor.getControlPlaneRequestId(), - descriptor.getVersionId(), - descriptor.getScriptPatchVersion(), - descriptor.getRuntimeFlagsJson(), - descriptor.getGenerationConfigRevision(), - descriptor.getVersionStateEpoch(), - descriptor.getReleaseBundleId(), - descriptor.getPublishedReleaseBundleRef(), - descriptor.getRemapSetId()); - } - - private String hashRequest( - String tenantId, - long gameTemplateId, - String controlPlaneRequestId, - String requestedScriptPatchVersion, - Long sourceVersionId, - Long targetVersionId, - String requestedRuntimeFlagsJson) { - Map request = new LinkedHashMap<>(); - request.put("tenantId", tenantId); - request.put("gameTemplateId", gameTemplateId); - request.put("controlPlaneRequestId", controlPlaneRequestId); - request.put("requestedScriptPatchVersion", normalizeBlank(requestedScriptPatchVersion)); - request.put("sourceVersionId", sourceVersionId); - request.put("targetVersionId", targetVersionId); - request.put("requestedRuntimeFlagsJson", normalizeBlank(requestedRuntimeFlagsJson)); + private PublishedReleaseBundleDto requirePublishedReleaseBundle(String tenantId, long versionId) { try { - return sha256(objectMapper.writeValueAsString(request)); - } catch (StreamReadException | tools.jackson.databind.DatabindException ex) { - throw new IllegalStateException("failed to hash launch descriptor request", ex); - } - } - - private String releaseBundleRef(String tenantId, long bundleId, long versionId) { - return "prb:" + tenantId + ":" + versionId + ":" + bundleId; - } - - private String sha256(String value) { - try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] bytes = digest.digest(value.getBytes(StandardCharsets.UTF_8)); - StringBuilder builder = new StringBuilder(bytes.length * 2); - for (byte current : bytes) { - builder.append(String.format("%02x", current)); - } - return builder.toString(); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("sha-256 unavailable", ex); + return publishedReleaseBundleService.getPublishedReleaseBundle(tenantId, versionId); + } catch (PublishedReleaseBundleNotFoundException exception) { + throw denial( + "RELEASE_BUNDLE_NOT_FOUND", "no published release bundle for the resolved version"); } } - private String normalizeBlank(String value) { + private static String normalizeBlank(String value) { return value == null || value.isBlank() ? null : value; } } diff --git a/services/game-design-service/src/main/resources/application-prod.yml b/services/game-design-service/src/main/resources/application-prod.yml index 4c8251d4e5..5f2bc1c4f4 100644 --- a/services/game-design-service/src/main/resources/application-prod.yml +++ b/services/game-design-service/src/main/resources/application-prod.yml @@ -51,6 +51,11 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy + - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies + - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor + - gamedesign.v1.GameDesignService/GetLaunchDescriptor + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} diff --git a/services/game-design-service/src/main/resources/application.yml b/services/game-design-service/src/main/resources/application.yml index cfa32714ea..a3b28b19a9 100644 --- a/services/game-design-service/src/main/resources/application.yml +++ b/services/game-design-service/src/main/resources/application.yml @@ -62,6 +62,11 @@ firemud: grpc: public-methods: - gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation + - game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy + - game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies + - gamedesign.v1.GameDesignService/ResolveLaunchDescriptor + - gamedesign.v1.GameDesignService/GetLaunchDescriptor + - gamedesign.v1.GameDesignService/GetCompleteLaunchBinding http: enabled: true role-requirement: PRIVILEGED diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java new file mode 100644 index 0000000000..d6f7f00c9e --- /dev/null +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java @@ -0,0 +1,582 @@ +package integration.net.firedevops.firemud.gamedesign.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.dto.CompleteLaunchBindingDto; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Game; +import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; +import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; +import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.Configuration; +import org.jooq.ExecuteContext; +import org.jooq.ExecuteListenerProvider; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; + +/** PostgreSQL proof for the immutable descriptor/release pair read from one owner snapshot. */ +@Testcontainers(disabledWithoutDocker = true) +@SpringBootTest( + classes = GameDesignServiceApplication.class, + properties = { + "spring.profiles.active=test", + "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=complete-launch-binding-test", + "spring.grpc.server.port=0", + "asset.store.endpoint=http://localhost:9000", + "asset.store.bucket=test-bucket", + "asset.store.region=us-east-1", + "asset.store.access-key=test-access-key", + "asset.store.secret-key=test-secret-key" + }) +@Import(NoGrpcServerTestConfiguration.class) +class CompleteLaunchBindingServiceIntegrationTest { + private static final String NAMESPACE = "complete-launch-binding-test"; + private static final org.jooq.Table VERSION_TABLE = DSL.table(DSL.name("version")); + private static final org.jooq.Field VERSION_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field VERSION_STATE = + DSL.field(DSL.name("version_state"), String.class); + private static final org.jooq.Field VERSION_STATE_EPOCH = + DSL.field(DSL.name("version_state_epoch"), Long.class); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "game_design_service"); + } + + @Autowired private CompleteLaunchBindingService completeLaunchBindingService; + @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Autowired private GameTemplateRepository gameTemplateRepository; + @Autowired private VersionRepository versionRepository; + @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private org.jooq.DSLContext dsl; + @Autowired private ObjectMapper objectMapper; + + @Test + void returnsAndRetriesThePersistedCompletePairWithoutChangingOwnerRows() { + Fixture fixture = fixture("complete-pair", true); + Map before = rowVersions(fixture); + + CompleteLaunchBindingDto first = readComplete(fixture); + CompleteLaunchBindingDto retry = readComplete(fixture); + + assertThat(first).isEqualTo(retry); + assertThat(first.descriptor()).isEqualTo(fixture.descriptor().authoredWorldBinding()); + first.releaseAttestation().requireValid(first.descriptor()); + assertThat(first.releaseAttestation().canonicalTenantId()) + .isEqualTo(fixture.canonicalTenantId()); + assertThat(first.releaseAttestation().canonicalVersionId()) + .isEqualTo(fixture.version().getCanonicalVersionId()); + assertThat(first.releaseAttestation().versionStateEpoch()) + .isEqualTo(fixture.descriptor().versionStateEpoch()); + assertThat(fixture.descriptor().releaseBundleId()).isEqualTo(fixture.bundle().getId()); + assertThat(fixture.descriptor().publishedReleaseBundleRef()) + .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); + assertThat(first.releaseAttestation().participantDigests()) + .extracting(AuthoredWorldReleaseAttestationEvidence.Participant::participantKey) + .containsExactlyElementsOf( + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()); + assertThat(first.releaseAttestation().artifactDigests()).hasSize(1); + + LaunchDescriptor persisted = persistedDescriptor(fixture); + assertThat(persisted.getLaunchDescriptorId()) + .isEqualTo(first.descriptor().launchDescriptorId()); + assertThat(persisted.getResultDigest()).isEqualTo(first.descriptor().resultDigest()); + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void retainsTheHistoricalAttestationWhenCurrentVersionStateAdvances() { + Fixture fixture = fixture("historical-epoch", true); + CompleteLaunchBindingDto original = readComplete(fixture); + Map immutableRowsBefore = immutableRowVersions(fixture); + + advanceVersion(fixture, VersionLifecycleState.RETIRED, 2L); + CompleteLaunchBindingDto later = readComplete(fixture); + + assertThat(later.descriptor()).isEqualTo(original.descriptor()); + assertThat(later.releaseAttestation()).isEqualTo(original.releaseAttestation()); + assertThat(later.releaseAttestation().versionStateEpoch()) + .isEqualTo(original.descriptor().versionStateEpoch()); + assertThat( + dsl.select(VERSION_STATE) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE)) + .isEqualTo(VersionLifecycleState.RETIRED.name()); + assertThat( + dsl.select(VERSION_STATE_EPOCH) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE_EPOCH)) + .isEqualTo(2L); + assertThat(immutableRowVersions(fixture)).isEqualTo(immutableRowsBefore); + // This is historical evidence equality, not a claim that RETIRED is currently launch-eligible. + } + + @Test + void deniesCrossTenantAndSubstitutedSourceSelectorsWithoutMutatingPersistedEvidence() { + Fixture first = fixture("cross-tenant-first", true); + Fixture second = fixture("cross-tenant-second", true); + Map firstBefore = rowVersions(first); + Map secondBefore = rowVersions(second); + UUID absentCanonicalTenant = UUID.randomUUID(); + + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + second.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + first.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied( + () -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + absentCanonicalTenant, + first.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + + PublishedReleaseBundle swappedCanonicalSource = new PublishedReleaseBundle(); + swappedCanonicalSource.setTenantId(first.privateTenantKey()); + swappedCanonicalSource.setVersionId(first.version().getId()); + swappedCanonicalSource.setCanonicalTenantId(second.canonicalTenantId()); + swappedCanonicalSource.setCanonicalVersionId(second.version().getCanonicalVersionId()); + assertThatThrownBy(() -> publishedReleaseBundleRepository.save(swappedCanonicalSource)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("canonical release identity"); + + assertThat(rowVersions(first)).isEqualTo(firstBefore); + assertThat(rowVersions(second)).isEqualTo(secondBefore); + } + + @Test + void deniesPersistedDescriptorWhoseBundleLacksCompleteOwnerEvidenceWithoutMutation() { + Fixture fixture = fixture("missing-owner-evidence", false); + Map before = rowVersions(fixture); + + assertThatThrownBy(() -> readComplete(fixture)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("PARTICIPANT_EVIDENCE_INCOMPLETE"); + + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void descriptorSnapshotRejectsNonRepeatableReadBeforeAnyWrite() { + Fixture fixture = fixture("snapshot-guard", true); + Map before = rowVersions(fixture); + TransactionTemplate readCommitted = new TransactionTemplate(transactionManager); + readCommitted.setReadOnly(true); + readCommitted.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + assertThatThrownBy( + () -> + readCommitted.execute( + status -> + launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + fixture.readRequestId(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + fixture.descriptor().authoredWorldBinding().requestDigest(), + fixture.descriptor().authoredWorldBinding().resultDigest()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("read-only REPEATABLE_READ"); + + assertThat(rowVersions(fixture)).isEqualTo(before); + } + + @Test + void concurrentVersionAdvanceCannotSplitTheCompleteOwnerSnapshot() throws Exception { + Fixture fixture = fixture("concurrent-owner-snapshot", true); + Map immutableRowsBefore = immutableRowVersions(fixture); + CountDownLatch producerVersionReadCompleted = new CountDownLatch(1); + CountDownLatch continueRead = new CountDownLatch(1); + AtomicInteger versionStateSnapshotReads = new AtomicInteger(); + AtomicReference readOnlyObserved = new AtomicReference<>(false); + AtomicReference isolationObserved = new AtomicReference<>(); + DefaultExecuteListener interlock = + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && isVersionStateSnapshotQuery(sql) + && versionStateSnapshotReads.incrementAndGet() == 2) { + readOnlyObserved.set( + TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + isolationObserved.set( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + producerVersionReadCompleted.countDown(); + awaitInterlock(continueRead); + } + } + }; + Configuration configuration = dsl.configuration(); + ExecuteListenerProvider[] originalProviders = configuration.executeListenerProviders(); + List providers = new ArrayList<>(Arrays.asList(originalProviders)); + providers.add(new DefaultExecuteListenerProvider(interlock)); + configuration.set(providers.toArray(ExecuteListenerProvider[]::new)); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + Future inFlightRead = executor.submit(() -> readComplete(fixture)); + assertThat(producerVersionReadCompleted.await(10, TimeUnit.SECONDS)).isTrue(); + + advanceVersion(fixture, VersionLifecycleState.RETIRED, 2L); + continueRead.countDown(); + + CompleteLaunchBindingDto snapshot = inFlightRead.get(20, TimeUnit.SECONDS); + assertThat(readOnlyObserved.get()).isTrue(); + assertThat(isolationObserved.get()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(snapshot.descriptor()).isEqualTo(fixture.descriptor().authoredWorldBinding()); + assertThat(snapshot.releaseAttestation().versionStateEpoch()) + .isEqualTo(fixture.descriptor().versionStateEpoch()); + assertThat(snapshot.releaseAttestation()) + .isEqualTo(readComplete(fixture).releaseAttestation()); + assertThat(immutableRowVersions(fixture)).isEqualTo(immutableRowsBefore); + assertThat( + dsl.select(VERSION_STATE_EPOCH) + .from(VERSION_TABLE) + .where(VERSION_ID.eq(fixture.version().getId())) + .fetchOne(VERSION_STATE_EPOCH)) + .isEqualTo(2L); + } finally { + continueRead.countDown(); + executor.shutdownNow(); + executor.awaitTermination(5, TimeUnit.SECONDS); + configuration.set(originalProviders); + } + } + + private boolean isVersionStateSnapshotQuery(String sql) { + String compact = sql.toLowerCase(Locale.ROOT).replace("\"", "").replaceAll("\\s+", ""); + return compact.contains( + "selectid,tenant_id,canonical_version_id,canonical_tenant_id," + + "identity_source_game_row_id,identity_source_game_tenant_key," + + "identity_source_provenance_kind,version_state,version_state_epoch" + + "fromversionwhereid=?"); + } + + private Fixture fixture(String label, boolean completeEvidence) { + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String privateTenantKey = "gd-" + UUID.randomUUID().toString().replace("-", ""); + assertThat(privateTenantKey).matches("gd-[0-9a-f]{32}").hasSize(35); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Complete binding source " + label + " " + suffix); + game.setDescription("Fresh persisted Game provenance for complete-binding proof"); + Game persistedGame = gameRepository.save(game); + assertThat(privateTenantKey).isNotEqualTo(persistedGame.getCanonicalTenantId().toString()); + + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Synthetic Complete Binding World")); + + Version version = new Version(); + version.setTenantId(privateTenantKey); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(1L); + version.setNotes("synthetic complete-release evidence fixture"); + version.setUpdatedAt(LocalDateTime.now()); + version = versionRepository.save(version); + + GameTemplate template = new GameTemplate(); + template.setTenantId(privateTenantKey); + template.setName("Complete Binding Template " + suffix); + template.setDescription("Persisted launch descriptor fixture"); + template.setConfig("{}"); + template.setDefaultVersionId(version.getId()); + template.setDefaultRuntimeFlagsJson("{}"); + template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + template = gameTemplateRepository.save(template); + + PublishedReleaseBundle bundle = + syntheticBundle(privateTenantKey, version, suffix, completeEvidence); + PublishedReleaseBundle persistedBundle = publishedReleaseBundleRepository.save(bundle); + String controlPlaneRequestId = "complete-launch-" + suffix; + UUID readRequestId = UUID.randomUUID(); + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + persistedGame.getCanonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + false, + null, + false, + null, + false, + null, + false, + null); + ResolvedLaunchDescriptorDto descriptor = + launchDescriptorService.resolveLaunchDescriptor(request); + LaunchDescriptor storedDescriptor = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, persistedGame.getCanonicalTenantId(), controlPlaneRequestId) + .orElseThrow(); + + return new Fixture( + readRequestId, + controlPlaneRequestId, + persistedGame.getId(), + persistedGame.getCanonicalTenantId(), + privateTenantKey, + source, + version, + template, + persistedBundle, + descriptor, + storedDescriptor); + } + + private PublishedReleaseBundle syntheticBundle( + String privateTenantKey, Version version, String suffix, boolean completeEvidence) { + // Synthetic fixture bytes produce real content-addressed hashes; this is not a claim that + // Game Logic or external object storage performed a normal publication in this test. + byte[] artifactBytes = + ("synthetic complete-binding artifact " + suffix).getBytes(StandardCharsets.UTF_8); + String artifactHex = sha256Hex(artifactBytes); + String artifactDigest = "sha256:" + artifactHex; + String manifestBytes = + "{\"schemaVersion\":1,\"assets\":[{\"usageKey\":\"world.navmesh\",\"contentDigest\":\"" + + artifactDigest + + "\"}]}"; + String manifestHash = "sha256:" + sha256Hex(manifestBytes.getBytes(StandardCharsets.UTF_8)); + PublishedArtifactDigest artifact = + new PublishedArtifactDigest( + "world.navmesh", + "world-navmesh", + "artifacts/sha256/" + artifactHex, + artifactDigest, + "application/octet-stream", + 1); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(privateTenantKey); + bundle.setVersionId(version.getId()); + bundle.setVersionNumber(version.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId("synthetic-publish-workflow:" + suffix); + bundle.setManifestHash(manifestHash); + bundle.setManifestSchemaVersion(1); + bundle.setArtifactDigestsJson(objectMapper.writeValueAsString(List.of(artifact))); + bundle.setGenerationConfigRevision("generation-config:" + suffix + ":" + "g".repeat(180)); + bundle.setRequiredManifestAssetKeysJson( + objectMapper.writeValueAsString(List.of("world.navmesh"))); + bundle.setParticipantDigestsJson( + objectMapper.writeValueAsString( + completeEvidence ? syntheticParticipants(version) : List.of())); + bundle.setCommandDefinitionsJson( + objectMapper.writeValueAsString(List.of("{\"commandId\":\"look\"}"))); + bundle.setScriptOnly(false); + return bundle; + } + + private List syntheticParticipants(Version version) { + List participants = new ArrayList<>(); + for (String participantKey : + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder()) { + boolean gameLogic = "GAME_LOGIC".equals(participantKey); + participants.add( + new PublishParticipantDigestDto( + participantKey, + Long.toString(version.getId()), + null, + "synthetic-applied-commit-" + version.getId(), + "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey), + gameLogic ? "sha256:" + "b".repeat(64) : null, + null, + null)); + } + return List.copyOf(participants); + } + + private CompleteLaunchBindingDto readComplete(Fixture fixture) { + AuthoredWorldLaunchDescriptorEvidence descriptor = fixture.descriptor().authoredWorldBinding(); + return completeLaunchBindingService.getCompleteLaunchBinding( + fixture.readRequestId(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + private void advanceVersion(Fixture fixture, VersionLifecycleState state, long epoch) { + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + transaction.execute( + status -> { + Version current = + versionRepository + .findByTenantIdAndId(fixture.privateTenantKey(), fixture.version().getId()) + .orElseThrow(); + current.setVersionState(state); + current.setVersionStateEpoch(epoch); + return versionRepository.save(current); + }); + } + + private Map rowVersions(Fixture fixture) { + Map snapshot = immutableRowVersions(fixture); + snapshot.put("version", rowXmin("version", "id", fixture.version().getId())); + return snapshot; + } + + private Map immutableRowVersions(Fixture fixture) { + Map snapshot = new LinkedHashMap<>(); + snapshot.put("game", rowXmin("game", "id", fixture.gameRowId())); + snapshot.put( + "source", + rowXmin( + "game_design_authored_world_source_operations", + "operation_id", + fixture.source().operationId())); + snapshot.put("template", rowXmin("game_templates", "id", fixture.template().getId())); + snapshot.put("bundle", rowXmin("published_release_bundle", "id", fixture.bundle().getId())); + snapshot.put( + "descriptor", rowXmin("launch_descriptor", "id", fixture.storedDescriptor().getId())); + return snapshot; + } + + private String rowXmin(String table, String idColumn, Object id) { + var row = dsl.fetchOne("SELECT xmin::text FROM " + table + " WHERE " + idColumn + " = ?", id); + return row == null ? "" : row.get(0, String.class); + } + + private LaunchDescriptor persistedDescriptor(Fixture fixture) { + return launchDescriptorRepository + .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + } + + private void assertDenied(Runnable operation) { + assertThatThrownBy(operation::run).isInstanceOf(IllegalArgumentException.class); + } + + private void awaitInterlock(CountDownLatch continueRead) { + try { + if (!continueRead.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to resume complete-binding snapshot"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while holding complete-binding snapshot", exception); + } + } + + private static String sha256Hex(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the JDK", impossible); + } + } + + private record Fixture( + UUID readRequestId, + String controlPlaneRequestId, + long gameRowId, + UUID canonicalTenantId, + String privateTenantKey, + AuthoredWorldSourceEvidence source, + Version version, + GameTemplate template, + PublishedReleaseBundle bundle, + ResolvedLaunchDescriptorDto descriptor, + LaunchDescriptor storedDescriptor) {} +} diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 1dbcec0d96..4b83a38f23 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -1,30 +1,65 @@ package integration.net.firedevops.firemud.gamedesign.service; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.time.LocalDateTime; +import java.util.Map; +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.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.gamedesign.GameDesignServiceApplication; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Game; import net.firedevops.firemud.gamedesign.entity.GameTemplate; +import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; import net.firedevops.firemud.gamedesign.entity.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.entity.Version; import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameRepository; +import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; +import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.impl.LaunchDescriptorServiceImpl; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; -import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @SpringBootTest( @@ -33,6 +68,7 @@ "spring.profiles.active=test", "firemud.auth.jwt-secret=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "firemud.grpc.plaintext=true", + "firemud.grpc.workload-namespace=launch-descriptor-test", "spring.grpc.server.port=0", "asset.store.endpoint=http://localhost:9000", "asset.store.bucket=test-bucket", @@ -42,9 +78,20 @@ }) @Import(NoGrpcServerTestConfiguration.class) class LaunchDescriptorServiceIntegrationTest { + private static final String NAMESPACE = "launch-descriptor-test"; + private static final String FLYWAY_TABLE = "flyway_schema_history_game_design_service"; + private static final org.jooq.Table LAUNCH_DESCRIPTOR = + DSL.table(DSL.name("launch_descriptor")); + private static final org.jooq.Field LAUNCH_ROW_ID = DSL.field(DSL.name("id"), Long.class); + private static final org.jooq.Field LAUNCH_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final org.jooq.Field LAUNCH_CANONICAL_TENANT = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final org.jooq.Field LAUNCH_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + @Container - static PostgreSQLContainer postgres = - new PostgreSQLContainer<>(TestContainerImages.postgres()); + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { @@ -53,51 +100,999 @@ static void configure(DynamicPropertyRegistry registry) { } @Autowired private LaunchDescriptorService launchDescriptorService; + @Autowired private GameRepository gameRepository; + @Autowired private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; @Autowired private GameTemplateRepository gameTemplateRepository; @Autowired private VersionRepository versionRepository; @Autowired private PublishedReleaseBundleRepository publishedReleaseBundleRepository; + @Autowired private PublishedReleaseBundleService publishedReleaseBundleService; + @Autowired private LaunchDescriptorRepository launchDescriptorRepository; + @Autowired private PlatformTransactionManager transactionManager; + @Autowired private DSLContext dsl; + + @Test + void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionChange() { + Fixture fixture = fixture("cp-persisted"); + + ResolvedLaunchDescriptorDto original = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + String generationConfigRevision = fixture.bundle().getGenerationConfigRevision(); + assertThat(generationConfigRevision.length()).isGreaterThan(128); + assertThat(original.generationConfigRevision()).isEqualTo(generationConfigRevision); + assertThat(original.gameTemplateId()).isEqualTo(fixture.template().getId()); + assertThat(original.versionId()).isEqualTo(fixture.version().getId()); + assertThat(original.versionStateEpoch()).isEqualTo(1L); + assertThat(original.canonicalTenantId()).isEqualTo(fixture.canonicalTenantId().toString()); + assertThat(original.publishedReleaseBundleRef()) + .isEqualTo(fixture.bundle().getPublishedReleaseBundleRef()); + assertThat( + publishedReleaseBundleRepository + .findByTenantIdAndVersionId( + fixture.privateSourceTenantKey(), fixture.version().getId()) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); + assertThat(original.authoredWorldBinding()).isNotNull(); + assertThat(original.authoredWorldBinding().authoredWorldSourceOperationId()) + .isEqualTo(fixture.source().operationId()); + assertThat(original.authoredWorldBinding().authoredWorldSourceEvidenceDigest()) + .isEqualTo(fixture.source().evidenceDigest()); + assertThat(original.canonicalTenantId()).isNotEqualTo(fixture.privateSourceTenantKey()); + + Version newDraft = new Version(); + newDraft.setTenantId(fixture.privateSourceTenantKey()); + newDraft.setVersionNumber(2); + newDraft.setVersionState(VersionLifecycleState.DRAFT); + newDraft.setVersionStateEpoch(1L); + newDraft.setNotes("new mutable template default"); + newDraft.setUpdatedAt(LocalDateTime.now()); + newDraft = versionRepository.save(newDraft); + fixture.template().setDefaultVersionId(newDraft.getId()); + gameTemplateRepository.save(fixture.template()); + fixture.version().setVersionState(VersionLifecycleState.RETIRED); + fixture.version().setVersionStateEpoch(2L); + versionRepository.save(fixture.version()); + + ResolvedLaunchDescriptorDto retry = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + + assertThat(retry).isEqualTo(original); + assertThat(retry.versionId()).isEqualTo(fixture.version().getId()); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(original.launchDescriptorId()); + assertThat(persisted.getRequestDigest()) + .isEqualTo(original.authoredWorldBinding().requestDigest()); + assertThat(persisted.getResultDigest()) + .isEqualTo(original.authoredWorldBinding().resultDigest()); + assertThat(persisted.getPublishedReleaseBundleRef()) + .isEqualTo(original.publishedReleaseBundleRef()); + assertThat(persisted.getGenerationConfigRevision()).isEqualTo(generationConfigRevision); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + ResolvedLaunchDescriptorDto readback = + launchDescriptorService.getLaunchDescriptor( + UUID.randomUUID(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + assertThat(readback).isEqualTo(original); + } + + @Test + void concurrentExactRetriesPersistOneOriginalDescriptor() throws Exception { + Fixture fixture = fixture("cp-concurrent"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + ResolvedLaunchDescriptorDto firstResult = first.get(20, TimeUnit.SECONDS); + ResolvedLaunchDescriptorDto secondResult = second.get(20, TimeUnit.SECONDS); + + assertThat(secondResult).isEqualTo(firstResult); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + LaunchDescriptor persisted = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(persisted.getLaunchDescriptorId()).isEqualTo(firstResult.launchDescriptorId()); + assertThat(persisted.getResultDigest()) + .isEqualTo(firstResult.authoredWorldBinding().resultDigest()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries() + throws Exception { + Fixture fixture = fixture("cp-frozen-phase"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + + assertThatThrownBy(() -> launchDescriptorService.resolveLaunchDescriptor(fixture.request())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + + LaunchDescriptor failed = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(failed.getOutcomeStatus()).isEqualTo(LaunchDescriptor.OUTCOME_FAILED); + assertThat(failed.getFailureCode()).isEqualTo("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + assertThat(failed.getFailureMessage()) + .isEqualTo( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced"); + assertThat(failed.getRequestDigest()).isEqualTo(fixture.request().requestDigest()); + assertThat(failed.getOriginalRequestJson()).isNotBlank(); + assertThat(failed.getSourceEvidenceJson()).isNotBlank(); + assertThat(failed.getLaunchDescriptorId()).isNull(); + assertThat(failed.getGameTemplateId()).isNull(); + assertThat(failed.getVersionId()).isNull(); + assertThat(failed.getReleaseBundleId()).isNull(); + assertThat(failed.getResultDigest()).isNull(); + assertFailedShapeRejected(failed, "cp-frozen-null-schema", true); + assertFailedShapeRejected(failed, "cp-frozen-null-failure-code", false); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); + gameTemplateRepository.save(fixture.template()); + + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + Future second = + executor.submit(() -> resolveFailureAfterLatch(fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + assertThat(second.get(20, TimeUnit.SECONDS)).isEqualTo(failed.getFailureMessage()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + + assertThatThrownBy( + () -> + launchDescriptorService.resolveLaunchDescriptor( + fixture.requestWithPatch("different-patch"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("control-plane request identity was reused with changed input"); + + ResolvedLaunchDescriptorDto freshAttempt = + launchDescriptorService.resolveLaunchDescriptor(fixture.request("cp-frozen-phase-fresh")); + assertThat(freshAttempt.versionId()).isEqualTo(fixture.version().getId()); + assertThat( + launchDescriptorRepository + .findBoundByRequest(NAMESPACE, fixture.canonicalTenantId(), "cp-frozen-phase-fresh") + .orElseThrow() + .getOutcomeStatus()) + .isEqualTo(LaunchDescriptor.OUTCOME_SUCCESS); + } + + @Test + void corruptFailureReadbackRollsBackTheOutcomeInsert() { + Fixture fixture = fixture("cp-corrupt-failure-readback"); + fixture.template().setTemplateReferencePhase(TemplateReferencePhase.LEGACY); + gameTemplateRepository.save(fixture.template()); + LaunchDescriptorRepository corruptingRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { + LaunchDescriptor persisted = super.insertImmutable(descriptor); + persisted.setFailureCode("UNRECOGNIZED_FAILURE"); + return persisted; + } + }; + LaunchDescriptorServiceImpl corruptingService = + new LaunchDescriptorServiceImpl( + gameTemplateRepository, + corruptingRepository, + versionRepository, + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(corruptingService, "workloadNamespace", NAMESPACE); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> corruptingService.resolveLaunchDescriptor(fixture.request()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("stored failure is not the exact immutable request outcome"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + } + + @Test + void concurrentSuccessAndFailureCandidatesPersistOnlyTheFirstOutcome() throws Exception { + Fixture fixture = fixture("cp-mixed-candidates"); + CountDownLatch lockArrivals = new CountDownLatch(2); + CountDownLatch viewReached = new CountDownLatch(1); + CountDownLatch continueResolution = new CountDownLatch(1); + LaunchDescriptorRepository serializedRepository = + new LaunchDescriptorRepository(dsl) { + @Override + public void lockBoundRequest(String targetNamespace, UUID tenantId, String requestId) { + lockArrivals.countDown(); + super.lockBoundRequest(targetNamespace, tenantId, requestId); + } + }; + LaunchDescriptorServiceImpl failureCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.LEGACY, + viewReached, + continueResolution); + LaunchDescriptorServiceImpl successCandidate = + candidateForPhase( + fixture, + serializedRepository, + TemplateReferencePhase.ENFORCED, + viewReached, + continueResolution); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> resolveCandidateInOwnerTransaction(failureCandidate, fixture, ready, start)); + Future second = + executor.submit( + () -> resolveCandidateInOwnerTransaction(successCandidate, fixture, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(viewReached.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(lockArrivals.await(10, TimeUnit.SECONDS)).isTrue(); + continueResolution.countDown(); + + String firstResult = first.get(20, TimeUnit.SECONDS); + String secondResult = second.get(20, TimeUnit.SECONDS); + assertThat(secondResult).isEqualTo(firstResult); + LaunchDescriptor stored = + launchDescriptorRepository + .findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId()) + .orElseThrow(); + assertThat(stored.getOutcomeStatus()) + .isEqualTo( + firstResult.startsWith("FAILED:") + ? LaunchDescriptor.OUTCOME_FAILED + : LaunchDescriptor.OUTCOME_SUCCESS); + assertThat( + dsl.fetchCount( + LAUNCH_DESCRIPTOR, + LAUNCH_NAMESPACE + .eq(NAMESPACE) + .and(LAUNCH_CANONICAL_TENANT.eq(fixture.canonicalTenantId())) + .and(LAUNCH_REQUEST_ID.eq(fixture.controlPlaneRequestId())))) + .isEqualTo(1); + } finally { + continueResolution.countDown(); + start.countDown(); + executor.shutdownNow(); + } + } @Test - void resolvesLaunchDescriptorForJsonConfiguredTemplate() { + void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { + Fixture fixture = fixture("cp-rollback"); + AuthoredWorldLaunchDescriptorEvidence evidence = evidence(fixture, "ld-rollback-candidate"); + LaunchDescriptor candidate = entity(evidence, fixture); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + + assertThatThrownBy( + () -> + transaction.execute( + status -> { + launchDescriptorRepository.insertImmutable(candidate); + throw new IllegalStateException("force owner transaction rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("force owner transaction rollback"); + + assertThat( + launchDescriptorRepository.findBoundByRequest( + NAMESPACE, fixture.canonicalTenantId(), fixture.controlPlaneRequestId())) + .isEmpty(); + assertThat( + launchDescriptorRepository.findByPrivateRequest( + fixture.privateSourceTenantKey(), fixture.controlPlaneRequestId())) + .isEmpty(); + ResolvedLaunchDescriptorDto committed = + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + assertThat(committed.authoredWorldBinding().requestDigest()) + .isEqualTo(evidence.requestDigest()); + } + + @Test + void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { + String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = isolatedDataSource(schema); + migrate(dataSource, schema, MigrationVersion.fromVersion("34")); + DSLContext isolatedDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager isolatedTransactionManager = + new DataSourceTransactionManager(dataSource); + TransactionTemplate isolatedTransaction = new TransactionTemplate(isolatedTransactionManager); + + String privateTenantKey = privateTenantKey(); + Game game = new Game(); + game.setTenantId(privateTenantKey); + game.setName("Retained launch source"); + game.setDescription("Persisted V34 source fixture"); + Game persistedGame = + isolatedTransaction.execute(status -> new GameRepository(isolatedDsl).save(game)); + assertThat(persistedGame).isNotNull(); + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + seedPreV41AuthoredWorldSource( + isolatedDsl, + isolatedTransaction, + persistedGame, + UUID.randomUUID(), + "tenant-" + suffix, + "world-" + suffix, + "Retained World 🐉"); + assertThat(source).isNotNull(); + + Long versionId = + isolatedDsl + .resultQuery( + "INSERT INTO version (tenant_id, version_number, version_state, version_state_epoch) " + + "VALUES (?, 1, 'PUBLISHED', 1) RETURNING id", + privateTenantKey) + .fetchOne(0, Long.class); + Long templateId = + isolatedDsl + .resultQuery( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, ?, '{}'::jsonb) RETURNING id", + privateTenantKey, + "Retained Template " + suffix) + .fetchOne(0, Long.class); + // Synthetic retained-row seed for storage compatibility only; not live publication proof. + Long bundleId = + isolatedDsl + .resultQuery( + "INSERT INTO published_release_bundle " + + "(tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, required_manifest_asset_keys_json, " + + "participant_digests_json, generation_config_revision) " + + "VALUES (?, ?, 1, 'v1', ?, ?, '[]', '[]', ?) RETURNING id", + privateTenantKey, + versionId, + "synthetic-retained-fixture-" + suffix, + "sha256:" + "d".repeat(64), + "gen-rev:" + suffix) + .fetchOne(0, Long.class); + if (bundleId == null) { + throw new IllegalStateException("Retained V34 release bundle insertion returned no identity"); + } + String requestId = "retained-cp-" + suffix; + String legacyDescriptorId = "ld-retained-" + suffix; + isolatedDsl.execute( + "INSERT INTO launch_descriptor " + + "(launch_descriptor_id, tenant_id, game_template_id, control_plane_request_id, " + + "request_hash, version_id, runtime_flags_json, generation_config_revision, " + + "version_state_epoch, release_bundle_id, published_release_bundle_ref) " + + "VALUES (?, ?, ?, ?, ?, ?, '{}', ?, 1, ?, ?)", + legacyDescriptorId, + privateTenantKey, + templateId, + requestId, + "legacy-request-hash-" + suffix, + versionId, + "gen-rev:" + suffix, + bundleId, + "legacy-release-ref-" + suffix); + Map retainedV34Snapshot = + legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId); + Map retainedBundleSnapshot = + retainedReleaseBundleSnapshot(isolatedDsl, bundleId); + + migrate(dataSource, schema, null); + LaunchDescriptorRepository launchRepository = new LaunchDescriptorRepository(isolatedDsl); + var retainedBundleReference = + isolatedDsl.fetchOne( + "SELECT published_release_bundle_ref FROM published_release_bundle WHERE id = ?", + bundleId); + if (retainedBundleReference == null) { + throw new IllegalStateException("Retained V34 release bundle reference row is missing"); + } + assertThat(retainedBundleReference.get("published_release_bundle_ref", String.class)).isNull(); + assertThat(retainedReleaseBundleSnapshot(isolatedDsl, bundleId)) + .isEqualTo(retainedBundleSnapshot); + assertThat( + new PublishedReleaseBundleRepository(isolatedDsl) + .findByTenantIdAndVersionId(privateTenantKey, versionId) + .orElseThrow() + .getPublishedReleaseBundleRef()) + .isNull(); + assertThat(legacyLaunchDescriptorSnapshot(isolatedDsl, privateTenantKey, requestId)) + .isEqualTo(retainedV34Snapshot); + LaunchDescriptor before = + launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow(); + assertThat(before.getDescriptorSchemaVersion()).isNull(); + assertThat(before.getCanonicalTenantId()).isNull(); + assertThat(before.getRequestHash()).isEqualTo("legacy-request-hash-" + suffix); + + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + persistedGame.getCanonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + templateId, + false, + null, + false, + null, + false, + null, + false, + null); + LaunchDescriptorServiceImpl isolatedService = + new LaunchDescriptorServiceImpl( + Mockito.mock(GameTemplateRepository.class), + launchRepository, + Mockito.mock(VersionRepository.class), + Mockito.mock(PublishedReleaseBundleService.class), + Mockito.mock(TemplateRemapSetService.class), + new GameAuthoredWorldSourceRepository(isolatedDsl), + new ObjectMapper()); + ReflectionTestUtils.setField(isolatedService, "workloadNamespace", NAMESPACE); + + assertThatThrownBy(() -> isolatedService.resolveLaunchDescriptor(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("LAUNCH_DESCRIPTOR_CONFLICT") + .hasMessageContaining("unbound"); + assertThat( + launchRepository.findBoundByRequest( + NAMESPACE, persistedGame.getCanonicalTenantId(), requestId)) + .isEmpty(); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE launch_descriptor SET runtime_flags_json = ? WHERE id = ?", + "{\"changed\":true}", + before.getId())) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("launch descriptors are immutable"); + assertRetainedRowUnchanged( + before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); + } + + private Fixture fixture(String controlPlaneRequestId) { + String privateTenantKey = privateTenantKey(); + Game sourceGame = new Game(); + sourceGame.setTenantId(privateTenantKey); + sourceGame.setName("Launch Source " + UUID.randomUUID()); + sourceGame.setDescription("Persisted fresh Game Design tenant source"); + Game persistedGame = + new TransactionTemplate(transactionManager) + .execute(status -> gameRepository.save(sourceGame)); + assertThat(persistedGame).isNotNull(); + + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + AuthoredWorldSourceEvidence source = + new TransactionTemplate(transactionManager) + .execute( + status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Launch World 🐉")); + assertThat(source).isNotNull(); + Version version = new Version(); - version.setTenantId("1"); + version.setTenantId(privateTenantKey); version.setVersionNumber(1); version.setVersionState(VersionLifecycleState.PUBLISHED); version.setVersionStateEpoch(1L); - version.setNotes("integration test version"); + version.setNotes("synthetic release storage proof fixture"); version.setUpdatedAt(LocalDateTime.now()); version = versionRepository.save(version); GameTemplate template = new GameTemplate(); - template.setTenantId("1"); - template.setName("Integration Template"); - template.setDescription("launch descriptor integration template"); + template.setTenantId(privateTenantKey); + template.setName("Launch Template " + suffix); + template.setDescription("Persisted descriptor resolution fixture"); template.setConfig("{}"); template.setDefaultVersionId(version.getId()); template.setDefaultRuntimeFlagsJson("{}"); template.setTemplateReferencePhase(TemplateReferencePhase.ENFORCED); template = gameTemplateRepository.save(template); + // This row exercises descriptor storage and resolution only; it is not live publication proof. PublishedReleaseBundle bundle = new PublishedReleaseBundle(); - bundle.setTenantId("1"); + bundle.setTenantId(privateTenantKey); bundle.setVersionId(version.getId()); bundle.setVersionNumber(1); bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId("integration-seed"); - bundle.setManifestHash("integration-manifest"); - bundle.setGenerationConfigRevision("genrev:integration"); + bundle.setPublishWorkflowId("synthetic-storage-proof-" + suffix); + bundle.setManifestHash("sha256:" + "e".repeat(64)); + bundle.setGenerationConfigRevision("gen-rev:" + suffix + ":" + "g".repeat(180)); bundle.setRequiredManifestAssetKeysJson("[]"); bundle.setParticipantDigestsJson("[]"); bundle.setScriptOnly(false); - publishedReleaseBundleRepository.save(bundle); + bundle = publishedReleaseBundleRepository.save(bundle); + + return new Fixture( + controlPlaneRequestId, + persistedGame.getCanonicalTenantId(), + privateTenantKey, + source, + version, + template, + bundle); + } + + private void assertFailedShapeRejected( + LaunchDescriptor failed, String controlPlaneRequestId, boolean nullSchemaVersion) { + assertThatThrownBy( + () -> + dsl.execute( + """ + INSERT INTO launch_descriptor ( + tenant_id, + control_plane_request_id, + request_hash, + descriptor_schema_version, + target_namespace, + canonical_tenant_id, + world_slug, + authored_world_source_operation_id, + authored_world_source_evidence_digest, + request_digest, + original_request_json, + source_evidence_json, + outcome_status, + failure_code, + failure_message) + VALUES (?, ?, ?, CAST(? AS SMALLINT), ?, CAST(? AS UUID), ?, + CAST(? AS UUID), ?, ?, ?, ?, 'FAILED', CAST(? AS VARCHAR(64)), ?) + """, + failed.getTenantId(), + controlPlaneRequestId, + failed.getRequestHash(), + nullSchemaVersion ? null : failed.getDescriptorSchemaVersion(), + failed.getTargetNamespace(), + failed.getCanonicalTenantId(), + failed.getWorldSlug(), + failed.getAuthoredWorldSourceOperationId(), + failed.getAuthoredWorldSourceEvidenceDigest(), + failed.getRequestDigest(), + failed.getOriginalRequestJson(), + failed.getSourceEvidenceJson(), + nullSchemaVersion ? failed.getFailureCode() : null, + failed.getFailureMessage())) + .isInstanceOf(DataIntegrityViolationException.class) + .hasStackTraceContaining("ck_launch_descriptor_authored_binding_complete"); + } + + private ResolvedLaunchDescriptorDto resolveAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + return launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + } + + private String resolveFailureAfterLatch( + Fixture fixture, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + await(start); + try { + launchDescriptorService.resolveLaunchDescriptor(fixture.request()); + return "unexpected success"; + } catch (IllegalArgumentException exception) { + return exception.getMessage(); + } + } + + private String resolveCandidateInOwnerTransaction( + LaunchDescriptorServiceImpl service, + Fixture fixture, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + await(start); + return new TransactionTemplate(transactionManager) + .execute( + status -> { + try { + return "SUCCESS:" + + service + .resolveLaunchDescriptor(fixture.request()) + .authoredWorldBinding() + .resultDigest(); + } catch (IllegalArgumentException exception) { + return "FAILED:" + exception.getMessage(); + } + }); + } + + private LaunchDescriptorServiceImpl candidateForPhase( + Fixture fixture, + LaunchDescriptorRepository repository, + TemplateReferencePhase phase, + CountDownLatch viewReached, + CountDownLatch continueResolution) { + GameTemplateRepository templateRepository = Mockito.mock(GameTemplateRepository.class); + GameTemplateLaunchConfigView view = Mockito.mock(GameTemplateLaunchConfigView.class); + Mockito.when(view.getId()).thenReturn(fixture.template().getId()); + Mockito.when(view.getTenantId()).thenReturn(fixture.privateSourceTenantKey()); + Mockito.when(view.getDefaultVersionId()).thenReturn(fixture.version().getId()); + Mockito.when(view.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + Mockito.when(view.getTemplateReferencePhase()) + .thenAnswer( + invocation -> { + viewReached.countDown(); + await(continueResolution); + return phase; + }); + Mockito.when( + templateRepository.findLaunchConfigByTenantIdAndId( + fixture.privateSourceTenantKey(), fixture.template().getId())) + .thenReturn(java.util.Optional.of(view)); + LaunchDescriptorServiceImpl service = + new LaunchDescriptorServiceImpl( + templateRepository, + repository, + versionRepository, + publishedReleaseBundleService, + Mockito.mock(TemplateRemapSetService.class), + authoredWorldSourceRepository, + new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + return service; + } + + private void await(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for descriptor retry race"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while waiting for descriptor retry race", exception); + } + } + + private AuthoredWorldLaunchDescriptorEvidence evidence(Fixture fixture, String descriptorId) { + return AuthoredWorldLaunchDescriptorEvidence.create( + fixture.request(), + descriptorId, + fixture.version().getId(), + false, + null, + "{}", + fixture.bundle().getGenerationConfigRevision(), + fixture.version().getVersionStateEpoch(), + fixture.bundle().getId(), + "release-bundle:" + + fixture.canonicalTenantId() + + ":" + + fixture.version().getId() + + ":" + + fixture.bundle().getId(), + false, + null); + } + + private LaunchDescriptor entity(AuthoredWorldLaunchDescriptorEvidence evidence, Fixture fixture) { + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(fixture.privateSourceTenantKey()); + descriptor.setGameTemplateId(evidence.gameTemplateId()); + descriptor.setControlPlaneRequestId(evidence.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setScriptPatchVersion(evidence.scriptPatchVersion()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setRemapSetId(evidence.remapSetId()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(json(evidence.request())); + descriptor.setSourceEvidenceJson(json(fixture.source())); + return descriptor; + } + + private String json(Object value) { + try { + return new ObjectMapper().writeValueAsString(value); + } catch (Exception exception) { + throw new IllegalStateException("Test evidence serialization failed", exception); + } + } + + private DriverManagerDataSource isolatedDataSource(String schema) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + return dataSource; + } + + /** Seeds the immutable source/binding shape written before V41 added automatic delivery. */ + private AuthoredWorldSourceEvidence seedPreV41AuthoredWorldSource( + DSLContext isolatedDsl, + TransactionTemplate isolatedTransaction, + Game sourceGame, + UUID registrationRequestId, + String tenantSlug, + String worldSlug, + String worldDisplayName) { + UUID operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW"); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + operationId, + requestDigest, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + sourceGame.getId(), + sourceGame.getTenantId(), + "NEW_GAME_ROW", + evidenceDigest); + + isolatedTransaction.execute( + status -> { + isolatedDsl.execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + isolatedDsl.execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, registration_request_id, " + + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " + + "world_display_name, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); + return source; + } + + private void migrate(DriverManagerDataSource dataSource, String schema, MigrationVersion target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table(FLYWAY_TABLE) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (target != null) { + configuration.target(target); + } + configuration.load().migrate(); + } + + private Map legacyLaunchDescriptorSnapshot( + DSLContext isolatedDsl, String privateTenantKey, String controlPlaneRequestId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, launch_descriptor_id, tenant_id, game_template_id, " + + "control_plane_request_id, request_hash, version_id, script_patch_version, " + + "runtime_flags_json, generation_config_revision, version_state_epoch, " + + "release_bundle_id, published_release_bundle_ref, remap_set_id, created_at " + + "FROM launch_descriptor WHERE tenant_id = ? AND control_plane_request_id = ?", + privateTenantKey, + controlPlaneRequestId); + if (record == null) { + throw new IllegalStateException("Retained V34 launch descriptor fixture is missing"); + } + return record.intoMap(); + } + + private Map retainedReleaseBundleSnapshot(DSLContext isolatedDsl, long bundleId) { + var record = + isolatedDsl.fetchOne( + "SELECT id, tenant_id, version_id, version_number, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, " + + "required_manifest_asset_keys_json, participant_digests_json, " + + "command_definitions_json, script_only, script_patch_version, published_at " + + "FROM published_release_bundle WHERE id = ?", + bundleId); + if (record == null) { + throw new IllegalStateException("Retained V34 release bundle fixture is missing"); + } + return record.intoMap(); + } + + private String privateTenantKey() { + return "src-" + UUID.randomUUID().toString().replace("-", ""); + } + + private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescriptor actual) { + assertThat(actual.getId()).isEqualTo(expected.getId()); + assertThat(actual.getLaunchDescriptorId()).isEqualTo(expected.getLaunchDescriptorId()); + assertThat(actual.getTenantId()).isEqualTo(expected.getTenantId()); + assertThat(actual.getGameTemplateId()).isEqualTo(expected.getGameTemplateId()); + assertThat(actual.getControlPlaneRequestId()).isEqualTo(expected.getControlPlaneRequestId()); + assertThat(actual.getRequestHash()).isEqualTo(expected.getRequestHash()); + assertThat(actual.getVersionId()).isEqualTo(expected.getVersionId()); + assertThat(actual.getScriptPatchVersion()).isEqualTo(expected.getScriptPatchVersion()); + assertThat(actual.getRuntimeFlagsJson()).isEqualTo(expected.getRuntimeFlagsJson()); + assertThat(actual.getGenerationConfigRevision()) + .isEqualTo(expected.getGenerationConfigRevision()); + assertThat(actual.getVersionStateEpoch()).isEqualTo(expected.getVersionStateEpoch()); + assertThat(actual.getReleaseBundleId()).isEqualTo(expected.getReleaseBundleId()); + assertThat(actual.getPublishedReleaseBundleRef()) + .isEqualTo(expected.getPublishedReleaseBundleRef()); + assertThat(actual.getRemapSetId()).isEqualTo(expected.getRemapSetId()); + assertThat(actual.getCreatedAt()).isEqualTo(expected.getCreatedAt()); + assertThat(actual.getDescriptorSchemaVersion()).isNull(); + assertThat(actual.getTargetNamespace()).isNull(); + assertThat(actual.getCanonicalTenantId()).isNull(); + assertThat(actual.getWorldSlug()).isNull(); + assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceEvidenceDigest()).isNull(); + assertThat(actual.getRequestDigest()).isNull(); + assertThat(actual.getResultDigest()).isNull(); + assertThat(actual.getOriginalRequestJson()).isNull(); + assertThat(actual.getSourceEvidenceJson()).isNull(); + } + + private record Fixture( + String controlPlaneRequestId, + UUID canonicalTenantId, + String privateSourceTenantKey, + AuthoredWorldSourceEvidence source, + Version version, + GameTemplate template, + PublishedReleaseBundle bundle) { + AuthoredWorldLaunchDescriptorEvidence.Request request() { + return request(controlPlaneRequestId); + } - var descriptor = - launchDescriptorService.resolveLaunchDescriptor( - "1", template.getId(), "integration-cp-1", null, null, null, null); + AuthoredWorldLaunchDescriptorEvidence.Request request(String requestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + requestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + false, + null, + false, + null, + false, + null, + false, + null); + } - assertThat(descriptor.gameTemplateId()).isEqualTo(template.getId()); - assertThat(descriptor.versionId()).isEqualTo(version.getId()); - assertThat(descriptor.generationConfigRevision()).isEqualTo("genrev:integration"); - assertThat(descriptor.versionStateEpoch()).isEqualTo(1L); + AuthoredWorldLaunchDescriptorEvidence.Request requestWithPatch(String patch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + template.getId(), + true, + patch, + false, + null, + false, + null, + false, + null); + } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java new file mode 100644 index 0000000000..2b673f3216 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java @@ -0,0 +1,463 @@ +package unit.net.firedevops.firemud.gamedesign.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +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 com.google.protobuf.Message; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.Status; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PingService; +import net.firedevops.firemud.gamedesign.service.RevisionService; +import net.firedevops.firemud.gamedesign.service.SettingsAuthorityService; +import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import net.firedevops.firemud.gamedesign.service.VersionAssetArtifactService; +import net.firedevops.firemud.gamedesign.service.VersionService; +import net.firedevops.firemud.gamedesign.service.impl.GameDesignGrpcService; +import net.firedevops.firemud.gamedesign.service.impl.TemporalVersionPublishWorkflowMetadataResolver; +import net.firedevops.firemud.gamedesign.v1.GetCompleteLaunchBindingResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; +import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; +import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; +import org.junit.jupiter.api.Test; +import org.springframework.test.util.ReflectionTestUtils; + +class CanonicalLaunchGrpcAuthWiringTest { + private static final String RESOLVE_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor"; + private static final String GET_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/GetLaunchDescriptor"; + private static final String GET_COMPLETE_LAUNCH_BINDING_METHOD = + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding"; + private static final String UNLISTED_METHOD = + "gamedesign.v1.GameDesignService/GetPublishedReleaseBundle"; + private static final List ALLOWLISTED_METHODS = + List.of( + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy", + "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies", + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + GET_LAUNCH_DESCRIPTOR_METHOD, + GET_COMPLETE_LAUNCH_BINDING_METHOD); + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String OTHER_NAMESPACE_GAME_SESSION_URI = + "spiffe://firemud/ns/other/sa/game-session-service"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String REQUEST_ID = "22222222-2222-4222-8222-222222222222"; + private static final String TENANT_ID = "33333333-3333-4333-8333-333333333333"; + private static final String SOURCE_OPERATION_ID = "44444444-4444-4444-8444-444444444444"; + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void sameNamespaceGameSessionPeerReachesEachRealCanonicalLaunchHandlerWithoutBearer() { + AuthTokenInterceptor interceptor = interceptor(); + Harness harness = harness(); + when(harness.launchDescriptorService().resolveLaunchDescriptor(any())) + .thenThrow(new IllegalStateException("intentional owner read probe")); + when(harness.launchDescriptorService() + .getLaunchDescriptor( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString())) + .thenThrow(new IllegalArgumentException("intentional exact read probe")); + when(harness.completeLaunchBindingService() + .getCompleteLaunchBinding( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString())) + .thenThrow(new IllegalArgumentException("intentional complete read probe")); + + DispatchResult resolve = + dispatchHandler( + interceptor, + harness, + GAME_SESSION_URI, + new Metadata(), + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor); + DispatchResult descriptorRead = + dispatchHandler( + interceptor, + harness, + GAME_SESSION_URI, + new Metadata(), + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor); + DispatchResult completeRead = + dispatchHandler( + interceptor, + harness, + GAME_SESSION_URI, + new Metadata(), + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding); + + assertThat(resolve.dispatched()).isTrue(); + assertThat(resolve.closedStatus()).isNull(); + assertThat(resolve.response()).isNotNull(); + assertThat(descriptorRead.dispatched()).isTrue(); + assertThat(descriptorRead.closedStatus()).isNull(); + assertThat(descriptorRead.response()).isNotNull(); + assertThat(completeRead.dispatched()).isTrue(); + assertThat(completeRead.closedStatus()).isNull(); + assertThat(completeRead.response()).isNotNull(); + verify(harness.launchDescriptorService()).resolveLaunchDescriptor(any()); + verify(harness.launchDescriptorService()) + .getLaunchDescriptor( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString()); + verify(harness.completeLaunchBindingService()) + .getCompleteLaunchBinding( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString()); + } + + @Test + void workloadPeerMustMatchNamespaceAndServiceEvenWhenMethodSkipsBearerValidation() { + AuthTokenInterceptor interceptor = interceptor(); + for (String peerUri : List.of("", OTHER_NAMESPACE_GAME_SESSION_URI, ACCOUNT_URI)) { + GrpcPeerIdentity peer = peerUri.isEmpty() ? null : identity(peerUri); + assertAllLaunchHandlersDeny(interceptor, peer, new Metadata()); + } + } + + @Test + void playerJwtCannotSubstituteForMissingGameSessionPeerIdentity() { + JwtUtil jwtUtil = new JwtUtil("valid-test-player-jwt-secret-123456", 60_000L); + Metadata playerJwt = new Metadata(); + playerJwt.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer " + jwtUtil.generateToken("player-42", Map.of("role", "player"))); + + assertAllLaunchHandlersDeny(interceptor(jwtUtil), null, playerJwt); + } + + @Test + void unlistedGameDesignMethodStillRequiresBearerToken() { + AuthTokenInterceptor interceptor = interceptor(); + DispatchResult result = + dispatch( + interceptor, + null, + new Metadata(), + UNLISTED_METHOD, + GetPublishedReleaseBundleRequest.getDefaultInstance(), + GetPublishedReleaseBundleResponse.getDefaultInstance(), + GetPublishedReleaseBundleRequest.getDefaultInstance(), + (request, observer) -> {}); + + assertThat(result.dispatched()).isFalse(); + assertThat(result.closedStatus()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(result.response()).isNull(); + } + + private static void assertAllLaunchHandlersDeny( + AuthTokenInterceptor interceptor, GrpcPeerIdentity peer, Metadata headers) { + assertDenied( + interceptor, + peer, + headers, + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + peer, + headers, + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + peer, + headers, + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding, + response -> response.getError().getCode()); + } + + private static void assertDenied( + AuthTokenInterceptor interceptor, + GrpcPeerIdentity peer, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + HandlerCall handlerCall, + java.util.function.Function errorCode) { + Harness harness = harness(); + DispatchResult result = + dispatchHandler( + interceptor, + harness, + peer, + headers, + methodName, + defaultRequest, + defaultResponse, + request, + handlerCall); + + assertThat(result.dispatched()).isTrue(); + assertThat(result.closedStatus()).isNull(); + assertThat(result.response()).isNotNull(); + assertThat(errorCode.apply(result.response())).isEqualTo("PERMISSION_DENIED"); + verifyNoInteractions( + harness.launchDescriptorService(), harness.completeLaunchBindingService()); + } + + private static + DispatchResult dispatchHandler( + AuthTokenInterceptor interceptor, + Harness harness, + String peerUri, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + HandlerCall handlerCall) { + return dispatchHandler( + interceptor, + harness, + peerUri == null ? null : identity(peerUri), + headers, + methodName, + defaultRequest, + defaultResponse, + request, + handlerCall); + } + + private static + DispatchResult dispatchHandler( + AuthTokenInterceptor interceptor, + Harness harness, + GrpcPeerIdentity peer, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + HandlerCall handlerCall) { + return dispatch( + interceptor, + peer, + headers, + methodName, + defaultRequest, + defaultResponse, + request, + (message, observer) -> handlerCall.invoke(harness.service(), message, observer)); + } + + private static + DispatchResult dispatch( + AuthTokenInterceptor interceptor, + GrpcPeerIdentity peer, + Metadata headers, + String methodName, + RequestT defaultRequest, + ResponseT defaultResponse, + RequestT request, + java.util.function.BiConsumer> handler) { + ServerCall call = mock(); + when(call.getMethodDescriptor()) + .thenReturn(method(methodName, defaultRequest, defaultResponse)); + AtomicReference closedStatus = new AtomicReference<>(); + AtomicBoolean dispatched = new AtomicBoolean(); + AtomicReference response = new AtomicReference<>(); + doAnswer( + invocation -> { + Status status = invocation.getArgument(0); + closedStatus.set(status.getCode()); + return null; + }) + .when(call) + .close(any(), any()); + + ServerCallHandler next = + (serverCall, ignoredHeaders) -> { + dispatched.set(true); + return new ServerCall.Listener<>() { + @Override + public void onMessage(RequestT message) { + handler.accept( + message, + new StreamObserver<>() { + @Override + public void onNext(ResponseT value) { + response.set(value); + } + + @Override + public void onError(Throwable throwable) { + closedStatus.set(Status.fromThrowable(throwable).getCode()); + } + + @Override + public void onCompleted() {} + }); + } + }; + }; + + Runnable invoke = + () -> { + ServerCall.Listener listener = interceptor.interceptCall(call, headers, next); + if (listener != null) { + listener.onMessage(request); + } + }; + if (peer == null) { + invoke.run(); + } else { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invoke); + } + return new DispatchResult<>(dispatched.get(), closedStatus.get(), response.get()); + } + + private static + MethodDescriptor method( + String methodName, RequestT defaultRequest, ResponseT defaultResponse) { + return MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(methodName) + .setRequestMarshaller(ProtoUtils.marshaller(defaultRequest)) + .setResponseMarshaller(ProtoUtils.marshaller(defaultResponse)) + .build(); + } + + private static AuthTokenInterceptor interceptor() { + return new AuthTokenInterceptor(mock(JwtUtil.class), Set.copyOf(ALLOWLISTED_METHODS)); + } + + private static AuthTokenInterceptor interceptor(JwtUtil jwtUtil) { + return new AuthTokenInterceptor(jwtUtil, Set.copyOf(ALLOWLISTED_METHODS)); + } + + private static Harness harness() { + LaunchDescriptorService launchDescriptorService = mock(LaunchDescriptorService.class); + CompleteLaunchBindingService completeLaunchBindingService = + mock(CompleteLaunchBindingService.class); + GameDesignGrpcService service = + new GameDesignGrpcService( + mock(PingService.class), + mock(RevisionService.class), + mock(VersionService.class), + launchDescriptorService, + completeLaunchBindingService, + mock(TemplateRemapSetService.class), + mock(VersionAssetArtifactService.class), + mock(SettingsAuthorityService.class), + mock(GameAuthoredHelpTopicService.class), + new TemporalVersionPublishWorkflowMetadataResolver(Optional.empty(), Optional.empty()), + new SimpleMeterRegistry()); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + return new Harness(service, launchDescriptorService, completeLaunchBindingService); + } + + private static ResolveLaunchDescriptorRequest resolveRequest() { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(TENANT_ID) + .setGameTemplateId(77L) + .setControlPlaneRequestId("launch-auth-control-plane") + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID) + .setExpectedAuthoredWorldSourceEvidenceDigest(DIGEST) + .build(); + } + + private static GetLaunchDescriptorRequest readRequest() { + return GetLaunchDescriptorRequest.newBuilder() + .setRequestId(REQUEST_ID) + .setCanonicalTenantId(TENANT_ID) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("launch-auth-control-plane") + .setExpectedRequestDigest(DIGEST) + .setExpectedResultDigest(DIGEST) + .build(); + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private record Harness( + GameDesignGrpcService service, + LaunchDescriptorService launchDescriptorService, + CompleteLaunchBindingService completeLaunchBindingService) {} + + private record DispatchResult( + boolean dispatched, Status.Code closedStatus, ResponseT response) {} + + @FunctionalInterface + private interface HandlerCall { + void invoke( + GameDesignGrpcService service, + RequestT request, + StreamObserver responseObserver); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index bb5a58ce07..17d1699f9d 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -51,7 +51,25 @@ class TenantIdentityGrpcAuthWiringTest { private static final String FRESH_CREATION_METHOD = "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation"; + private static final String POLICY_RESOLVE_METHOD = + "game_design.v1.PublishedRealmEntryPolicyService/ResolvePublishedRealmEntryPolicy"; + private static final String POLICY_LIST_METHOD = + "game_design.v1.PublishedRealmEntryPolicyService/ListPublishedRealmEntryPolicies"; + private static final String RESOLVE_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor"; + private static final String GET_LAUNCH_DESCRIPTOR_METHOD = + "gamedesign.v1.GameDesignService/GetLaunchDescriptor"; + private static final String GET_COMPLETE_LAUNCH_BINDING_METHOD = + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding"; private static final String OTHER_METHOD = "gamedesign.v1.TenantIdentityService/UnlistedMethod"; + private static final List ALLOWLISTED_METHODS = + List.of( + FRESH_CREATION_METHOD, + POLICY_RESOLVE_METHOD, + POLICY_LIST_METHOD, + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + GET_LAUNCH_DESCRIPTOR_METHOD, + GET_COMPLETE_LAUNCH_BINDING_METHOD); private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String SOURCE_KEY = "fresh-owner-key-91"; @@ -62,10 +80,11 @@ class TenantIdentityGrpcAuthWiringTest { GameTenantCreationDigest.requestDigest("test", REQUEST_ID, SOURCE_KEY, "Fresh Realm", null); @Test - void defaultAndProductionProfilesAllowOnlyFreshReadAndRequireClientTls() throws IOException { + void defaultAndProductionProfilesKeepExactReadAllowlistAndRequireClientTls() + throws IOException { for (String file : List.of("application.yml", "application-prod.yml")) { GrpcConfiguration config = load(file); - assertThat(config.publicMethods()).containsExactly(FRESH_CREATION_METHOD); + assertThat(config.publicMethods()).containsExactlyElementsOf(ALLOWLISTED_METHODS); assertThat(config.clientAuth()).isEqualTo("REQUIRE"); } } @@ -180,7 +199,7 @@ private static void withConfiguredInterceptor(Consumer act context -> { assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(FRESH_CREATION_METHOD); + .containsExactlyElementsOf(ALLOWLISTED_METHODS); action.accept(context.getBean(AuthTokenInterceptor.class)); }); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java new file mode 100644 index 0000000000..3917711ae3 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -0,0 +1,1011 @@ +package net.firedevops.firemud.gamedesign.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; +import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; +import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; +import net.firedevops.firemud.gamedesign.entity.Version; +import net.firedevops.firemud.gamedesign.model.PublishParticipantKey; +import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository.AuthoredWorldVersionStateSnapshot; +import net.firedevops.firemud.gamedesign.repository.VersionRepository; +import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; +import net.firedevops.firemud.gamedesign.service.PublishedArtifactDigest; +import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.test.util.ReflectionTestUtils; + +class CompleteLaunchBindingServiceImplTest { + @Test + void selectorReleaseIsAssembledFromImmutableLocalBundleWithoutMutableOwnerReads() + throws Exception { + var selector = + PublishedWorldSelectorFixtures.evidence( + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_ID, + PRIVATE_TENANT_KEY, + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + var selected = + new PublishedReleaseBundleDto( + bundle.id(), + bundle.tenantId(), + bundle.versionId(), + bundle.versionNumber(), + "v2", + selector.request().publishWorkflowId(), + bundle.manifestHash(), + bundle.requiredManifestAssetKeys(), + PublishedWorldSelectorFixtures.participants(VERSION_ID, selector), + bundle.commandDefinitions(), + bundle.generationConfigRevision(), + bundle.scriptOnly(), + bundle.scriptPatchVersion(), + bundle.publishedAt(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.publishedReleaseBundleRef(), + bundle.manifestSchemaVersion(), + bundle.artifactDigests(), + selector); + givenBundle(selected); + var result = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + assertEquals(2, result.releaseAttestation().schemaVersion()); + assertEquals(selector, result.releaseAttestation().worldStartLocationEvidence()); + result.releaseAttestation().requireValid(descriptor); + verifyReadOnlyCallsOnly(); + } + + private static final String NAMESPACE = "test"; + private static final UUID READ_REQUEST_ID = + UUID.fromString("72345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("82345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_REGISTRATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "silver-march"; + private static final String PRIVATE_TENANT_KEY = "game-owner-key-901"; + private static final long VERSION_ID = 7L; + private static final int VERSION_NUMBER = 12; + private static final long BUNDLE_ID = 211L; + private static final String CONTROL_PLANE_REQUEST_ID = "launch-request-901"; + private static final String BUNDLE_REF = "opaque-release-reference-from-owner"; + private static final String WORKFLOW_ID = + "publish:game-owner-key-901:publish-request:publish-901"; + private static final String MANIFEST_HASH = "sha256:" + "c".repeat(64); + private static final String CONTENT_DIGEST = "d".repeat(64); + private static final String ABILITY_SCHEMA_DIGEST = "sha256:" + "e".repeat(64); + private static final String ARTIFACT_DIGEST = "sha256:" + "f".repeat(64); + + @Mock private LaunchDescriptorService launchDescriptorService; + @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; + @Mock private PublishedReleaseBundleService publishedReleaseBundleService; + @Mock private VersionRepository versionRepository; + + private CompleteLaunchBindingServiceImpl service; + private AuthoredWorldSourceEvidence source; + private AuthoredWorldLaunchDescriptorEvidence descriptor; + private ResolvedLaunchDescriptorDto resolved; + private PublishedReleaseBundleDto bundle; + private Version version; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + source = sourceEvidence(WORLD_SLUG); + descriptor = descriptorEvidence(source); + resolved = resolvedDescriptor(descriptor); + bundle = validBundle(); + version = canonicalVersion(); + service = + new CompleteLaunchBindingServiceImpl( + launchDescriptorService, + authoredWorldSourceRepository, + publishedReleaseBundleService, + versionRepository); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); + givenValidSnapshot(); + } + + @Test + void returnsImmutableFullBindingUsingTheDescriptorEpochAfterCurrentVersionStateAdvances() { + var first = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(44L); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.RETIRED, 44L))); + + var later = + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest()); + + assertEquals(descriptor, first.descriptor()); + assertEquals(descriptor.versionStateEpoch(), first.releaseAttestation().versionStateEpoch()); + assertEquals(first.releaseAttestation(), later.releaseAttestation()); + assertEquals( + first.releaseAttestation().evidenceDigest(), later.releaseAttestation().evidenceDigest()); + verifyReadOnlyCallsOnly(); + } + + @Test + void rejectsMissingOrSubstitutedSourceEvidence() { + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn(Optional.empty()); + assertDenied(); + + AuthoredWorldSourceEvidence substituted = sourceEvidence("other-world"); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + substituted, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 17L))); + assertDenied(); + } + + @Test + void rejectsMissingOrSubstitutedReleaseIdentityAndReference() { + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_TENANT_KEY, VERSION_ID)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID + 1, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + bundle.publishedReleaseBundleRef(), + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + "substituted-reference", + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + "other-private-key", + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID + 1, + VERSION_NUMBER, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER + 1, + BUNDLE_REF, + bundle.canonicalTenantId(), + bundle.canonicalVersionId(), + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + } + + @Test + void rejectsMissingCanonicalVersionOrContradictoryPersistedGameProvenance() { + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.empty()); + assertDenied(); + + version.setIdentitySourceGameRowId(74L); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + assertDenied(); + } + + @Test + void rejectsCanonicalTenantOrVersionUuidSubstitution() { + UUID otherCanonicalTenant = UUID.fromString("92345678-1234-4234-8234-123456789abc"); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + otherCanonicalTenant, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + UUID otherCanonicalVersion = UUID.fromString("a2345678-1234-4234-8234-123456789abc"); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + otherCanonicalVersion, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + @Test + void requiresOneConsistentOwnerSnapshotAndMonotonicHistoricalEpoch() { + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 16L))); + assertDenied(); + + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.RETIRED, 23L))); + assertDenied(); + } + + @Test + void rejectsReleaseVersionUuidThatDiffersFromTheSameSourceSnapshot() { + UUID differentVersionId = UUID.fromString("b2345678-1234-4234-8234-123456789abc"); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, differentVersionId, VersionLifecycleState.PUBLISHED, 23L))); + + assertDenied(); + verify(versionRepository, never()) + .findByCanonicalTenantIdAndCanonicalVersionId(CANONICAL_TENANT_ID, CANONICAL_VERSION_ID); + } + + @Test + void rejectsAbsentOrNilCanonicalVersionUuidWithoutNumericInference() { + UUID nil = new UUID(0L, 0L); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + nil, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + bundle.scriptOnly(), + bundle.scriptPatchVersion())); + assertDenied(); + verify(versionRepository, never()) + .findByCanonicalTenantIdAndCanonicalVersionId(CANONICAL_TENANT_ID, nil); + } + + @Test + void rejectsScriptOnlyVersionMetadata() { + version.setScriptOnly(true); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + assertDenied(); + + version.setScriptOnly(false); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + true, + "patch-1")); + assertDenied(); + } + + @Test + void rejectsMissingOrContradictoryManifestAndArtifactProof() { + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + null, + bundle.manifestHash(), + null, + false, + null)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + "not-a-digest", + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + List.of("world.navmesh"), + bundle.participantDigests(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + List.of(), + false, + null)); + assertDenied(); + } + + @Test + void rejectsMissingFailedUnsupportedAndMisorderedParticipantEvidence() { + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + List.of(), + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List unsupported = + new java.util.ArrayList<>(bundle.participantDigests()); + unsupported.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 99, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + unsupported, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List failed = + new java.util.ArrayList<>(bundle.participantDigests()); + failed.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 2, + null, + "OWNER_FAILED", + "owner failed")); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + failed, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List misordered = + new java.util.ArrayList<>(bundle.participantDigests()); + java.util.Collections.swap(misordered, 0, 1); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + misordered, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + @Test + void requiresGameLogicOwnedAbilityProofAndOneSharedParticipantCommit() { + List missingAbility = + new java.util.ArrayList<>(bundle.participantDigests()); + missingAbility.set( + 2, + new PublishParticipantDigestDto( + PublishParticipantKey.GAME_LOGIC.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 1, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + missingAbility, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List mismatchedCommit = + new java.util.ArrayList<>(bundle.participantDigests()); + mismatchedCommit.set( + 4, + new PublishParticipantDigestDto( + PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), + Long.toString(VERSION_ID), + null, + "different-commit", + CONTENT_DIGEST, + 1, + null, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + mismatchedCommit, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + + List wrongAbilityOwner = + new java.util.ArrayList<>(bundle.participantDigests()); + wrongAbilityOwner.set( + 0, + new PublishParticipantDigestDto( + PublishParticipantKey.WORLD_MANAGEMENT.name(), + Long.toString(VERSION_ID), + null, + "commit-1", + CONTENT_DIGEST, + 2, + ABILITY_SCHEMA_DIGEST, + null, + null)); + givenBundle( + copyBundle( + bundle, + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + BUNDLE_REF, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + bundle.requiredManifestAssetKeys(), + wrongAbilityOwner, + bundle.manifestSchemaVersion(), + bundle.manifestHash(), + bundle.artifactDigests(), + false, + null)); + assertDenied(); + } + + private void givenValidSnapshot() { + when(launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())) + .thenReturn(resolved); + when(authoredWorldSourceRepository.readVersionStateSnapshot( + NAMESPACE, + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + source.evidenceDigest(), + VERSION_ID)) + .thenReturn( + Optional.of( + new AuthoredWorldVersionStateSnapshot( + source, CANONICAL_VERSION_ID, VersionLifecycleState.PUBLISHED, 23L))); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID)) + .thenReturn(bundle); + when(versionRepository.findByCanonicalTenantIdAndCanonicalVersionId( + CANONICAL_TENANT_ID, CANONICAL_VERSION_ID)) + .thenReturn(Optional.of(version)); + } + + private void givenBundle(PublishedReleaseBundleDto replacement) { + doReturn(replacement) + .when(publishedReleaseBundleService) + .getPublishedReleaseBundle(PRIVATE_TENANT_KEY, VERSION_ID); + } + + private void assertDenied() { + IllegalArgumentException denied = + assertThrows( + IllegalArgumentException.class, + () -> + service.getCompleteLaunchBinding( + READ_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + CONTROL_PLANE_REQUEST_ID, + descriptor.requestDigest(), + descriptor.resultDigest())); + assertTrue( + denied.getMessage().startsWith("COMPLETE_LAUNCH_BINDING_") + || denied.getMessage().startsWith("LAUNCH_DESCRIPTOR_") + || denied.getMessage().startsWith("AUTHORED_WORLD_SOURCE_")); + verifyReadOnlyCallsOnly(); + } + + private void verifyReadOnlyCallsOnly() { + verify(launchDescriptorService, never()).resolveLaunchDescriptor(any()); + verify(authoredWorldSourceRepository, never()) + .register( + anyString(), any(UUID.class), any(UUID.class), anyString(), anyString(), anyString()); + verify(publishedReleaseBundleService, never()) + .createFullVersionBundle(any(), anyString(), any(), anyString(), any()); + verify(versionRepository, never()).save(any(Version.class)); + verify(versionRepository, never()).delete(any(Version.class)); + } + + private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March", + 73L, + PRIVATE_TENANT_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + "silver-tenant", + worldSlug, + "Silver March", + 73L, + PRIVATE_TENANT_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( + AuthoredWorldSourceEvidence sourceEvidence) { + AuthoredWorldLaunchDescriptorEvidence.Request request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST_ID, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence.evidenceDigest(), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-71234567-1234-4234-8234-123456789abc", + VERSION_ID, + false, + null, + "{}", + "generation-config-12", + 17L, + BUNDLE_ID, + BUNDLE_REF, + false, + null); + } + + private ResolvedLaunchDescriptorDto resolvedDescriptor( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private PublishedReleaseBundleDto validBundle() { + String artifactObjectKey = "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()); + return new PublishedReleaseBundleDto( + BUNDLE_ID, + PRIVATE_TENANT_KEY, + VERSION_ID, + VERSION_NUMBER, + "v1", + WORKFLOW_ID, + MANIFEST_HASH, + List.of("world.navmesh"), + validParticipants(), + List.of("{\"commandId\":\"look\"}"), + "generation-config-12", + false, + null, + null, + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + BUNDLE_REF, + 1, + List.of( + new PublishedArtifactDigest( + "world.navmesh", + "world-navmesh", + artifactObjectKey, + ARTIFACT_DIGEST, + "application/octet-stream", + 1))); + } + + private List validParticipants() { + return List.of( + participant(PublishParticipantKey.WORLD_MANAGEMENT.name(), 3, null), + participant(PublishParticipantKey.ENTITY_MANAGEMENT.name(), 2, null), + participant(PublishParticipantKey.GAME_LOGIC.name(), 1, ABILITY_SCHEMA_DIGEST), + participant(PublishParticipantKey.AUTOMATION_SCRIPTING.name(), 5, null), + participant(PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE.name(), 1, null)); + } + + private PublishParticipantDigestDto participant( + String participantKey, int digestSchemaVersion, String abilitySchemaDigest) { + return new PublishParticipantDigestDto( + participantKey, + Long.toString(VERSION_ID), + null, + "commit-12", + CONTENT_DIGEST, + digestSchemaVersion, + abilitySchemaDigest, + null, + null); + } + + private Version canonicalVersion() { + Version result = new Version(); + result.setId(VERSION_ID); + result.setTenantId(PRIVATE_TENANT_KEY); + result.setCanonicalTenantId(CANONICAL_TENANT_ID); + result.setCanonicalVersionId(CANONICAL_VERSION_ID); + result.setIdentitySourceGameRowId(73L); + result.setIdentitySourceGameTenantKey(PRIVATE_TENANT_KEY); + result.setIdentitySourceProvenanceKind("NEW_GAME_ROW"); + result.setVersionNumber((int) VERSION_NUMBER); + result.setVersionState(VersionLifecycleState.PUBLISHED); + result.setVersionStateEpoch(23L); + return result; + } + + private PublishedReleaseBundleDto copyBundle( + PublishedReleaseBundleDto original, + long id, + String tenantId, + long versionId, + int versionNumber, + String releaseRef, + UUID canonicalTenantId, + UUID canonicalVersionId, + List requiredKeys, + List participants, + Integer manifestSchemaVersion, + String manifestHash, + List artifacts, + boolean scriptOnly, + String scriptPatchVersion) { + return new PublishedReleaseBundleDto( + id, + tenantId, + versionId, + versionNumber, + original.attestationSchemaVersion(), + original.publishWorkflowId(), + manifestHash, + requiredKeys, + participants, + original.commandDefinitions(), + original.generationConfigRevision(), + scriptOnly, + scriptPatchVersion, + original.publishedAt(), + canonicalTenantId, + canonicalVersionId, + releaseRef, + manifestSchemaVersion, + artifacts); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index 6cdbaa103c..ed3b6d2880 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -3,12 +3,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; @@ -29,6 +33,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceAuthTest { @AfterEach @@ -45,6 +50,7 @@ void adminMethodsReturnPermissionDeniedErrorDetail() { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -74,7 +80,7 @@ public void onCompleted() {} } @Test - void launchAttestationReadMethodsAllowInternalServiceIdentity() { + void launchAttestationReadAndCanonicalResolveRequireWorkloadIdentity() { VersionService versionService = Mockito.mock(VersionService.class); LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); Mockito.when(versionService.getPublishedReleaseBundle("1", 7L)) @@ -93,12 +99,55 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { false, null, java.time.LocalDateTime.parse("2026-04-14T12:00:00"))); - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "1", 9L, "cp-1", null, null, null, null)) + UUID canonicalTenantId = UUID.fromString("12345678-1234-4234-8234-123456789abc"); + UUID sourceOperationId = UUID.fromString("22345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request launchRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "cp-1", + canonicalTenantId, + "silver-march", + sourceOperationId, + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + launchRequest, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:" + canonicalTenantId + ":7:11", + false, + null); + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenReturn( new ResolvedLaunchDescriptorDto( - "ld-1", "1", 9L, "cp-1", 7L, null, "{}", "genrev-1", 11L, 11L, "prb:1:7:11", null)); + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence)); GameDesignGrpcService service = new GameDesignGrpcService( @@ -106,6 +155,7 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { Mockito.mock(RevisionService.class), versionService, launchDescriptorService, + Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -114,6 +164,7 @@ void launchAttestationReadMethodsAllowInternalServiceIdentity() { new SimpleMeterRegistry()); SessionContext.setContext(null, List.of(), Map.of(), true, "game-session-service", "gs-1"); + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); AtomicReference bundleRef = new AtomicReference<>(); service.getPublishedReleaseBundle( @@ -132,24 +183,36 @@ public void onCompleted() {} }); AtomicReference descriptorRef = new AtomicReference<>(); - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - descriptorRef.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") + .orElseThrow(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .run( + () -> + service.resolveLaunchDescriptor( + ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(canonicalTenantId.toString()) + .setGameTemplateId(9L) + .setControlPlaneRequestId("cp-1") + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId(sourceOperationId.toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(), + new StreamObserver<>() { + @Override + public void onNext(ResolveLaunchDescriptorResponse value) { + descriptorRef.set(value); + } + + @Override + public void onError(Throwable t) { + throw new AssertionError(t); + } + + @Override + public void onCompleted() {} + })); assertNotNull(bundleRef.get()); assertEquals("", bundleRef.get().getError().getCode()); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java index 9c8499397d..760db9b802 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java @@ -38,6 +38,7 @@ class GameDesignGrpcServiceHelpTopicTest { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), + Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java index 95018adc29..a95a14bbef 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java @@ -59,6 +59,7 @@ void setUp() { revisionService, versionService, launchDescriptorService, + Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 436a406852..379e2079fe 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -2,12 +2,17 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import com.google.protobuf.UnknownFieldSet; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.gamedesign.dto.AppliedWorldDesignMutationDto; import net.firedevops.firemud.gamedesign.dto.DesignControlPlaneDigestDto; @@ -25,6 +30,7 @@ import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; +import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; @@ -47,6 +53,8 @@ import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.GetTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateRequest; @@ -82,13 +90,20 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; class GameDesignGrpcServiceTest { + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID AUTHORED_SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); private final PingService pingService = Mockito.mock(PingService.class); private final RevisionService revisionService = Mockito.mock(RevisionService.class); private final VersionService versionService = Mockito.mock(VersionService.class); private final LaunchDescriptorService launchDescriptorService = Mockito.mock(LaunchDescriptorService.class); + private final CompleteLaunchBindingService completeLaunchBindingService = + Mockito.mock(CompleteLaunchBindingService.class); private final TemplateRemapSetService templateRemapSetService = Mockito.mock(TemplateRemapSetService.class); private final VersionAssetArtifactService versionAssetArtifactService = @@ -105,6 +120,7 @@ class GameDesignGrpcServiceTest { revisionService, versionService, launchDescriptorService, + completeLaunchBindingService, templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, @@ -1054,122 +1070,234 @@ void getPublishedReleaseBundleRejectsUnsupportedSchema() { @Test void resolveLaunchDescriptorReturnsDeterministicDescriptor() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-1", null, null, null, null)) - .thenReturn( - new ResolvedLaunchDescriptorDto( - "ld-1", - "tenant-1", - 9L, - "cp-1", - 7L, - "patch-1", - "{}", - "genrev-1", - 11L, - 11L, - "prb:tenant-1:7:11", - "")); + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-1"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) + .thenReturn(launchDto(evidence)); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-1") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-1"), observerFor(ref))); assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); assertEquals("genrev-1", ref.get().getLaunchDescriptor().getGenerationConfigRevision()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService).resolveLaunchDescriptor(request); } @Test void resolveLaunchDescriptorSurfacesTypedReleaseBundleNotFoundError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-2", null, null, null, null)) + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenThrow( new IllegalArgumentException( "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version")); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-2") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } - - @Override - public void onCompleted() {} - }); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-2"), observerFor(ref))); assertEquals("RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); } @Test void resolveLaunchDescriptorSurfacesTypedRemapRequiredError() { - Mockito.when( - launchDescriptorService.resolveLaunchDescriptor( - "tenant-1", 9L, "cp-3", null, null, null, null)) + Mockito.when(launchDescriptorService.resolveLaunchDescriptor(Mockito.any())) .thenThrow( new IllegalArgumentException( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId")); AtomicReference ref = new AtomicReference<>(); - try (MockedStatic ignored = Mockito.mockStatic(AdminRoleGuard.class)) { - service.resolveLaunchDescriptor( - ResolveLaunchDescriptorRequest.newBuilder() - .setTenantId("tenant-1") - .setGameTemplateId(9L) - .setControlPlaneRequestId("cp-3") - .build(), - new StreamObserver<>() { - @Override - public void onNext(ResolveLaunchDescriptorResponse value) { - ref.set(value); - } + underLaunchPeer( + "game-session-service", + () -> service.resolveLaunchDescriptor(resolveRequest("cp-3"), observerFor(ref))); - @Override - public void onError(Throwable t) { - throw new AssertionError(t); - } + assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + } - @Override - public void onCompleted() {} - }); - } + @Test + void getLaunchDescriptorReturnsExactBoundReadback() { + AuthoredWorldLaunchDescriptorEvidence.Request request = launchRequest("cp-read"); + AuthoredWorldLaunchDescriptorEvidence evidence = launchEvidence(request); + UUID readRequestId = UUID.fromString("32345678-1234-4234-8234-123456789abc"); + Mockito.when( + launchDescriptorService.getLaunchDescriptor( + readRequestId, + CANONICAL_TENANT_ID, + "silver-march", + "cp-read", + evidence.requestDigest(), + evidence.resultDigest())) + .thenReturn(launchDto(evidence)); + + var readRequest = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(readRequestId.toString()) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest(evidence.requestDigest()) + .setExpectedResultDigest(evidence.resultDigest()) + .build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "world-management-service", () -> service.getLaunchDescriptor(readRequest, observerFor(ref))); + + assertEquals(readRequestId.toString(), ref.get().getRequestId()); + assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); + assertEquals( + evidence.resultDigest(), + ref.get().getLaunchDescriptor().getAuthoredWorldBinding().getResultDigest()); + Mockito.verify(launchDescriptorService) + .getLaunchDescriptor( + readRequestId, + CANONICAL_TENANT_ID, + "silver-march", + "cp-read", + evidence.requestDigest(), + evidence.resultDigest()); + } - assertEquals("LAUNCH_REMAP_REQUIRED", ref.get().getError().getCode()); + @Test + void resolveLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + var request = + resolveRequest("cp-unknown").toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void getLaunchDescriptorRejectsUnknownFieldsBeforeOwnerRead() { + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-read") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", () -> service.getLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); + } + + @Test + void completeLaunchBindingRejectsUnlistedPeerBeforeOwnerRead() { + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-complete") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .build(); + AtomicReference ref = + new AtomicReference<>(); + underLaunchPeer( + "automation-scripting-service", + () -> service.getCompleteLaunchBinding(request, observerFor(ref))); + + assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(completeLaunchBindingService); + } + + @Test + void completeLaunchBindingRejectsUnknownFieldsBeforeOwnerRead() { + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId("32345678-1234-4234-8234-123456789abc") + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-complete") + .setExpectedRequestDigest("sha256:" + "a".repeat(64)) + .setExpectedResultDigest("sha256:" + "b".repeat(64)) + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build(); + AtomicReference ref = + new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> service.getCompleteLaunchBinding(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(completeLaunchBindingService); + } + + @Test + void completeLaunchBindingPreservesTypedOwnerDenial() { + UUID readRequestId = UUID.fromString("32345678-1234-4234-8234-123456789abc"); + String requestDigest = "sha256:" + "a".repeat(64); + String resultDigest = "sha256:" + "b".repeat(64); + Mockito.when( + completeLaunchBindingService.getCompleteLaunchBinding( + readRequestId, + CANONICAL_TENANT_ID, + "silver-march", + "cp-complete", + requestDigest, + resultDigest)) + .thenThrow( + new IllegalArgumentException( + "COMPLETE_LAUNCH_BINDING_RELEASE_BUNDLE_NOT_FOUND: matching release is absent")); + var request = + GetLaunchDescriptorRequest.newBuilder() + .setRequestId(readRequestId.toString()) + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setWorldSlug("silver-march") + .setControlPlaneRequestId("cp-complete") + .setExpectedRequestDigest(requestDigest) + .setExpectedResultDigest(resultDigest) + .build(); + AtomicReference ref = + new AtomicReference<>(); + underLaunchPeer( + "game-session-service", + () -> service.getCompleteLaunchBinding(request, observerFor(ref))); + + assertEquals("COMPLETE_LAUNCH_BINDING_RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); + Mockito.verify(completeLaunchBindingService) + .getCompleteLaunchBinding( + readRequestId, + CANONICAL_TENANT_ID, + "silver-march", + "cp-complete", + requestDigest, + resultDigest); + } + + @Test + void resolveLaunchDescriptorRejectsNonCanonicalTenantUuidBeforeOwnerRead() { + var request = resolveRequest("cp-invalid-uuid").toBuilder().setCanonicalTenantId("not-a-uuid").build(); + AtomicReference ref = new AtomicReference<>(); + underLaunchPeer( + "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); + + assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); + Mockito.verifyNoInteractions(launchDescriptorService); } @Test @@ -1480,6 +1608,79 @@ private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } + private void underLaunchPeer(String serviceName, Runnable operation) { + ReflectionTestUtils.setField(service, "workloadNamespace", "test"); + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + serviceName).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request launchRequest( + String controlPlaneRequestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + controlPlaneRequestId, + CANONICAL_TENANT_ID, + "silver-march", + AUTHORED_SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence launchEvidence( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:" + CANONICAL_TENANT_ID + ":7:11", + false, + null); + } + + private ResolvedLaunchDescriptorDto launchDto( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return new ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private ResolveLaunchDescriptorRequest resolveRequest(String controlPlaneRequestId) { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setGameTemplateId(9L) + .setControlPlaneRequestId(controlPlaneRequestId) + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId(AUTHORED_SOURCE_OPERATION_ID.toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(); + } + private TemplateRemapSetDto sampleRemapSetDto( TemplateRemapSetStatus status, String approvalReason, LocalDateTime approvedAt) { return new TemplateRemapSetDto( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 78f7b1d6ec..378f8aa1c8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -1,13 +1,28 @@ package net.firedevops.firemud.gamedesign.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.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.clearInvocations; +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.time.LocalDateTime; import java.util.List; import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.entity.LaunchDescriptor; @@ -15,6 +30,7 @@ import net.firedevops.firemud.gamedesign.model.TemplateReferencePhase; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameTemplateLaunchConfigView; import net.firedevops.firemud.gamedesign.repository.GameTemplateRepository; import net.firedevops.firemud.gamedesign.repository.LaunchDescriptorRepository; @@ -24,21 +40,111 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.test.util.ReflectionTestUtils; import tools.jackson.databind.ObjectMapper; class LaunchDescriptorServiceImplTest { + private static final String NAMESPACE = "test"; + private static final UUID CANONICAL_TENANT_ID = + UUID.fromString("12345678-1234-4234-8234-123456789abc"); + private static final UUID CANONICAL_VERSION_ID = + UUID.fromString("c472ebd1-56d8-49df-b8fa-85963dd940f8"); + private static final UUID SOURCE_OPERATION_ID = + UUID.fromString("22345678-1234-4234-8234-123456789abc"); + private static final UUID SOURCE_REGISTRATION_ID = + UUID.fromString("32345678-1234-4234-8234-123456789abc"); + private static final String WORLD_SLUG = "silver-march"; + private static final String PRIVATE_SOURCE_TENANT_KEY = "game-owner-key-901"; + private static final String PUBLISHED_RELEASE_BUNDLE_REF = "opaque-release-reference-from-owner"; + private static final String MANIFEST_HASH = "sha256:" + "a".repeat(64); + @Mock private GameTemplateRepository gameTemplateRepository; @Mock private LaunchDescriptorRepository launchDescriptorRepository; @Mock private VersionRepository versionRepository; @Mock private PublishedReleaseBundleService publishedReleaseBundleService; @Mock private TemplateRemapSetService templateRemapSetService; + @Mock private GameAuthoredWorldSourceRepository authoredWorldSourceRepository; private LaunchDescriptorServiceImpl service; + @Test + void completeSelectorV2ResolvesTheUnchangedDescriptorV1Binding() throws Exception { + var request = request("cp-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + var bundle = selectorBundle(false); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(bundle); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(7L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + assertEquals( + AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION, + resolved.authoredWorldBinding().schemaVersion()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(17L, resolved.versionStateEpoch()); + verify(launchDescriptorRepository).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void selectorV2WithoutCompleteParticipantProofCannotResolveOrFreezeSyntheticSuccess() + throws Exception { + var request = request("cp-incomplete-selector-v2", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(selectorBundle(true)); + + assertThrows(IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + private PublishedReleaseBundleDto selectorBundle(boolean omitParticipant) throws Exception { + // Stipulated original component bytes; this fixture does not authenticate a producer or admit + // gameplay. + WorldPublishedStartLocationEvidence evidence = + PublishedWorldSelectorFixtures.evidence( + new TargetProof( + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + 7L, + PRIVATE_SOURCE_TENANT_KEY, + 1L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + var participants = PublishedWorldSelectorFixtures.participants(7L, evidence); + return new PublishedReleaseBundleDto( + 11L, + PRIVATE_SOURCE_TENANT_KEY, + 7L, + 8, + "v2", + evidence.request().publishWorkflowId(), + MANIFEST_HASH, + List.of(), + omitParticipant ? participants.subList(0, 4) : participants, + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + PUBLISHED_RELEASE_BUNDLE_REF, + 1, + List.of(), + evidence); + } + @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); service = new LaunchDescriptorServiceImpl( gameTemplateRepository, @@ -46,122 +152,387 @@ void setUp() { versionRepository, publishedReleaseBundleService, templateRemapSetService, + authoredWorldSourceRepository, new ObjectMapper()); + ReflectionTestUtils.setField(service, "workloadNamespace", NAMESPACE); } @Test - void resolveLaunchDescriptorPersistsDeterministicDescriptor() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); + void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-1", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + AtomicReference inserted = new AtomicReference<>(); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + inserted.set(descriptor); + return descriptor; + }); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(7L, resolved.versionId()); + assertEquals("genrev-1", resolved.generationConfigRevision()); + assertEquals(17L, resolved.versionStateEpoch()); + assertEquals(11L, resolved.releaseBundleId()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals( + PRIVATE_SOURCE_TENANT_KEY, + inserted.get().getTenantId(), + "The private source key remains owner-local and is not the canonical tenant UUID"); + assertEquals(CANONICAL_TENANT_ID.toString(), inserted.get().getCanonicalTenantId()); + verify(authoredWorldSourceRepository) + .read(SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE); + verify(gameTemplateRepository).findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(CANONICAL_TENANT_ID.toString(), 9L); + } + + @Test + void exactRetryReturnsStoredResultWithoutReadingChangedTemplateDefaultsVersionOrRelease() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-retry", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(7L, 11L, "v1"); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-retry")) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest(PRIVATE_SOURCE_TENANT_KEY, "cp-retry")) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + var first = service.resolveLaunchDescriptor(request); + when(template.getDefaultVersionId()).thenReturn(8L); when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) + clearInvocations(template); + when(versionRepository.findById(8L)).thenReturn(Optional.empty()); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 8L)); + + var retry = service.resolveLaunchDescriptor(request); + + assertEquals(first, retry); + assertEquals(7L, retry.versionId()); + verify(gameTemplateRepository, times(1)) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verifyNoInteractions(template); + verify(versionRepository, times(1)).findById(7L); + verify(versionRepository, never()).findById(8L); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 8L); + verify(launchDescriptorRepository, times(1)).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void changedSourceScopeTemplateOrRequestCannotReplaceOriginalDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request original = request("cp-conflict", 9L); + stubSuccessfulLaunch(original, 7L, 11L); + LaunchDescriptor stored = descriptorFor(original, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-conflict")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + AuthoredWorldLaunchDescriptorEvidence.Request changedTemplate = request("cp-conflict", 10L); + IllegalArgumentException templateConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedTemplate)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + templateConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedRequest = + request("cp-conflict", 9L, true, "other-patch"); + IllegalArgumentException requestConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedRequest)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + requestConflict.getMessage()); + + UUID otherOperation = UUID.fromString("42345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedSource = + request("cp-conflict", 9L, otherOperation, WORLD_SLUG, CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + otherOperation, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + IllegalArgumentException sourceConflict = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(changedSource)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + sourceConflict.getMessage()); + + UUID otherCanonicalTenant = UUID.fromString("52345678-1234-4234-8234-123456789abc"); + AuthoredWorldLaunchDescriptorEvidence.Request changedTenantScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, WORLD_SLUG, otherCanonicalTenant); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, otherCanonicalTenant, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException scopeConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedTenantScope)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + scopeConflict.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedWorldScope = + request("cp-conflict", 9L, SOURCE_OPERATION_ID, "other-world", CANONICAL_TENANT_ID); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, "other-world", NAMESPACE)) + .thenReturn(Optional.empty()); + IllegalArgumentException worldConflict = + assertThrows( + IllegalArgumentException.class, + () -> service.resolveLaunchDescriptor(changedWorldScope)); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: control-plane request identity was reused with changed input", + worldConflict.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void exactReadbackReturnsOriginalEvidenceAndRejectsDigestOrScopeSubstitution() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-read", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + when(launchDescriptorRepository.findBoundByRequest(NAMESPACE, CANONICAL_TENANT_ID, "cp-read")) + .thenReturn(Optional.of(stored)); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); + var original = service.resolveLaunchDescriptor(request); + + var readback = + service.getLaunchDescriptor( + UUID.fromString("62345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest()); + + assertEquals(original, readback); + IllegalArgumentException changedRequestDigest = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("72345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + "sha256:" + "b".repeat(64), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedRequestDigest.getMessage()); - var descriptor = - service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null); + IllegalArgumentException changedResultDigest = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("82345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + WORLD_SLUG, + "cp-read", + original.authoredWorldBinding().requestDigest(), + "sha256:" + "c".repeat(64))); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedResultDigest.getMessage()); - assertEquals("tenant-1", descriptor.tenantId()); - assertEquals(7L, descriptor.versionId()); - assertEquals("genrev-1", descriptor.generationConfigRevision()); - assertEquals(17L, descriptor.versionStateEpoch()); - assertEquals(11L, descriptor.releaseBundleId()); + IllegalArgumentException changedWorld = + assertThrows( + IllegalArgumentException.class, + () -> + service.getLaunchDescriptor( + UUID.fromString("92345678-1234-4234-8234-123456789abc"), + CANONICAL_TENANT_ID, + "other-world", + "cp-read", + original.authoredWorldBinding().requestDigest(), + original.authoredWorldBinding().resultDigest())); + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: exact readback selector or digest does not match", + changedWorld.getMessage()); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); } @Test - void resolveLaunchDescriptorRejectsConflictingRequestReuse() { - LaunchDescriptor existing = new LaunchDescriptor(); - existing.setRequestHash("other-hash"); - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.of(existing)); + void selectedPatchWithoutExactPublicationAndReadinessEvidenceCannotResolve() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-patch", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, "patch-1"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "SCRIPT_PATCH_NOT_READY: exact published-for-base and Automation READY evidence is unavailable", + thrown.getMessage()); + verify(template).getDefaultScriptPatchVersion(); + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("SCRIPT_PATCH_NOT_READY", failure.getValue().getFailureCode()); + assertEquals(request.requestDigest(), failure.getValue().getRequestDigest()); + assertEquals(null, failure.getValue().getLaunchDescriptorId()); + assertEquals(null, failure.getValue().getVersionId()); + } + + @Test + void sourceAndTransientDependencyFailuresDoNotCreateFrozenOutcomes() { + AuthoredWorldLaunchDescriptorEvidence.Request missingSource = request("cp-no-source", 9L); + when(authoredWorldSourceRepository.read( + SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE)) + .thenReturn(Optional.empty()); + + IllegalArgumentException sourceFailure = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(missingSource)); + assertEquals( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing", + sourceFailure.getMessage()); + + AuthoredWorldLaunchDescriptorEvidence.Request changedSourceEvidence = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "cp-changed-source", + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + "sha256:" + "f".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + stubSource(changedSourceEvidence, sourceEvidence(WORLD_SLUG)); assertThrows( IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + () -> service.resolveLaunchDescriptor(changedSourceEvidence)); + + AuthoredWorldLaunchDescriptorEvidence.Request unavailableDependency = + request("cp-unavailable", 9L); + stubSource(unavailableDependency, sourceEvidence(WORLD_SLUG)); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L)) + .thenThrow(new DataAccessResourceFailureException("temporary database outage")); + + assertThrows( + DataAccessResourceFailureException.class, + () -> service.resolveLaunchDescriptor(unavailableDependency)); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void exactRetryOfStoredFailureReturnsItsOriginalCodeAndMessageBeforeMutableReads() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-frozen-failure", 9L); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + LaunchDescriptor failure = new LaunchDescriptor(); + failure.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + failure.setControlPlaneRequestId(request.controlPlaneRequestId()); + failure.setRequestHash(request.requestDigest()); + failure.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); + failure.setTargetNamespace(NAMESPACE); + failure.setCanonicalTenantId(CANONICAL_TENANT_ID.toString()); + failure.setWorldSlug(WORLD_SLUG); + failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + failure.setRequestDigest(request.requestDigest()); + failure.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + failure.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + failure.setOutcomeStatus(LaunchDescriptor.OUTCOME_FAILED); + failure.setFailureCode("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED"); + failure.setFailureMessage("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(failure)); + stubSource(request, source); + + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", thrown.failureCode()); + assertEquals("TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: frozen phase denial", thrown.getMessage()); + verify(gameTemplateRepository, never()) + .findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); + verify(launchDescriptorRepository, never()).insertImmutable(any(LaunchDescriptor.class)); + } + + @Test + void tamperedStoredPatchCannotReplayOutsideItsCommittedResultDigest() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setScriptPatchVersion("patch-1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, "cp-tampered")) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored resolved result digest is inconsistent", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorPreservesTemplatePhaseGate() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-phase", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.LEGACY); + stubSource(request, sourceEvidence(WORLD_SLUG)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED: template reference phase is not enforced", + thrown.getMessage()); } @Test void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn("patch-1"); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-1")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - version.setUpdatedAt(LocalDateTime.now()); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 7L, - 8, - "v2", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-schema", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v999")); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-1", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( true, @@ -173,33 +544,16 @@ void resolveLaunchDescriptorFailsClosedOnUnsupportedAttestationSchema() { @Test void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-2")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(7L); - version.setTenantId("tenant-1"); - version.setVersionNumber(8); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(17L); - when(versionRepository.findById(7L)).thenReturn(Optional.of(version)); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 7L)) - .thenThrow(new PublishedReleaseBundleNotFoundException("tenant-1", 7L)); + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-release", 9L); + stubTemplate(request, 7L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenThrow(new PublishedReleaseBundleNotFoundException(PRIVATE_SOURCE_TENANT_KEY, 7L)); IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-2", null, null, null, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "RELEASE_BUNDLE_NOT_FOUND: no published release bundle for the resolved version", @@ -207,34 +561,107 @@ void resolveLaunchDescriptorReportsMissingReleaseBundleDeterministically() { } @Test - void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(7L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-3")) + void missingOpaqueBundleReferenceDeniesCreationAndExactRetryWithoutSynthesizing() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-missing-reference", 9L); + stubTemplate(request, 7L, null); + AuthoredWorldSourceEvidence source = sourceEvidence(WORLD_SLUG); + stubSource(request, source); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L)) + .thenReturn(releaseBundle(7L, 11L, "v1", null)); + AtomicReference stored = new AtomicReference<>(); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenAnswer(invocation -> Optional.ofNullable(stored.get())); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); + + IllegalArgumentException first = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + IllegalArgumentException retry = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: published release bundle has no persisted opaque reference", + first.getMessage()); + assertEquals(first.getMessage(), retry.getMessage()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, stored.get().getOutcomeStatus()); + assertEquals("RELEASE_BUNDLE_NOT_FOUND", stored.get().getFailureCode()); + assertNull(stored.get().getPublishedReleaseBundleRef()); + verify(publishedReleaseBundleService, times(1)) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void resolveLaunchDescriptorAcceptsEqualLargeReleaseVersionIdsByValue() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-large-version", 9L); + Long resolvedVersionId = boxedLargeVersionId(); + Long bundleVersionId = boxedLargeVersionId(); + assertNotSame(resolvedVersionId, bundleVersionId); + stubTemplate(request, resolvedVersionId, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(bundleVersionId, 11L, "v1")); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(CANONICAL_TENANT_ID.toString(), resolved.canonicalTenantId()); + assertEquals(9L, resolved.gameTemplateId()); + assertEquals(1_000L, resolved.versionId()); + assertEquals(11L, resolved.releaseBundleId()); + assertNotNull(resolved.authoredWorldBinding()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); + } + + @Test + void resolveLaunchDescriptorRejectsReleaseBundleForDifferentVersionDeterministically() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-mismatched-release", 9L); + stubTemplate(request, 1_000L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(1_000L, VersionLifecycleState.PUBLISHED, 17L, null); + when(publishedReleaseBundleService.getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 1_000L)) + .thenReturn(releaseBundle(1_001L, 11L, "v1")); + IllegalArgumentException thrown = assertThrows( - IllegalArgumentException.class, - () -> service.resolveLaunchDescriptor("tenant-1", 9L, "cp-3", null, 7L, 8L, null)); + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "RELEASE_BUNDLE_NOT_FOUND: release bundle is not owned by the resolved source version", + thrown.getMessage()); + } + + @Test + void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-required", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) + .thenReturn(Optional.empty()); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); assertEquals( "LAUNCH_REMAP_REQUIRED: replacement-instance launch requires an approved remapSetId", @@ -243,61 +670,292 @@ void resolveLaunchDescriptorRequiresRemapForCrossVersionReplacementLaunch() { @Test void resolveLaunchDescriptorUsesApprovedRemapSetForCrossVersionReplacementLaunch() { - GameTemplateLaunchConfigView template = - org.mockito.Mockito.mock(GameTemplateLaunchConfigView.class); - when(template.getId()).thenReturn(9L); - when(template.getTenantId()).thenReturn("tenant-1"); - when(template.getDefaultVersionId()).thenReturn(8L); - when(template.getDefaultScriptPatchVersion()).thenReturn(null); - when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); - when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); - when(gameTemplateRepository.findLaunchConfigByTenantIdAndId("tenant-1", 9L)) - .thenReturn(Optional.of(template)); - when(launchDescriptorRepository.findByTenantIdAndGameTemplateIdAndControlPlaneRequestId( - "tenant-1", 9L, "cp-4")) - .thenReturn(Optional.empty()); - Version version = new Version(); - version.setId(8L); - version.setTenantId("tenant-1"); - version.setVersionNumber(9); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(18L); - when(versionRepository.findById(8L)).thenReturn(Optional.of(version)); - when(templateRemapSetService.findApprovedTemplateRemapSet("tenant-1", 7L, 8L)) + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-remap-approved", 9L, 7L, 8L); + stubTemplate(request, 8L, null); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(8L, VersionLifecycleState.PUBLISHED, 18L, null); + when(templateRemapSetService.findApprovedTemplateRemapSet(PRIVATE_SOURCE_TENANT_KEY, 7L, 8L)) .thenReturn( Optional.of( new TemplateRemapSetDto( "remap-1", - "tenant-1", + PRIVATE_SOURCE_TENANT_KEY, 7L, 8L, TemplateRemapSetStatus.APPROVED, - "prep", + "preparation", "approved", LocalDateTime.now(), LocalDateTime.now(), List.of()))); - when(publishedReleaseBundleService.getPublishedReleaseBundle("tenant-1", 8L)) - .thenReturn( - new PublishedReleaseBundleDto( - 11L, - "tenant-1", - 8L, - 9, - "v1", - "workflow-1", - "hash-1", - List.of("manifest.json"), - List.of(), - "genrev-1", - false, - null, - LocalDateTime.now())); - when(launchDescriptorRepository.save(any(LaunchDescriptor.class))) + stubBundle(8L, 11L, "v1"); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) .thenAnswer(invocation -> invocation.getArgument(0)); - var descriptor = service.resolveLaunchDescriptor("tenant-1", 9L, "cp-4", null, 7L, 8L, null); + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals("remap-1", resolved.remapSetId()); + assertEquals("remap-1", resolved.authoredWorldBinding().remapSetId()); + } + + private void stubSuccessfulLaunch( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + stubTemplate(request, versionId, null); + stubSource(request, sourceEvidence(request.worldSlug())); + stubVersion(versionId, VersionLifecycleState.PUBLISHED, 17L, null); + stubBundle(versionId, bundleId, "v1"); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + when(launchDescriptorRepository.findByPrivateRequest( + PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + } + + private GameTemplateLaunchConfigView stubTemplate( + AuthoredWorldLaunchDescriptorEvidence.Request request, + Long defaultVersionId, + String defaultPatch) { + GameTemplateLaunchConfigView template = Mockito.mock(GameTemplateLaunchConfigView.class); + when(template.getId()).thenReturn(request.gameTemplateId()); + when(template.getTenantId()).thenReturn(PRIVATE_SOURCE_TENANT_KEY); + when(template.getDefaultVersionId()).thenReturn(defaultVersionId); + when(template.getDefaultScriptPatchVersion()).thenReturn(defaultPatch); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{}"); + when(template.getTemplateReferencePhase()).thenReturn(TemplateReferencePhase.ENFORCED); + when(gameTemplateRepository.findLaunchConfigByTenantIdAndId( + PRIVATE_SOURCE_TENANT_KEY, request.gameTemplateId())) + .thenReturn(Optional.of(template)); + return template; + } + + private void stubSource( + AuthoredWorldLaunchDescriptorEvidence.Request request, AuthoredWorldSourceEvidence source) { + when(authoredWorldSourceRepository.read( + request.authoredWorldSourceOperationId(), + request.canonicalTenantId(), + request.worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(source)); + } + + private void stubVersion( + long versionId, VersionLifecycleState state, long epoch, String scriptPatchVersion) { + Version version = new Version(); + version.setId(versionId); + version.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + version.setVersionNumber(8); + version.setVersionState(state); + version.setVersionStateEpoch(epoch); + version.setScriptPatchVersion(scriptPatchVersion); + version.setUpdatedAt(LocalDateTime.now()); + when(versionRepository.findById(versionId)).thenReturn(Optional.of(version)); + } + + private void stubBundle(long versionId, long bundleId, String schemaVersion) { + when(publishedReleaseBundleService.getPublishedReleaseBundle( + PRIVATE_SOURCE_TENANT_KEY, versionId)) + .thenReturn(releaseBundle(versionId, bundleId, schemaVersion)); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion) { + return releaseBundle(versionId, bundleId, schemaVersion, PUBLISHED_RELEASE_BUNDLE_REF); + } + + private PublishedReleaseBundleDto releaseBundle( + Long versionId, long bundleId, String schemaVersion, String publishedReleaseBundleRef) { + return new PublishedReleaseBundleDto( + bundleId, + PRIVATE_SOURCE_TENANT_KEY, + versionId, + 8, + schemaVersion, + "workflow-1", + MANIFEST_HASH, + List.of(), + List.of(), + "genrev-1", + false, + null, + LocalDateTime.now(), + CANONICAL_TENANT_ID, + CANONICAL_VERSION_ID, + publishedReleaseBundleRef, + 1, + List.of()); + } + + @SuppressWarnings("removal") + private Long boxedLargeVersionId() { + return new Long(1_000L); + } + + private LaunchDescriptor descriptorFor( + AuthoredWorldLaunchDescriptorEvidence.Request request, long versionId, long bundleId) { + var evidence = + AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-stored-" + request.controlPlaneRequestId(), + versionId, + false, + null, + "{}", + "genrev-1", + 17L, + bundleId, + PUBLISHED_RELEASE_BUNDLE_REF, + false, + null); + AuthoredWorldSourceEvidence source = sourceEvidence(request.worldSlug()); + LaunchDescriptor descriptor = new LaunchDescriptor(); + descriptor.setLaunchDescriptorId(evidence.launchDescriptorId()); + descriptor.setTenantId(PRIVATE_SOURCE_TENANT_KEY); + descriptor.setGameTemplateId(request.gameTemplateId()); + descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); + descriptor.setRequestHash(evidence.requestDigest()); + descriptor.setVersionId(evidence.versionId()); + descriptor.setRuntimeFlagsJson(evidence.runtimeFlagsJson()); + descriptor.setGenerationConfigRevision(evidence.generationConfigRevision()); + descriptor.setVersionStateEpoch(evidence.versionStateEpoch()); + descriptor.setReleaseBundleId(evidence.releaseBundleId()); + descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); + descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); + descriptor.setTargetNamespace(evidence.targetNamespace()); + descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setWorldSlug(evidence.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId( + evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); + descriptor.setRequestDigest(evidence.requestDigest()); + descriptor.setResultDigest(evidence.resultDigest()); + descriptor.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); + descriptor.setSourceEvidenceJson(new ObjectMapper().writeValueAsString(source)); + return descriptor; + } + + private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { + String tenantSlug = "silver-company"; + String displayName = "Silver March 🐉"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + SOURCE_REGISTRATION_ID, + SOURCE_OPERATION_ID, + requestDigest, + CANONICAL_TENANT_ID, + tenantSlug, + worldSlug, + displayName, + 901L, + PRIVATE_SOURCE_TENANT_KEY, + "NEW_GAME_ROW")); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, long gameTemplateId) { + return request( + controlPlaneRequestId, + gameTemplateId, + SOURCE_OPERATION_ID, + WORLD_SLUG, + CANONICAL_TENANT_ID); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + long sourceVersionId, + long targetVersionId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + true, + sourceVersionId, + true, + targetVersionId, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + boolean requestedPatchPresent, + String requestedPatch) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + requestedPatchPresent, + requestedPatch, + false, + null, + false, + null, + false, + null); + } - assertEquals("remap-1", descriptor.remapSetId()); + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, + long gameTemplateId, + UUID operationId, + String worldSlug, + UUID canonicalTenantId) { + String evidenceDigest = + SOURCE_OPERATION_ID.equals(operationId) + && WORLD_SLUG.equals(worldSlug) + && CANONICAL_TENANT_ID.equals(canonicalTenantId) + ? sourceEvidence(WORLD_SLUG).evidenceDigest() + : "sha256:" + "a".repeat(64); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + canonicalTenantId, + worldSlug, + operationId, + evidenceDigest, + gameTemplateId, + false, + null, + false, + null, + false, + null, + false, + null); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java new file mode 100644 index 0000000000..7ffea40a81 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalLaunchPreparationSnapshot.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; + +/** Exact immutable source/catalog/descriptor evidence consumed by one launch preparation. */ +public record CanonicalLaunchPreparationSnapshot( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalogSnapshot, + IntakeReceipt sourceIntakeReceipt, + AuthoredWorldLaunchDescriptorEvidence launchDescriptorEvidence, + String requestDigest, + String receiptDigest) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + + public CanonicalLaunchPreparationSnapshot { + requireNonNil(operationId, "operationId"); + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalogSnapshot, "catalogSnapshot"); + Objects.requireNonNull(sourceIntakeReceipt, "sourceIntakeReceipt"); + Objects.requireNonNull(launchDescriptorEvidence, "launchDescriptorEvidence"); + requireDigest(requestDigest, "requestDigest"); + requireDigest(receiptDigest, "receiptDigest"); + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + } + + /** Revalidates the complete closed shared descriptor and all local identity joins. */ + public void requireValid() { + requireConsumedEvidence( + request, catalogSnapshot, sourceIntakeReceipt, launchDescriptorEvidence); + launchDescriptorEvidence.requireValid(); + } + + private static void requireConsumedEvidence( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new IllegalArgumentException( + "Launch preparation evidence does not match its exact request, catalog, and source"); + } + descriptor.requireValid(); + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static void requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(name + " must be a canonical SHA-256 digest"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java new file mode 100644 index 0000000000..1b9b7cdded --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CreateCanonicalLaunchPreparationRequest.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.gamesession.dto; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import org.springframework.lang.Nullable; + +/** Immutable input for source-qualified Game Design launch preparation; it grants no authority. */ +public record CreateCanonicalLaunchPreparationRequest( + String controlPlaneRequestId, + UUID actingAccountUuid, + String targetNamespace, + UUID canonicalTenantId, + UUID realmId, + UUID catalogCreationRequestId, + long catalogRevision, + UUID sourceIntakeOperationId, + long gameTemplateId, + boolean requestedScriptPatchVersionPresent, + @Nullable String requestedScriptPatchVersion, + boolean sourceVersionIdPresent, + @Nullable Long sourceVersionId, + boolean targetVersionIdPresent, + @Nullable Long targetVersionId, + boolean requestedRuntimeFlagsJsonPresent, + @Nullable String requestedRuntimeFlagsJson) { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + public CreateCanonicalLaunchPreparationRequest { + requireText(controlPlaneRequestId, "controlPlaneRequestId", 128); + requireNonNil(actingAccountUuid, "actingAccountUuid"); + Objects.requireNonNull(targetNamespace, "targetNamespace"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + requireNonNil(canonicalTenantId, "canonicalTenantId"); + requireNonNil(realmId, "realmId"); + requireNonNil(catalogCreationRequestId, "catalogCreationRequestId"); + requireNonNil(sourceIntakeOperationId, "sourceIntakeOperationId"); + if (catalogRevision <= 0L) { + throw new IllegalArgumentException("catalogRevision must be positive"); + } + if (gameTemplateId <= 0L) { + throw new IllegalArgumentException("gameTemplateId must be positive"); + } + requireOptional( + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + "requestedScriptPatchVersion"); + requireOptional(sourceVersionIdPresent, sourceVersionId, "sourceVersionId"); + if (sourceVersionIdPresent && sourceVersionId <= 0L) { + throw new IllegalArgumentException("sourceVersionId must be positive when present"); + } + requireOptional(targetVersionIdPresent, targetVersionId, "targetVersionId"); + if (targetVersionIdPresent && targetVersionId <= 0L) { + throw new IllegalArgumentException("targetVersionId must be positive when present"); + } + requireOptional( + requestedRuntimeFlagsJsonPresent, requestedRuntimeFlagsJson, "requestedRuntimeFlagsJson"); + } + + public AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest( + CanonicalRealmCatalogSnapshot catalog, AuthoredWorldSourceEvidence source) { + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + return new AuthoredWorldLaunchDescriptorEvidence.Request( + targetNamespace, + controlPlaneRequestId, + canonicalTenantId, + catalog.worldSlug(), + source.operationId(), + source.evidenceDigest(), + gameTemplateId, + requestedScriptPatchVersionPresent, + requestedScriptPatchVersion, + sourceVersionIdPresent, + sourceVersionId, + targetVersionIdPresent, + targetVersionId, + requestedRuntimeFlagsJsonPresent, + requestedRuntimeFlagsJson); + } + + private static void requireOptional(boolean present, Object value, String name) { + if (present != (value != null)) { + throw new IllegalArgumentException(name + " presence does not match its value"); + } + if (value instanceof String text) { + strictUtf8(text, name); + } + } + + private static void requireText(String value, String name, int maxUtf8Bytes) { + Objects.requireNonNull(value, name); + byte[] bytes = strictUtf8(value, name); + if (value.isBlank() || bytes.length > maxUtf8Bytes) { + throw new IllegalArgumentException(name + " must be nonblank and bounded"); + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (NIL_UUID.equals(value)) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private static byte[] strictUtf8(String value, String name) { + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException(name + " must be well-formed UTF-8", exception); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java new file mode 100644 index 0000000000..52511f5c61 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java @@ -0,0 +1,656 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.sql.Connection; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.JSONB; +import org.jooq.Record; +import org.jooq.Table; +import org.jooq.impl.DSL; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Game Session-owned immutable persistence for source-qualified launch preparation evidence. */ +@Repository +public class GameSessionCanonicalLaunchPreparationRepository { + private static final int SCHEMA_VERSION = 1; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final String REQUEST_DOMAIN = + "game-session-canonical-launch-preparation-request/v1"; + private static final String RECEIPT_DOMAIN = + "game-session-canonical-launch-preparation-receipt/v1"; + private static final ObjectMapper JSON = + new ObjectMapper( + JsonFactory.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + private static final Table PREPARATION = + DSL.table(DSL.name("game_session_canonical_launch_preparation")); + private static final Field TARGET_NAMESPACE = + DSL.field(DSL.name("target_namespace"), String.class); + private static final Field CONTROL_PLANE_REQUEST_ID = + DSL.field(DSL.name("control_plane_request_id"), String.class); + private static final Field OPERATION_ID = DSL.field(DSL.name("operation_id"), UUID.class); + private static final Field ACTING_ACCOUNT_UUID = + DSL.field(DSL.name("acting_account_uuid"), UUID.class); + private static final Field CANONICAL_TENANT_ID = + DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field REALM_ID = DSL.field(DSL.name("realm_id"), UUID.class); + private static final Field CATALOG_CREATION_REQUEST_ID = + DSL.field(DSL.name("catalog_creation_request_id"), UUID.class); + private static final Field CATALOG_REVISION = + DSL.field(DSL.name("catalog_revision"), Long.class); + private static final Field SOURCE_INTAKE_OPERATION_ID = + DSL.field(DSL.name("source_intake_operation_id"), UUID.class); + private static final Field SOURCE_INTAKE_REQUEST_ID = + DSL.field(DSL.name("source_intake_request_id"), UUID.class); + private static final Field SOURCE_REGISTRATION_REQUEST_ID = + DSL.field(DSL.name("source_registration_request_id"), UUID.class); + private static final Field SOURCE_OPERATION_ID = + DSL.field(DSL.name("source_operation_id"), UUID.class); + private static final Field CATALOG_REQUEST_DIGEST = + DSL.field(DSL.name("catalog_request_digest"), String.class); + private static final Field CATALOG_RECEIPT_DIGEST = + DSL.field(DSL.name("catalog_receipt_digest"), String.class); + private static final Field SOURCE_INTAKE_REQUEST_DIGEST = + DSL.field(DSL.name("source_intake_request_digest"), String.class); + private static final Field SOURCE_INTAKE_RECEIPT_DIGEST = + DSL.field(DSL.name("source_intake_receipt_digest"), String.class); + private static final Field SOURCE_EVIDENCE_DIGEST = + DSL.field(DSL.name("source_evidence_digest"), String.class); + private static final Field DESCRIPTOR_REQUEST_DIGEST = + DSL.field(DSL.name("descriptor_request_digest"), String.class); + private static final Field DESCRIPTOR_RESULT_DIGEST = + DSL.field(DSL.name("descriptor_result_digest"), String.class); + private static final Field REQUEST_DIGEST = + DSL.field(DSL.name("request_digest"), String.class); + private static final Field RECEIPT_DIGEST = + DSL.field(DSL.name("receipt_digest"), String.class); + private static final Field REQUEST_EVIDENCE_JSON = + DSL.field(DSL.name("request_evidence_json"), JSONB.class); + private static final Field CATALOG_EVIDENCE_JSON = + DSL.field(DSL.name("catalog_evidence_json"), JSONB.class); + private static final Field SOURCE_INTAKE_EVIDENCE_JSON = + DSL.field(DSL.name("source_intake_evidence_json"), JSONB.class); + private static final Field LAUNCH_DESCRIPTOR_EVIDENCE_JSON = + DSL.field(DSL.name("launch_descriptor_evidence_json"), JSONB.class); + + private final DSLContext dsl; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Injected owner collaborators are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationRepository( + DSLContext dsl, GameSessionCanonicalRealmCatalogRepository catalogRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl must not be null"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + } + + /** Reads one complete committed preparation without repairing or re-resolving evidence. */ + @Transactional(propagation = Propagation.NEVER, readOnly = true) + public Optional readByControlPlaneRequestId( + String targetNamespace, String controlPlaneRequestId) { + requireSelector(targetNamespace, controlPlaneRequestId); + requireCommittedRead(); + Record row = find(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(toSnapshot(row)); + } + + /** + * Persists one exact immutable source/catalog/descriptor composition under a caller-owned + * writable READ COMMITTED transaction. No network operation is performed while owner rows are + * locked. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CanonicalLaunchPreparationSnapshot persistPrepared( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot committedCatalog, + IntakeReceipt committedSource, + AuthoredWorldLaunchDescriptorEvidence descriptorEvidence) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(committedCatalog, "committedCatalog"); + Objects.requireNonNull(committedSource, "committedSource"); + Objects.requireNonNull(descriptorEvidence, "descriptorEvidence"); + requireWritableReadCommittedOwnerTransaction(); + requireEvidenceMatchesRequest(request, committedCatalog, committedSource, descriptorEvidence); + + Record existing = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (existing != null) { + return requireExactPrepared( + existing, request, committedCatalog, committedSource, descriptorEvidence); + } + + CanonicalRealmCatalogSnapshot lockedCatalog = + catalogRepository.lockExactInitialPublicProduction( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.catalogCreationRequestId(), + request.catalogRevision()); + if (!committedCatalog.equals(lockedCatalog)) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical catalog changed after launch preparation readback"); + } + IntakeReceipt lockedSource = lockExactSource(committedSource); + if (!committedSource.equals(lockedSource) + || !committedCatalog.sourceIntakeReceipt().equals(lockedSource)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed authored-world source changed before launch preparation persistence"); + } + + UUID operationId = UUID.randomUUID(); + requireNonNil(operationId, "operationId"); + String requestDigest = + requestDigest(request, committedCatalog, committedSource, descriptorEvidence); + String receiptDigest = + receiptDigest( + operationId, + request, + committedCatalog, + committedSource, + descriptorEvidence, + requestDigest); + dsl.insertInto(PREPARATION) + .set(TARGET_NAMESPACE, request.targetNamespace()) + .set(CONTROL_PLANE_REQUEST_ID, request.controlPlaneRequestId()) + .set(OPERATION_ID, operationId) + .set(ACTING_ACCOUNT_UUID, request.actingAccountUuid()) + .set(CANONICAL_TENANT_ID, request.canonicalTenantId()) + .set(REALM_ID, request.realmId()) + .set(CATALOG_CREATION_REQUEST_ID, request.catalogCreationRequestId()) + .set(CATALOG_REVISION, request.catalogRevision()) + .set(SOURCE_INTAKE_OPERATION_ID, committedSource.operationId()) + .set(SOURCE_INTAKE_REQUEST_ID, committedSource.intakeRequestId()) + .set(SOURCE_REGISTRATION_REQUEST_ID, committedSource.source().registrationRequestId()) + .set(SOURCE_OPERATION_ID, committedSource.source().operationId()) + .set(CATALOG_REQUEST_DIGEST, committedCatalog.requestDigest()) + .set(CATALOG_RECEIPT_DIGEST, committedCatalog.receiptDigest()) + .set(SOURCE_INTAKE_REQUEST_DIGEST, committedSource.requestDigest()) + .set(SOURCE_INTAKE_RECEIPT_DIGEST, committedSource.receiptDigest()) + .set(SOURCE_EVIDENCE_DIGEST, committedSource.source().evidenceDigest()) + .set(DESCRIPTOR_REQUEST_DIGEST, descriptorEvidence.requestDigest()) + .set(DESCRIPTOR_RESULT_DIGEST, descriptorEvidence.resultDigest()) + .set(REQUEST_DIGEST, requestDigest) + .set(RECEIPT_DIGEST, receiptDigest) + .set(REQUEST_EVIDENCE_JSON, toJson(request, "request")) + .set(CATALOG_EVIDENCE_JSON, toJson(committedCatalog, "catalog")) + .set(SOURCE_INTAKE_EVIDENCE_JSON, toJson(committedSource, "source intake")) + .set(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, toJson(descriptorEvidence, "launch descriptor")) + .onConflictDoNothing() + .execute(); + + Record stored = find(request.targetNamespace(), request.controlPlaneRequestId()); + if (stored == null) { + throw new LaunchPreparationConflictException( + "Canonical launch preparation conflicts with existing immutable owner evidence"); + } + return requireExactPrepared( + stored, request, committedCatalog, committedSource, descriptorEvidence); + } + + public static String requestDigest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + requireEvidenceMatchesRequest(request, catalog, source, descriptor); + AuthoredWorldSourceEvidence authoredSource = source.source(); + return digest( + REQUEST_DOMAIN, + Integer.toString(SCHEMA_VERSION), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + request.sourceIntakeOperationId().toString(), + Long.toString(request.gameTemplateId()), + Boolean.toString(request.requestedScriptPatchVersionPresent()), + optional( + request.requestedScriptPatchVersionPresent(), request.requestedScriptPatchVersion()), + Boolean.toString(request.sourceVersionIdPresent()), + optional(request.sourceVersionIdPresent(), decimal(request.sourceVersionId())), + Boolean.toString(request.targetVersionIdPresent()), + optional(request.targetVersionIdPresent(), decimal(request.targetVersionId())), + Boolean.toString(request.requestedRuntimeFlagsJsonPresent()), + optional(request.requestedRuntimeFlagsJsonPresent(), request.requestedRuntimeFlagsJson()), + catalog.targetNamespace(), + catalog.tenantId().toString(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId().toString(), + catalog.realmSlug(), + catalog.realmDisplayName(), + Boolean.toString(catalog.visible()), + Boolean.toString(catalog.publicProduction()), + catalog.stateScope(), + catalog.playableStateNamespaceId().toString(), + catalog.characterCreationPolicy(), + Long.toString(catalog.catalogRevision()), + catalog.creationRequestId().toString(), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + Integer.toString(authoredSource.schemaVersion()), + authoredSource.registrationRequestId().toString(), + authoredSource.operationId().toString(), + authoredSource.requestDigest(), + authoredSource.canonicalTenantId().toString(), + authoredSource.tenantSlug(), + authoredSource.worldSlug(), + authoredSource.worldDisplayName(), + Long.toString(authoredSource.sourceGameRowId()), + authoredSource.sourceGameTenantKey(), + authoredSource.provenanceKind(), + authoredSource.evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + public static String receiptDigest( + UUID operationId, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + String requestDigest) { + requireNonNil(operationId, "operationId"); + requireDigest(requestDigest, "requestDigest"); + return digest( + RECEIPT_DOMAIN, + Integer.toString(SCHEMA_VERSION), + operationId.toString(), + requestDigest, + request.targetNamespace(), + request.controlPlaneRequestId(), + request.actingAccountUuid().toString(), + request.canonicalTenantId().toString(), + request.realmId().toString(), + request.catalogCreationRequestId().toString(), + Long.toString(request.catalogRevision()), + catalog.requestDigest(), + catalog.receiptDigest(), + source.operationId().toString(), + source.intakeRequestId().toString(), + source.requestDigest(), + source.receiptDigest(), + source.source().evidenceDigest(), + descriptor.requestDigest(), + descriptor.resultDigest()); + } + + private CanonicalLaunchPreparationSnapshot requireExactPrepared( + Record row, + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + CanonicalLaunchPreparationSnapshot stored = toSnapshot(row); + if (!stored.request().equals(request) + || !stored.catalogSnapshot().equals(catalog) + || !stored.sourceIntakeReceipt().equals(source) + || !stored.launchDescriptorEvidence().equals(descriptor)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation evidence"); + } + return stored; + } + + private CanonicalLaunchPreparationSnapshot toSnapshot(Record row) { + try { + CreateCanonicalLaunchPreparationRequest request = + fromJson( + row.get(REQUEST_EVIDENCE_JSON, JSONB.class), + CreateCanonicalLaunchPreparationRequest.class); + CanonicalRealmCatalogSnapshot catalog = + fromJson( + row.get(CATALOG_EVIDENCE_JSON, JSONB.class), CanonicalRealmCatalogSnapshot.class); + IntakeReceipt source = + fromJson(row.get(SOURCE_INTAKE_EVIDENCE_JSON, JSONB.class), IntakeReceipt.class); + AuthoredWorldLaunchDescriptorEvidence descriptor = + fromJson( + row.get(LAUNCH_DESCRIPTOR_EVIDENCE_JSON, JSONB.class), + AuthoredWorldLaunchDescriptorEvidence.class); + CanonicalLaunchPreparationSnapshot snapshot = + new CanonicalLaunchPreparationSnapshot( + required(row.get(OPERATION_ID), "operationId"), + request, + catalog, + source, + descriptor, + required(row.get(REQUEST_DIGEST), "requestDigest"), + required(row.get(RECEIPT_DIGEST), "receiptDigest")); + snapshot.requireValid(); + String expectedRequestDigest = requestDigest(request, catalog, source, descriptor); + String expectedReceiptDigest = + receiptDigest( + snapshot.operationId(), request, catalog, source, descriptor, expectedRequestDigest); + if (!request.targetNamespace().equals(required(row.get(TARGET_NAMESPACE), "targetNamespace")) + || !request + .controlPlaneRequestId() + .equals(required(row.get(CONTROL_PLANE_REQUEST_ID), "controlPlaneRequestId")) + || !request + .actingAccountUuid() + .equals(required(row.get(ACTING_ACCOUNT_UUID), "actingAccountUuid")) + || !request + .canonicalTenantId() + .equals(required(row.get(CANONICAL_TENANT_ID), "canonicalTenantId")) + || !request.realmId().equals(required(row.get(REALM_ID), "realmId")) + || !request + .catalogCreationRequestId() + .equals(required(row.get(CATALOG_CREATION_REQUEST_ID), "catalogCreationRequestId")) + || request.catalogRevision() != required(row.get(CATALOG_REVISION), "catalogRevision") + || !source + .operationId() + .equals(required(row.get(SOURCE_INTAKE_OPERATION_ID), "sourceIntakeOperationId")) + || !source + .intakeRequestId() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_ID), "sourceIntakeRequestId")) + || !source + .source() + .registrationRequestId() + .equals( + required(row.get(SOURCE_REGISTRATION_REQUEST_ID), "sourceRegistrationRequestId")) + || !source + .source() + .operationId() + .equals(required(row.get(SOURCE_OPERATION_ID), "sourceOperationId")) + || !catalog + .requestDigest() + .equals(required(row.get(CATALOG_REQUEST_DIGEST), "catalogRequestDigest")) + || !catalog + .receiptDigest() + .equals(required(row.get(CATALOG_RECEIPT_DIGEST), "catalogReceiptDigest")) + || !source + .requestDigest() + .equals(required(row.get(SOURCE_INTAKE_REQUEST_DIGEST), "sourceIntakeRequestDigest")) + || !source + .receiptDigest() + .equals(required(row.get(SOURCE_INTAKE_RECEIPT_DIGEST), "sourceIntakeReceiptDigest")) + || !source + .source() + .evidenceDigest() + .equals(required(row.get(SOURCE_EVIDENCE_DIGEST), "sourceEvidenceDigest")) + || !descriptor + .requestDigest() + .equals(required(row.get(DESCRIPTOR_REQUEST_DIGEST), "descriptorRequestDigest")) + || !descriptor + .resultDigest() + .equals(required(row.get(DESCRIPTOR_RESULT_DIGEST), "descriptorResultDigest")) + || !expectedRequestDigest.equals(snapshot.requestDigest()) + || !expectedReceiptDigest.equals(snapshot.receiptDigest())) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation evidence does not match its stored identity and digests"); + } + return snapshot; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted canonical launch preparation evidence is invalid", exception); + } + } + + private IntakeReceipt lockExactSource(IntakeReceipt expected) { + Record row = + dsl.fetchOne( + "SELECT * FROM game_session_authored_world_source_intake " + + "WHERE target_namespace = ? AND operation_id = ? FOR UPDATE", + expected.source().targetNamespace(), + expected.operationId()); + if (row == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing at launch preparation commit"); + } + try { + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + required(row.get("source_schema_version", Integer.class), "sourceSchemaVersion"), + required(row.get("target_namespace", String.class), "sourceTargetNamespace"), + required( + row.get("source_registration_request_id", UUID.class), + "sourceRegistrationRequestId"), + required(row.get("source_operation_id", UUID.class), "sourceOperationId"), + required(row.get("source_request_digest", String.class), "sourceRequestDigest"), + required(row.get("canonical_tenant_id", UUID.class), "sourceCanonicalTenantId"), + required(row.get("tenant_slug", String.class), "sourceTenantSlug"), + required(row.get("world_slug", String.class), "sourceWorldSlug"), + required(row.get("world_display_name", String.class), "sourceWorldDisplayName"), + required(row.get("source_game_row_id", Long.class), "sourceGameRowId"), + required(row.get("source_game_tenant_key", String.class), "sourceGameTenantKey"), + required(row.get("source_provenance_kind", String.class), "sourceProvenanceKind"), + required(row.get("source_evidence_digest", String.class), "sourceEvidenceDigest")); + if (!Integer.valueOf(SCHEMA_VERSION).equals(row.get("schema_version", Integer.class))) { + throw new IllegalArgumentException("Unsupported source intake schema version"); + } + IntakeReceipt locked = + new IntakeReceipt( + required(row.get("operation_id", UUID.class), "sourceIntakeOperationId"), + required(row.get("intake_request_id", UUID.class), "sourceIntakeRequestId"), + required(row.get("request_digest", String.class), "sourceIntakeRequestDigest"), + source, + required(row.get("receipt_digest", String.class), "sourceIntakeReceiptDigest")); + if (!"NEW_GAME_ROW".equals(source.provenanceKind())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch preparation requires exact fresh authored-world source evidence"); + } + return locked; + } catch (InvalidLaunchPreparationEvidenceException exception) { + throw exception; + } catch (RuntimeException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted authored-world source evidence is invalid", exception); + } + } + + private Record find(String targetNamespace, String controlPlaneRequestId) { + return dsl.selectFrom(PREPARATION) + .where( + TARGET_NAMESPACE + .eq(targetNamespace) + .and(CONTROL_PLANE_REQUEST_ID.eq(controlPlaneRequestId))) + .fetchOne(); + } + + private static void requireEvidenceMatchesRequest( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(descriptor, "descriptor"); + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !source.equals(catalog.sourceIntakeReceipt()) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !descriptor.request().equals(request.descriptorRequest(catalog, source.source()))) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation does not match exact fresh catalog/source/descriptor evidence"); + } + descriptor.requireValid(); + } + + private static void requireSelector(String namespace, String controlPlaneRequestId) { + if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("targetNamespace must be one canonical DNS label"); + } + if (controlPlaneRequestId == null || controlPlaneRequestId.isBlank()) { + throw new IllegalArgumentException("controlPlaneRequestId is required"); + } + strictUtf8(controlPlaneRequestId); + } + + private static void requireCommittedRead() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Launch preparation read requires committed owner evidence"); + } + } + + private void requireWritableReadCommittedOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Launch preparation persistence requires a writable owner transaction"); + } + dsl.connectionResult( + connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Launch preparation persistence requires the owner READ COMMITTED connection"); + } + return null; + }); + Record isolation = dsl.fetchOne("SHOW transaction_isolation"); + if (isolation == null + || !"read committed".equalsIgnoreCase(isolation.get(0, String.class).trim())) { + throw new IllegalStateException("Launch preparation persistence requires READ COMMITTED"); + } + } + + private static JSONB toJson(Object value, String name) { + try { + return JSONB.valueOf(JSON.writeValueAsString(value)); + } catch (IOException exception) { + throw new IllegalStateException("Could not store exact " + name + " evidence", exception); + } + } + + private static T fromJson(JSONB value, Class type) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException("Persisted JSON evidence is missing"); + } + try { + return JSON.readValue(value.data(), type); + } catch (IOException exception) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted closed launch preparation evidence cannot be decoded", exception); + } + } + + private static String digest(String domain, String... values) { + try { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + writeSegment(preimage, domain); + for (String value : values) { + writeSegment(preimage, value); + } + return "sha256:" + + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void writeSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = strictUtf8(value); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private static byte[] strictUtf8(String value) { + Objects.requireNonNull(value, "digest value"); + try { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + return bytes; + } catch (CharacterCodingException exception) { + throw new IllegalArgumentException("Digest inputs must be well-formed UTF-8", exception); + } + } + + private static String decimal(Long value) { + return value == null ? "" : Long.toString(value); + } + + private static String optional(boolean present, String value) { + return present ? Objects.requireNonNull(value, "present optional value") : ""; + } + + private static void requireDigest(String value, String fieldName) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " must be a canonical SHA-256 digest"); + } + } + + private static void requireNonNil(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a non-nil UUID"); + } + } + + private static T required(T value, String fieldName) { + if (value == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Persisted launch preparation " + fieldName + " is missing"); + } + return value; + } + + public static final class LaunchPreparationConflictException extends IllegalStateException { + public LaunchPreparationConflictException(String message) { + super(message); + } + } + + public static final class InvalidLaunchPreparationEvidenceException + extends IllegalStateException { + public InvalidLaunchPreparationEvidenceException(String message) { + super(message); + } + + public InvalidLaunchPreparationEvidenceException(String message, Throwable cause) { + super(message, cause); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java new file mode 100644 index 0000000000..57d25a4a29 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java @@ -0,0 +1,246 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +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; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unwired Game Session consumer for exact source-qualified launch preparation. It persists no game + * instance, calls no World API, and does not authorize creator or launch actions. + */ +public class GameSessionCanonicalLaunchPreparationService { + private final AuthoredWorldLaunchDescriptorClient descriptorClient; + private final GameSessionCanonicalRealmCatalogRepository catalogRepository; + private final GameSessionAuthoredWorldSourceRepository sourceRepository; + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository; + private final String workloadNamespace; + private final TransactionTemplate ownerTransaction; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Trusted owner collaborators and namespace are validated before use; construction acquires no resources.") + public GameSessionCanonicalLaunchPreparationService( + AuthoredWorldLaunchDescriptorClient descriptorClient, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.descriptorClient = Objects.requireNonNull(descriptorClient, "descriptorClient"); + this.catalogRepository = Objects.requireNonNull(catalogRepository, "catalogRepository"); + this.sourceRepository = Objects.requireNonNull(sourceRepository, "sourceRepository"); + this.preparationRepository = + Objects.requireNonNull(preparationRepository, "preparationRepository"); + Objects.requireNonNull(transactionManager, "transactionManager"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Game Session workload namespace is invalid"); + } + this.workloadNamespace = workloadNamespace; + this.ownerTransaction = new TransactionTemplate(transactionManager); + this.ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + this.ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.ownerTransaction.setReadOnly(false); + } + + /** + * Resolves and independently reads back exact immutable Game Design evidence before taking any + * catalog/source owner locks. Exact retries return the original preparation without network I/O. + */ + public CanonicalLaunchPreparationSnapshot prepare( + CreateCanonicalLaunchPreparationRequest request) { + Objects.requireNonNull(request, "request"); + requireNoAmbientTransaction(); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + + Optional prior = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (prior.isPresent()) { + CanonicalLaunchPreparationSnapshot stored = prior.orElseThrow(); + stored.requireValid(); + if (!stored.request().equals(request)) { + throw new LaunchPreparationConflictException( + "controlPlaneRequestId was reused with changed launch preparation inputs"); + } + return stored; + } + + CanonicalRealmCatalogSnapshot catalog = + catalogRepository + .readByRequest(workloadNamespace, request.catalogCreationRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed canonical realm catalog is missing")); + requireCatalogBinding(request, catalog); + IntakeReceipt source = + sourceRepository + .read( + request.sourceIntakeOperationId(), + request.canonicalTenantId(), + catalog.worldSlug(), + workloadNamespace) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing")); + requireSourceBinding(request, catalog, source); + + AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = + request.descriptorRequest(catalog, source.source()); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptorClient.resolve(descriptorRequest); + if (resolved == null + || !descriptorRequest.equals(resolved.request()) + || !workloadNamespace.equals(resolved.targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Resolved Game Design descriptor does not match the exact launch preparation request"); + } + resolved.requireValid(); + + AuthoredWorldLaunchDescriptorEvidence readback = + descriptorClient.get( + new GetRequest(UUID.randomUUID(), descriptorRequest, resolved.resultDigest())); + if (!resolved.equals(readback)) { + throw new InvalidLaunchPreparationEvidenceException( + "Independent Game Design descriptor readback differs from the resolved evidence"); + } + + CanonicalLaunchPreparationSnapshot written = + ownerTransaction.execute( + status -> preparationRepository.persistPrepared(request, catalog, source, readback)); + if (written == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Session owner transaction returned no launch preparation result"); + } + + Optional committed = + preparationRepository.readByControlPlaneRequestId( + workloadNamespace, request.controlPlaneRequestId()); + if (committed.isEmpty()) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing after independent readback"); + } + CanonicalLaunchPreparationSnapshot exact = committed.orElseThrow(); + exact.requireValid(); + if (!written.equals(exact)) { + throw new InvalidLaunchPreparationEvidenceException( + "Launch preparation changed during independent commit readback"); + } + return exact; + } + + /** + * Reads the complete authenticated Game Design binding for one exact committed preparation. This + * is a non-admitting evidence read: it neither creates nor advances a game instance. + */ + public CompleteLaunchBindingEvidence readCompleteBinding( + CanonicalLaunchPreparationSnapshot snapshot) { + Objects.requireNonNull(snapshot, "snapshot"); + requireNoAmbientTransaction(); + snapshot.requireValid(); + if (!workloadNamespace.equals(snapshot.request().targetNamespace())) { + throw new SecurityException("Launch preparation namespace does not match this workload"); + } + + CanonicalLaunchPreparationSnapshot committed = + preparationRepository + .readByControlPlaneRequestId( + workloadNamespace, snapshot.request().controlPlaneRequestId()) + .orElseThrow( + () -> + new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing before complete binding read")); + committed.requireValid(); + if (!snapshot.equals(committed)) { + throw new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation changed before complete binding read"); + } + + AuthoredWorldLaunchDescriptorEvidence descriptor = snapshot.launchDescriptorEvidence(); + GetRequest readSelector = + new GetRequest(randomNonNilUuid(), descriptor.request(), descriptor.resultDigest()); + CompleteLaunchBindingEvidence binding = + descriptorClient.getComplete( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(readSelector)); + if (binding == null) { + throw new InvalidLaunchPreparationEvidenceException( + "Game Design returned no complete launch binding"); + } + binding.descriptor().requireValid(); + binding.releaseAttestation().requireValid(binding.descriptor()); + if (!descriptor.equals(binding.descriptor()) + || !workloadNamespace.equals(binding.descriptor().targetNamespace())) { + throw new InvalidLaunchPreparationEvidenceException( + "Complete Game Design binding differs from the committed launch descriptor"); + } + return binding; + } + + private static void requireCatalogBinding( + CreateCanonicalLaunchPreparationRequest request, CanonicalRealmCatalogSnapshot catalog) { + if (!request.targetNamespace().equals(catalog.targetNamespace()) + || !request.canonicalTenantId().equals(catalog.tenantId()) + || !request.realmId().equals(catalog.realmId()) + || !request.catalogCreationRequestId().equals(catalog.creationRequestId()) + || request.catalogRevision() != catalog.catalogRevision() + || !catalog.visible() + || !catalog.publicProduction()) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact committed initial catalog"); + } + } + + private static void requireSourceBinding( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + if (!request.targetNamespace().equals(source.source().targetNamespace()) + || !request.canonicalTenantId().equals(source.source().canonicalTenantId()) + || !request.sourceIntakeOperationId().equals(source.operationId()) + || !catalog.sourceIntakeReceipt().equals(source) + || !"NEW_GAME_ROW".equals(source.source().provenanceKind()) + || !catalog.worldSlug().equals(source.source().worldSlug())) { + throw new InvalidLaunchPreparationEvidenceException( + "Canonical launch request does not match the exact fresh source intake"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Canonical launch preparation cannot enter from an ambient transaction"); + } + } + + private static UUID randomNonNilUuid() { + UUID value; + do { + value = UUID.randomUUID(); + } while (new UUID(0L, 0L).equals(value)); + return value; + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index dc77068423..bbd83a59c0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -1,17 +1,15 @@ package net.firedevops.firemud.gamesession; import static org.assertj.core.api.Assertions.assertThat; -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.nullable; import static org.mockito.Mockito.when; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; -import net.firedevops.firemud.common.ApiResponse; -import net.firedevops.firemud.common.ResultStatus; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.common.settings.ScopedSettingsOverrides; import net.firedevops.firemud.common.settings.ScopedSettingsSnapshot; @@ -20,15 +18,17 @@ import net.firedevops.firemud.gamesession.client.GameDesignClient; import net.firedevops.firemud.gamesession.client.GameLogicClient; 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.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.FiremudAuthTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; @@ -41,7 +41,6 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import tools.jackson.core.type.TypeReference; import tools.jackson.databind.ObjectMapper; @Testcontainers(disabledWithoutDocker = true) @@ -88,168 +87,40 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @MockitoBean private SharedSettingsAuthorityReader sharedSettingsAuthorityReader; - @org.springframework.beans.factory.annotation.Autowired - private SessionContextService sessionContextService; + @Autowired private SessionContextService sessionContextService; + + @Autowired private GameInstanceRepository gameInstanceRepository; @Test - void startSessionUsesRealHttpAndPersistencePath() throws Exception { + void legacyNumericStartIsDeniedBeforePersistenceOrWorldPreparation() throws Exception { when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) .thenReturn( net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-1") - .setTenantId("42") - .setGameTemplateId(7L) - .setControlPlaneRequestId("cp-1") - .setVersionId(11L) - .setScriptPatchVersion("patch-1") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:42:11:77") - .build()) - .build()); - when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(77L) - .setVersionId(11L) - .setAttestationSchemaVersion("v1") - .setManifestHash("manifest-11") - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-11") - .build()) - .build()); - when(gameDesignClient.getVersionAssetArtifactState(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse.newBuilder() - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId("42") - .setVersionId(11L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState - .ARTIFACT_STATE_PUBLISHED) - .setStateEpoch(2L) - .setManifestHash("manifest-11") - .addExportedManifestAssetKeys("manifest.json") + .setError( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("Numeric Game Session launch selectors are not authorizing") .build()) .build()); - when(gameDesignClient.getVersionState(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse.newBuilder() - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() - .setTenantId("42") - .setVersionId(11L) - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setVersionStateEpoch(77L) - .setUpdatedAt("2026-04-15T10:00:00") - .build()) - .build()); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - nullable(String.class), - anyString(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId(Long.toString(invocation.getArgument(2, Long.class))) - .setControlPlaneRequestId(invocation.getArgument(3, String.class)) - .setLaunchDescriptorId(invocation.getArgument(4, String.class)) - .setVersionId(Long.toString(invocation.getArgument(5, Long.class))) - .setReleaseBundleId( - Long.toString(invocation.getArgument(9, Long.class))) - .setGenerationConfigRevision(invocation.getArgument(8, String.class)) - .setPublishedReleaseBundleRef(invocation.getArgument(10, String.class)) - .setVersionStateEpoch(invocation.getArgument(11, Long.class)) - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()); - when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); StartSessionRequest request = new StartSessionRequest(42L, 7L, "cp-1", 100L); - String responseBody = - HttpTestSupport.postJsonBodyUnchecked( - "http://localhost:" + port + "/sessions", - OBJECT_MAPPER.writeValueAsString(request), - privilegedHeaders()); - ApiResponse body = - OBJECT_MAPPER.readValue(responseBody, new TypeReference>() {}); - - org.mockito.Mockito.verify(worldManagementClient) - .prepareWorldInstance( - eq(42L), - anyLong(), - eq(7L), - eq("cp-1"), - eq("ld-1"), - eq(11L), - org.mockito.ArgumentMatchers.isNull(), - eq("{}"), - eq("genrev-11"), - eq(77L), - eq("prb:42:11:77"), - eq(77L), - any()); - - assertThat(body).isNotNull(); - assertThat(body.status()).isEqualTo(ResultStatus.SUCCESS); - assertThat(body.data()).isNotNull(); - assertThat(body.data().tenantId()).isEqualTo(42L); - assertThat(body.data().runtimeVersion()).isEqualTo("11"); - assertThat(body.data().scriptPatchVersion()).isNull(); - assertThat(body.data().scriptPinEpoch()).isNull(); - assertThat(body.data().gameTemplateId()).isEqualTo(7L); - assertThat(body.data().launchDescriptorId()).isEqualTo("ld-1"); - assertThat(body.data().versionId()).isEqualTo(11L); - assertThat(body.data().releaseBundleId()).isEqualTo(77L); - assertThat(body.data().versionStateEpoch()).isEqualTo(77L); - assertThat(body.data().generationConfigRevision()).isEqualTo("genrev-11"); - assertThat(body.data().ownerAccountId()).isEqualTo(100L); - assertThat(body.data().status()).isEqualTo("RUNNING"); - assertThat(body.data().id()).isPositive(); + HttpRequest.Builder httpRequest = + HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/sessions")) + .header("Content-Type", "application/json"); + privilegedHeaders().forEach(httpRequest::header); + HttpResponse response = + HttpClient.newHttpClient() + .send( + httpRequest + .POST( + HttpRequest.BodyPublishers.ofString( + OBJECT_MAPPER.writeValueAsString(request), StandardCharsets.UTF_8)) + .build(), + HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + + assertThat(response.statusCode()).isGreaterThanOrEqualTo(400); + assertThat(gameInstanceRepository.findAll()).isEmpty(); + org.mockito.Mockito.verifyNoInteractions(worldManagementClient); } @Test 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 new file mode 100644 index 0000000000..74c72fac1a --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -0,0 +1,588 @@ +package integration.net.firedevops.firemud.gamesession.service; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +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.gamedesign.AuthoredWorldLaunchDescriptorClient; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +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.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.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; + +/** + * Real PostgreSQL source/catalog transactions and immutable preparation storage. Game Design's + * descriptor response is deliberately synthetic here; this is not transport or mTLS proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { + private static final String NAMESPACE = "canonical-launch-it"; + private static final UUID TENANT = uuid(101); + private static final UUID SOURCE_OPERATION = uuid(102); + private static final UUID INTAKE_REQUEST = uuid(104); + private static final UUID CATALOG_REQUEST = uuid(105); + private static final UUID ACTOR = uuid(106); + private static final UUID REALM = uuid(107); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final long RETAINED_TENANT_ID = 917L; + private static final long RETAINED_GAME_INSTANCE_ID = 901L; + private static final UUID RETAINED_REALM_ID = uuid(108); + private static final UUID RETAINED_PLAYABLE_NAMESPACE_ID = uuid(109); + private static final UUID RETAINED_SHARED_NAMESPACE_ID = uuid(110); + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void + commitsExactFreshSourceCatalogAndSyntheticDescriptorThenReplaysWithoutChangingRetainedRows() { + Fixture fixture = fixture(true, true); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = java.util.Objects.requireNonNull(fixture.preV14Source); + CanonicalRealmCatalogSnapshot catalog = java.util.Objects.requireNonNull(fixture.preV14Catalog); + assertThat( + fixture.sourceRepository.read( + source.operationId(), TENANT, source.source().worldSlug(), NAMESPACE)) + .contains(source); + assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .contains(catalog); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorClient syntheticGameDesign = syntheticGameDesignClient(); + GameSessionCanonicalLaunchPreparationService service = fixture.service(syntheticGameDesign); + + CanonicalLaunchPreparationSnapshot first = service.prepare(request); + // A repeated call models recovery after the caller loses the first successful response. + CanonicalLaunchPreparationSnapshot retry = service.prepare(request); + + assertThat(first).isEqualTo(retry); + assertThat(first.operationId()).isNotEqualTo(NIL_UUID); + assertThat(first.catalogSnapshot()).isEqualTo(catalog); + assertThat(first.sourceIntakeReceipt()).isEqualTo(source); + first.launchDescriptorEvidence().requireValid(); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isEqualTo(1); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT game_instance_uuid FROM game_instances WHERE id = ?", + RETAINED_GAME_INSTANCE_ID) + .get("game_instance_uuid", UUID.class)) + .isNull(); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT representation_version, tenant_id, game_instance_id, realm_id, " + + "canonical_tenant_id, playable_state_namespace_id FROM gameplay_admission_pointer " + + "WHERE tenant_id = ?", + RETAINED_TENANT_ID)) + .satisfies( + row -> { + assertThat(row.get("representation_version", Integer.class)).isEqualTo(1); + assertThat(row.get("tenant_id", Long.class)).isEqualTo(RETAINED_TENANT_ID); + assertThat(row.get("game_instance_id", Long.class)).isEqualTo(501L); + assertThat(row.get("realm_id", UUID.class)).isEqualTo(RETAINED_REALM_ID); + assertThat(row.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + }); + assertThat( + requiredRecord( + fixture.dsl, + "SELECT playable_state_namespace_id FROM " + + "gameplay_tenant_shared_playable_state_namespace WHERE tenant_id = ?", + RETAINED_TENANT_ID) + .get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_SHARED_NAMESPACE_ID); + verify(syntheticGameDesign, times(1)).resolve(any()); + verify(syntheticGameDesign, times(1)).get(any(GetRequest.class)); + } + + @Test + void ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation() { + Fixture fixture = fixture(false, false); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request, catalog, source); + + assertThatThrownBy( + () -> + fixture.transactions.execute( + status -> { + fixture.preparationRepository.persistPrepared( + request, catalog, source, descriptor); + throw new IllegalStateException("forced owner rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("forced owner rollback"); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isZero(); + + CanonicalLaunchPreparationSnapshot committed = + fixture.service(syntheticGameDesignClient()).prepare(request); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET receipt_digest = ? WHERE target_namespace = ?", + digest("f"), + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_launch_preparation " + + "WHERE target_namespace = ?", + NAMESPACE)) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThatThrownBy( + () -> fixture.dsl.execute("TRUNCATE game_session_canonical_launch_preparation")) + .isInstanceOf(DataAccessException.class) + .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); + assertThat( + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .contains(committed); + + // Simulate privileged storage corruption in this isolated test schema; normal update/delete + // paths remain blocked by the immutable trigger above. + fixture.transactions.execute( + status -> { + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation DISABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET catalog_evidence_json = jsonb_set(catalog_evidence_json, " + + "'{realmDisplayName}', to_jsonb(CAST(? AS text))) " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + "Tampered Realm Display Name", + NAMESPACE, + request.controlPlaneRequestId()); + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation ENABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + return null; + }); + assertThatThrownBy( + () -> + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) + .isInstanceOf( + GameSessionCanonicalLaunchPreparationRepository + .InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("stored identity and digests"); + } + + @Test + void concurrentExactPreparationsReturnOneImmutableOperation() throws Exception { + Fixture fixture = fixture(false, false); + IntakeReceipt source = fixture.registerFreshSource(); + CanonicalRealmCatalogSnapshot catalog = fixture.createCatalog(source); + CreateCanonicalLaunchPreparationRequest request = request(source, catalog); + CountDownLatch bothResolved = new CountDownLatch(2); + AuthoredWorldLaunchDescriptorClient concurrentGameDesign = + concurrentSyntheticGameDesignClient(bothResolved); + GameSessionCanonicalLaunchPreparationService service = fixture.service(concurrentGameDesign); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> service.prepare(request)); + Future second = + executor.submit(() -> service.prepare(request)); + + assertThat(bothResolved.await(15, TimeUnit.SECONDS)).isTrue(); + CanonicalLaunchPreparationSnapshot firstResult = first.get(15, TimeUnit.SECONDS); + CanonicalLaunchPreparationSnapshot secondResult = second.get(15, TimeUnit.SECONDS); + + assertThat(firstResult).isEqualTo(secondResult); + assertThat(firstResult.operationId()).isEqualTo(secondResult.operationId()); + assertThat( + fixture.dsl.fetchCount( + DSL.table(DSL.name("game_session_canonical_launch_preparation")))) + .isEqualTo(1); + verify(concurrentGameDesign, times(2)).resolve(any()); + verify(concurrentGameDesign, times(2)).get(any(GetRequest.class)); + } finally { + executor.shutdownNow(); + } + } + + private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient() { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorClient concurrentSyntheticGameDesignClient( + CountDownLatch bothResolved) { + AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); + when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) + .thenAnswer( + invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + bothResolved.countDown(); + try { + if (!bothResolved.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent exact attempts did not both resolve"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Concurrent exact attempt was interrupted", exception); + } + return syntheticDescriptor(request); + }); + when(client.get(any(GetRequest.class))) + .thenAnswer( + invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); + return client; + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source) { + return syntheticDescriptor(request.descriptorRequest(catalog, source.source())); + } + + private static AuthoredWorldLaunchDescriptorEvidence syntheticDescriptor( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "synthetic-descriptor-" + request.controlPlaneRequestId(), + 515, + false, + null, + "{}", + "generation-config-1", + 4, + 616, + "synthetic-published-release-616", + false, + null); + } + + private static CreateCanonicalLaunchPreparationRequest request( + IntakeReceipt source, CanonicalRealmCatalogSnapshot catalog) { + return new CreateCanonicalLaunchPreparationRequest( + "canonical-launch-it-" + catalog.realmId(), + ACTOR, + NAMESPACE, + TENANT, + catalog.realmId(), + catalog.creationRequestId(), + catalog.catalogRevision(), + source.operationId(), + 404, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private Fixture fixture( + boolean seedRetainedNumericRows, boolean seedCanonicalOwnerEvidenceBeforeV14) { + String schema = "gs_canonical_launch_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + 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) + .target(MigrationVersion.fromVersion("11")) + .load() + .migrate(); + + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + if (seedRetainedNumericRows) { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, owner_account_id, status) " + + "VALUES (?, ?, ?, ?, ?)", + RETAINED_GAME_INSTANCE_ID, + RETAINED_TENANT_ID, + "retained-runtime", + 77L, + "RUNNING"); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace " + + "(tenant_id, playable_state_namespace_id) VALUES (?, ?)", + RETAINED_TENANT_ID, + RETAINED_SHARED_NAMESPACE_ID); + dsl.execute( + "INSERT INTO gameplay_admission_pointer " + + "(world_slug, world_display_name, realm_slug, 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, realm_id, playable_state_namespace_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "legacy-world", + "Legacy World", + "legacy-realm", + "Legacy Realm", + RETAINED_TENANT_ID, + 501L, + 1L, + true, + false, + "SHARED", + "ALLOW_NEW", + "fixture", + "retained evidence", + true, + RETAINED_REALM_ID, + RETAINED_PLAYABLE_NAMESPACE_ID); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("13")) + .load() + .migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + DSLContext transactionalDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + GameSessionAuthoredWorldSourceRepository sourceRepository = + new GameSessionAuthoredWorldSourceRepository(transactionalDsl); + GameSessionCanonicalRealmCatalogRepository catalogRepository = + new GameSessionCanonicalRealmCatalogRepository(transactionalDsl); + IntakeReceipt preV14Source = null; + CanonicalRealmCatalogSnapshot preV14Catalog = null; + if (seedCanonicalOwnerEvidenceBeforeV14) { + preV14Source = + java.util.Objects.requireNonNull( + transactions.execute( + status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); + CreateCanonicalRealmCatalogRequest catalogRequest = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + preV14Source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); + preV14Catalog = + java.util.Objects.requireNonNull( + transactions.execute( + status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); + } + + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + GameSessionCanonicalLaunchPreparationRepository preparationRepository = + new GameSessionCanonicalLaunchPreparationRepository(transactionalDsl, catalogRepository); + return new Fixture( + transactionalDsl, + sourceRepository, + catalogRepository, + preparationRepository, + transactionManager, + transactions, + preV14Source, + preV14Catalog); + } + + private static AuthoredWorldSourceEvidence freshSource() { + String worldSlug = "violet-wilds"; + String tenantSlug = "tenant-" + TENANT.toString().substring(0, 8); + String displayName = "Violet Wilds"; + UUID registrationRequestId = uuid(111); + long sourceGameRowId = 821; + String sourceGameTenantKey = "fresh-source-821"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationRequestId, TENANT, tenantSlug, worldSlug, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + SOURCE_OPERATION, + requestDigest, + TENANT, + tenantSlug, + worldSlug, + displayName, + sourceGameRowId, + sourceGameTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + } + + 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"); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private record Fixture( + DSLContext dsl, + GameSessionAuthoredWorldSourceRepository sourceRepository, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + GameSessionCanonicalLaunchPreparationRepository preparationRepository, + DataSourceTransactionManager transactionManager, + TransactionTemplate transactions, + IntakeReceipt preV14Source, + CanonicalRealmCatalogSnapshot preV14Catalog) { + IntakeReceipt registerFreshSource() { + IntakeReceipt receipt = + transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); + return java.util.Objects.requireNonNull(receipt); + } + + CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { + CreateCanonicalRealmCatalogRequest request = + new CreateCanonicalRealmCatalogRequest( + CATALOG_REQUEST, + NAMESPACE, + TENANT, + source.operationId(), + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + "explicit-policy-v1", + null, + null); + var prepared = catalogRepository.prepareInitialPublicProduction(request); + CanonicalRealmCatalogSnapshot created = + transactions.execute(status -> catalogRepository.createInitialPublicProduction(prepared)); + return java.util.Objects.requireNonNull(created); + } + + GameSessionCanonicalLaunchPreparationService service( + AuthoredWorldLaunchDescriptorClient descriptorClient) { + return new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index 70dddcb0f1..82555d44cc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -5,10 +5,10 @@ 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.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -31,6 +31,7 @@ import net.firedevops.firemud.gamesession.service.CommandService; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionStateService; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -133,197 +134,9 @@ void setUp() throws Exception { entity.getStatus()); }); when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-1") - .setTenantId("42") - .setGameTemplateId(7L) - .setControlPlaneRequestId("cp-1") - .setVersionId(11L) - .setScriptPatchVersion("patch-1") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef("prb:42:11:77") - .build()) - .build()); + .thenReturn(deniedNumericLaunchResponse()); when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-2")) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-2") - .setTenantId("42") - .setGameTemplateId(7L) - .setControlPlaneRequestId("cp-2") - .setVersionId(12L) - .setScriptPatchVersion("patch-2") - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-12") - .setVersionStateEpoch(78L) - .setReleaseBundleId(78L) - .setPublishedReleaseBundleRef("prb:42:12:78") - .build()) - .build()); - when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(77L) - .setVersionId(11L) - .setAttestationSchemaVersion("v1") - .setManifestHash("manifest-11") - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-11") - .build()) - .build()); - when(gameDesignClient.getVersionAssetArtifactState(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse.newBuilder() - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId("42") - .setVersionId(11L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState - .ARTIFACT_STATE_PUBLISHED) - .setStateEpoch(2L) - .setManifestHash("manifest-11") - .addExportedManifestAssetKeys("manifest.json") - .build()) - .build()); - when(gameDesignClient.getVersionState(42L, 11L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse.newBuilder() - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() - .setTenantId("42") - .setVersionId(11L) - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setVersionStateEpoch(77L) - .setUpdatedAt("2026-04-15T10:00:00") - .build()) - .build()); - when(gameDesignClient.getPublishedReleaseBundle(42L, 12L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse.newBuilder() - .setBundle( - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(78L) - .setVersionId(12L) - .setAttestationSchemaVersion("v1") - .setManifestHash("manifest-12") - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-12") - .build()) - .build()); - when(gameDesignClient.getVersionAssetArtifactState(42L, 12L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse.newBuilder() - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId("42") - .setVersionId(12L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState - .ARTIFACT_STATE_PUBLISHED) - .setStateEpoch(3L) - .setManifestHash("manifest-12") - .addExportedManifestAssetKeys("manifest.json") - .build()) - .build()); - when(gameDesignClient.getVersionState(42L, 12L)) - .thenReturn( - net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse.newBuilder() - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() - .setTenantId("42") - .setVersionId(12L) - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setVersionStateEpoch(78L) - .setUpdatedAt("2026-04-15T10:00:00") - .build()) - .build()); - when(worldManagementClient.prepareWorldInstance( - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - anyLong(), - any(), - any(), - anyString(), - anyLong(), - anyString(), - anyLong(), - any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId(Long.toString(invocation.getArgument(2, Long.class))) - .setControlPlaneRequestId(invocation.getArgument(3, String.class)) - .setLaunchDescriptorId(invocation.getArgument(4, String.class)) - .setVersionId(Long.toString(invocation.getArgument(5, Long.class))) - .setReleaseBundleId( - Long.toString(invocation.getArgument(9, Long.class))) - .setGenerationConfigRevision(invocation.getArgument(8, String.class)) - .setPublishedReleaseBundleRef(invocation.getArgument(10, String.class)) - .setVersionStateEpoch(invocation.getArgument(11, Long.class)) - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()); - when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); - when(worldManagementClient.failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) - .build()) - .build()); + .thenReturn(deniedNumericLaunchResponse()); when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) .thenAnswer( invocation -> @@ -362,17 +175,13 @@ void setUp() throws Exception { } @Test - void startSessionRollsBackWhenStatePropagationFails() { - doThrow(new IllegalStateException("state propagation failed")) - .when(sessionStateService) - .saveState(any()); - + void numericStartIsDeniedBeforeStateOrWorldMutation() { assertThatThrownBy(() -> service.startSession(new StartSessionRequest(42L, 7L, "cp-1", 100L))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("state propagation failed"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FAILED_PRECONDITION"); assertThat(repository.findAll()).isEmpty(); - verify(sessionStateService).saveState(any()); + verifyNoInteractions(sessionStateService, worldManagementClient); } @Test @@ -433,7 +242,7 @@ void restartSessionRollsBackWhenStatePropagationFails() { } @Test - void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { + void numericReplacementLaunchIsDeniedBeforeChangingPriorRunningSession() { GameInstance existing = new GameInstance(); existing.setTenantId(42L); existing.setRuntimeVersion("1.0.0"); @@ -445,14 +254,10 @@ void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { existing = repository.saveAndFlush(existing); long existingId = existing.getId(); - doThrow(new IllegalStateException("state propagation failed")) - .when(sessionStateService) - .saveState(any()); - assertThatThrownBy( () -> service.startSession(new StartSessionRequest(42L, 7L, "cp-2", 100L), true)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("state propagation failed"); + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FAILED_PRECONDITION"); assertThat(repository.findAll()).hasSize(1); GameInstance restored = repository.findById(existingId).orElseThrow(); @@ -462,10 +267,11 @@ void replacingExistingSessionRestoresPriorRunningSessionWhenNewStartFails() { assertThat(restored.getScriptPinEpoch()).isEqualTo(1L); assertThat(restored.getScriptPatchPinnedControlPlaneRequestId()).isEqualTo("pin-request-1"); assertThat(restored.getOwnerAccountId()).isEqualTo(100L); + verifyNoInteractions(sessionStateService, worldManagementClient); } @Test - void replacingExistingSessionTerminatesPriorWorldBeforeFinalizingReplacement() { + void numericReplacementLaunchIsDeniedBeforePriorWorldTermination() { GameInstance existing = new GameInstance(); existing.setTenantId(42L); existing.setRuntimeVersion("1.0.0"); @@ -477,15 +283,25 @@ void replacingExistingSessionTerminatesPriorWorldBeforeFinalizingReplacement() { existing = repository.saveAndFlush(existing); long existingId = existing.getId(); - GameInstanceDto started = - service.startSession(new StartSessionRequest(42L, 7L, "cp-2", 100L), true); - - assertThat(started.status()).isEqualTo("RUNNING"); + assertThatThrownBy( + () -> service.startSession(new StartSessionRequest(42L, 7L, "cp-2", 100L), true)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("FAILED_PRECONDITION"); assertThat(repository.findById(existingId)).isPresent(); - assertThat(repository.findById(existingId).orElseThrow().getStatus()).isEqualTo("STOPPED"); - verify(worldManagementClient).getWorldInstanceLifecycle(42L, existingId); - verify(worldManagementClient) - .terminateWorldInstance(anyLong(), eq(existingId), anyLong(), any(), any()); + assertThat(repository.findById(existingId).orElseThrow().getStatus()).isEqualTo("RUNNING"); + assertThat(repository.findAll()).hasSize(1); + verifyNoInteractions(sessionStateService, worldManagementClient); + } + + private static net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse + deniedNumericLaunchResponse() { + return net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("Numeric Game Session launch selectors cannot authorize a launch") + .build()) + .build(); } @TestConfiguration diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java new file mode 100644 index 0000000000..2c2536f491 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -0,0 +1,853 @@ +package net.firedevops.firemud.gamesession.service; + +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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +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; +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.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalLaunchPreparationSnapshot; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalLaunchPreparationRequest; +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.GameSessionCanonicalLaunchPreparationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.InvalidLaunchPreparationEvidenceException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalLaunchPreparationRepository.LaunchPreparationConflictException; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class GameSessionCanonicalLaunchPreparationServiceTest { + private static final String NAMESPACE = "canonical-launch-test"; + private static final String CONTROL_PLANE_REQUEST = "launch-attempt-1"; + private static final UUID ACTOR = uuid(1); + private static final UUID TENANT = uuid(2); + private static final UUID SOURCE_OPERATION = uuid(3); + private static final UUID SOURCE_INTAKE_OPERATION = uuid(4); + private static final UUID INTAKE_REQUEST = uuid(5); + private static final UUID REALM = uuid(6); + private static final UUID CATALOG_REQUEST = uuid(7); + + private final AuthoredWorldLaunchDescriptorClient descriptorClient = + mock(AuthoredWorldLaunchDescriptorClient.class); + private final GameSessionCanonicalRealmCatalogRepository catalogRepository = + mock(GameSessionCanonicalRealmCatalogRepository.class); + private final GameSessionAuthoredWorldSourceRepository sourceRepository = + mock(GameSessionAuthoredWorldSourceRepository.class); + private final GameSessionCanonicalLaunchPreparationRepository preparationRepository = + mock(GameSessionCanonicalLaunchPreparationRepository.class); + private final RecordingTransactionManager transactionManager = new RecordingTransactionManager(); + private final GameSessionCanonicalLaunchPreparationService service = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsAmbientTransactionBeforeAnyOwnerReadOrNetworkCall() { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.prepare(request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void rejectsAmbientTransactionBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void readsCompleteBindingOnlyForExactCommittedPreparationAndPreservesBothSharedEvidenceValues() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + CompleteLaunchBindingEvidence binding = completeBinding(snapshot.launchDescriptorEvidence()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(binding); + + assertThat(service.readCompleteBinding(snapshot)).isEqualTo(binding); + + ArgumentCaptor request = + ArgumentCaptor.forClass(GetLaunchDescriptorRequest.class); + verify(descriptorClient).getComplete(request.capture()); + GetLaunchDescriptorRequest selector = request.getValue(); + assertThat(UUID.fromString(selector.getRequestId())).isNotEqualTo(SOURCE_OPERATION); + assertThat(selector) + .isEqualTo( + AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest( + new GetRequest( + UUID.fromString(selector.getRequestId()), + snapshot.launchDescriptorEvidence().request(), + snapshot.launchDescriptorEvidence().resultDigest()))); + assertThat(selector.getCanonicalTenantId()).isEqualTo(TENANT.toString()); + assertThat(selector.getWorldSlug()).isEqualTo(snapshot.launchDescriptorEvidence().worldSlug()); + assertThat(selector.getControlPlaneRequestId()).isEqualTo(CONTROL_PLANE_REQUEST); + assertThat(selector.getExpectedRequestDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().requestDigest()); + assertThat(selector.getExpectedResultDigest()) + .isEqualTo(snapshot.launchDescriptorEvidence().resultDigest()); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient, never()).resolve(any()); + verify(descriptorClient, never()).get(any(GetRequest.class)); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedCommittedSourceFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot requested = preparedSnapshot(); + AuthoredWorldSourceEvidence changedSource = source("emerald-grove"); + IntakeReceipt changedIntake = intake(changedSource); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(changedIntake); + CanonicalLaunchPreparationSnapshot changedCommitted = + snapshot( + requested.request(), + changedCatalog, + changedIntake, + descriptor(requested.request(), changedCatalog, changedSource)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(changedCommitted)); + + assertThatThrownBy(() -> service.readCompleteBinding(requested)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed before complete binding read"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verifyNoInteractions(descriptorClient); + } + + @Test + void missingCommittedPreparationFailsBeforeCompleteBindingNetworkRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("missing before complete binding read"); + + verifyNoInteractions(descriptorClient); + } + + @Test + void namespaceMismatchFailsBeforeCompleteBindingOwnerReadOrNetworkCall() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + GameSessionCanonicalLaunchPreparationService otherNamespaceService = + new GameSessionCanonicalLaunchPreparationService( + descriptorClient, + catalogRepository, + sourceRepository, + preparationRepository, + transactionManager, + NAMESPACE + "-other"); + + assertThatThrownBy(() -> otherNamespaceService.readCompleteBinding(snapshot)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + @Test + void changedCompleteDescriptorFailsAfterExactCommittedPreparationRead() { + CanonicalLaunchPreparationSnapshot snapshot = preparedSnapshot(); + AuthoredWorldLaunchDescriptorEvidence original = snapshot.launchDescriptorEvidence(); + AuthoredWorldLaunchDescriptorEvidence changed = + AuthoredWorldLaunchDescriptorEvidence.create( + original.request(), + original.launchDescriptorId() + "-changed", + original.versionId(), + original.scriptPatchVersionPresent(), + original.scriptPatchVersion(), + original.runtimeFlagsJson(), + original.generationConfigRevision(), + original.versionStateEpoch(), + original.releaseBundleId(), + original.publishedReleaseBundleRef(), + original.remapSetIdPresent(), + original.remapSetId()); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(snapshot)); + when(descriptorClient.getComplete(any(GetLaunchDescriptorRequest.class))) + .thenReturn(completeBinding(changed)); + + assertThatThrownBy(() -> service.readCompleteBinding(snapshot)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("differs from the committed launch descriptor"); + + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(descriptorClient).getComplete(any(GetLaunchDescriptorRequest.class)); + } + + @Test + void resolvesThenGetsExactDescriptorOutsideShortOwnerTransactionAndReadsCommitBack() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot snapshot = snapshot(request, catalog, intake, descriptor); + stubNewPreparation(request, source, intake, catalog, descriptor, snapshot); + + assertThat(service.prepare(request)).isEqualTo(snapshot); + + ArgumentCaptor getRequest = ArgumentCaptor.forClass(GetRequest.class); + verify(descriptorClient).resolve(descriptor.request()); + verify(descriptorClient).get(getRequest.capture()); + assertThat(getRequest.getValue().expectedRequest()).isEqualTo(descriptor.request()); + assertThat(getRequest.getValue().expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + assertThat(getRequest.getValue().requestId()).isNotEqualTo(SOURCE_OPERATION); + assertThat(transactionManager.startedWith.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(transactionManager.startedWith.isReadOnly()).isFalse(); + assertThat(transactionManager.startedWith.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionManager.commitCount).isEqualTo(1); + verify(preparationRepository).persistPrepared(request, catalog, intake, descriptor); + } + + @Test + void changedDurableCommitReadbackFailsWithoutRepairingTheStoredPreparation() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot written = snapshot(request, catalog, intake, descriptor); + CanonicalLaunchPreparationSnapshot changedReadback = + snapshot(request, catalog, intake, descriptor, uuid(14)); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(changedReadback)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())).thenReturn(descriptor); + when(descriptorClient.get(any(GetRequest.class))).thenReturn(descriptor); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenReturn(written); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("changed during independent commit readback"); + + verify(preparationRepository, times(1)).persistPrepared(request, catalog, intake, descriptor); + verify(preparationRepository, times(2)) + .readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + } + + @Test + void exactRetryReturnsOriginalPreparationWithoutRepeatingSourceOrDescriptorCalls() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(request, catalog, source); + CanonicalLaunchPreparationSnapshot original = snapshot(request, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + + assertThat(service.prepare(request)).isEqualTo(original); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository).readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void changedRetryInputConflictsBeforeUpstreamResolutionOrMutation() { + CreateCanonicalLaunchPreparationRequest originalRequest = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence descriptor = descriptor(originalRequest, catalog, source); + CanonicalLaunchPreparationSnapshot original = + snapshot(originalRequest, catalog, intake, descriptor); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.of(original)); + CreateCanonicalLaunchPreparationRequest changed = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", // Present-empty remains distinct from absence. + false, + null, + false, + null, + false, + null); + + assertThatThrownBy(() -> service.prepare(changed)) + .isInstanceOf(LaunchPreparationConflictException.class) + .hasMessageContaining("changed"); + + verifyNoInteractions(descriptorClient, catalogRepository, sourceRepository); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + assertThat(transactionManager.startedWith).isNull(); + } + + @Test + void catalogAndSourceSubstitutionFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest request = request(); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + CanonicalRealmCatalogSnapshot changedCatalog = catalog(intake(source()), uuid(88)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(changedCatalog)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source, uuid(89)); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact fresh source intake"); + verifyNoInteractions(descriptorClient); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void namespaceTenantAndCatalogSelectorMismatchesFailBeforeDescriptorResolution() { + CreateCanonicalLaunchPreparationRequest wrongNamespace = + request(NAMESPACE + "-other", TENANT, CATALOG_REQUEST, 1); + assertThatThrownBy(() -> service.prepare(wrongNamespace)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("namespace"); + verifyNoInteractions( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + + resetRepositories(); + CreateCanonicalLaunchPreparationRequest wrongTenant = + request(NAMESPACE, uuid(91), CATALOG_REQUEST, 1); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongTenant)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + + resetRepositories(); + UUID changedCatalogRequestId = uuid(92); + CreateCanonicalLaunchPreparationRequest wrongCatalog = + request(NAMESPACE, TENANT, changedCatalogRequestId, 2); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, changedCatalogRequestId)) + .thenReturn(Optional.of(catalog(intake(source())))); + + assertThatThrownBy(() -> service.prepare(wrongCatalog)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("exact committed initial catalog"); + verifyNoInteractions(descriptorClient, sourceRepository); + } + + @Test + void descriptorAndIndependentReadbackMustBothMatchCompleteSharedEvidence() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence.Request expected = + request.descriptorRequest(catalog, source); + AuthoredWorldLaunchDescriptorEvidence substituted = + AuthoredWorldLaunchDescriptorEvidence.create( + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + CONTROL_PLANE_REQUEST, + TENANT, + catalog.worldSlug(), + uuid(90), + source.evidenceDigest(), + 71, + false, + null, + false, + null, + false, + null, + false, + null), + "descriptor-90", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(expected)).thenReturn(substituted); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("does not match"); + verify(descriptorClient, never()).get(any()); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + + resetRepositories(); + AuthoredWorldLaunchDescriptorEvidence resolved = descriptor(request, catalog, source); + AuthoredWorldLaunchDescriptorEvidence changedReadback = + AuthoredWorldLaunchDescriptorEvidence.create( + resolved.request(), + "changed-descriptor-readback", + 74, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty()); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(resolved.request())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return resolved; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return changedReadback; + }); + + assertThatThrownBy(() -> service.prepare(request)) + .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) + .hasMessageContaining("readback differs"); + verify(preparationRepository, never()).persistPrepared(any(), any(), any(), any()); + } + + @Test + void requestDigestBindsOptionalPresenceAndDescriptorDigest() { + CreateCanonicalLaunchPreparationRequest absent = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + AuthoredWorldLaunchDescriptorEvidence absentDescriptor = descriptor(absent, catalog, source); + CreateCanonicalLaunchPreparationRequest presentEmpty = + new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + NAMESPACE, + TENANT, + REALM, + CATALOG_REQUEST, + 1, + SOURCE_INTAKE_OPERATION, + 71, + true, + "", + false, + null, + false, + null, + false, + null); + AuthoredWorldLaunchDescriptorEvidence presentEmptyDescriptor = + descriptor(presentEmpty, catalog, source); + + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + presentEmpty, catalog, intake, presentEmptyDescriptor)); + + CanonicalRealmCatalogSnapshot changedCatalogPayload = + new CanonicalRealmCatalogSnapshot( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.tenantSlug(), + catalog.worldSlug(), + catalog.realmId(), + "changed-realm-slug", + "Changed Realm Display Name", + catalog.visible(), + catalog.publicProduction(), + catalog.stateScope(), + uuid(93), + catalog.characterCreationPolicy(), + catalog.catalogRevision(), + catalog.creationRequestId(), + catalog.requestDigest(), + catalog.receiptDigest(), + intake); + assertThat( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, changedCatalogPayload, intake, absentDescriptor)) + .isNotEqualTo( + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + absent, catalog, intake, absentDescriptor)); + } + + private void stubNewPreparation( + CreateCanonicalLaunchPreparationRequest request, + AuthoredWorldSourceEvidence sourceEvidence, + IntakeReceipt intake, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldLaunchDescriptorEvidence descriptor, + CanonicalLaunchPreparationSnapshot snapshot) { + when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) + .thenReturn(Optional.empty(), Optional.of(snapshot)); + when(catalogRepository.readByRequest(NAMESPACE, CATALOG_REQUEST)) + .thenReturn(Optional.of(catalog)); + when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) + .thenReturn(Optional.of(intake)); + when(descriptorClient.resolve(descriptor.request())) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(descriptorClient.get(any(GetRequest.class))) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); + when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) + .thenAnswer( + ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(descriptor.authoredWorldSourceOperationId()) + .isEqualTo(sourceEvidence.operationId()); + return snapshot; + }); + } + + private void resetRepositories() { + org.mockito.Mockito.reset( + descriptorClient, catalogRepository, sourceRepository, preparationRepository); + } + + private static CanonicalLaunchPreparationSnapshot preparedSnapshot() { + CreateCanonicalLaunchPreparationRequest request = request(); + AuthoredWorldSourceEvidence source = source(); + IntakeReceipt intake = intake(source); + CanonicalRealmCatalogSnapshot catalog = catalog(intake); + return snapshot(request, catalog, intake, descriptor(request, catalog, source)); + } + + private static CreateCanonicalLaunchPreparationRequest request() { + return request(NAMESPACE, TENANT, CATALOG_REQUEST, 1); + } + + private static CreateCanonicalLaunchPreparationRequest request( + String namespace, UUID tenant, UUID catalogRequest, long catalogRevision) { + return new CreateCanonicalLaunchPreparationRequest( + CONTROL_PLANE_REQUEST, + ACTOR, + namespace, + tenant, + REALM, + catalogRequest, + catalogRevision, + SOURCE_INTAKE_OPERATION, + 71, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private static AuthoredWorldSourceEvidence source() { + return source("violet-wilds"); + } + + private static AuthoredWorldSourceEvidence source(String world) { + String tenantSlug = "north-star"; + String displayName = "emerald-grove".equals(world) ? "Emerald Grove" : "Violet Wilds"; + UUID registrationId = uuid(10); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, registrationId, TENANT, tenantSlug, world, displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationId, + SOURCE_OPERATION, + sourceRequestDigest, + TENANT, + tenantSlug, + world, + displayName, + 44, + "fresh-source-key-44", + "NEW_GAME_ROW", + evidenceDigest); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source) { + return intake(source, SOURCE_INTAKE_OPERATION); + } + + private static IntakeReceipt intake(AuthoredWorldSourceEvidence source, UUID operationId) { + String requestDigest = + GameSessionAuthoredWorldIntakeDigest.requestDigest(INTAKE_REQUEST, source); + return new IntakeReceipt( + operationId, + INTAKE_REQUEST, + requestDigest, + source, + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + operationId, requestDigest, source.evidenceDigest())); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source) { + return catalog(source, REALM); + } + + private static CanonicalRealmCatalogSnapshot catalog(IntakeReceipt source, UUID realmId) { + return new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT, + source.source().tenantSlug(), + source.source().worldSlug(), + realmId, + "violet-realm", + "Violet Realm", + true, + true, + "SHARED", + uuid(12), + "explicit-policy-v1", + 1, + CATALOG_REQUEST, + digest("c"), + digest("d"), + source); + } + + private static AuthoredWorldLaunchDescriptorEvidence descriptor( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + AuthoredWorldSourceEvidence source) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request.descriptorRequest(catalog, source), + "launch-descriptor-1", + 72, + false, + null, + "{}", + "generation-1", + 3, + 73, + "bundle-73", + false, + null); + } + + private static CompleteLaunchBindingEvidence completeBinding( + AuthoredWorldLaunchDescriptorEvidence descriptor) { + String publishCommitId = "publish-commit-902"; + List participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + publishCommitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .toList(); + AuthoredWorldReleaseAttestationEvidence releaseAttestation = + AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + uuid(15), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + "publish:tenant:version:request", + publishCommitId, + participants, + digest("b"), + 1, + List.of(), + List.of(), + List.of(), + descriptor.generationConfigRevision()); + return new CompleteLaunchBindingEvidence(descriptor, releaseAttestation); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor) { + return snapshot(request, catalog, source, descriptor, uuid(13)); + } + + private static CanonicalLaunchPreparationSnapshot snapshot( + CreateCanonicalLaunchPreparationRequest request, + CanonicalRealmCatalogSnapshot catalog, + IntakeReceipt source, + AuthoredWorldLaunchDescriptorEvidence descriptor, + UUID operationId) { + String requestDigest = + GameSessionCanonicalLaunchPreparationRepository.requestDigest( + request, catalog, source, descriptor); + return new CanonicalLaunchPreparationSnapshot( + operationId, + request, + catalog, + source, + descriptor, + requestDigest, + GameSessionCanonicalLaunchPreparationRepository.receiptDigest( + operationId, request, catalog, source, descriptor, requestDigest)); + } + + private static String digest(String letter) { + return "sha256:" + letter.repeat(64); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private TransactionDefinition startedWith; + private int commitCount; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + startedWith = definition; + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly()); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + definition.getIsolationLevel()); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + commitCount++; + TransactionSynchronizationManager.clear(); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.clear(); + } + } +} From 6d8ce7dde0933c97f59eeda109725b5accf03caf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:19:07 +1300 Subject: [PATCH 04/34] test(game-design): prove canonical launch reader peer matrix --- .../CanonicalLaunchGrpcAuthWiringTest.java | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java index 2b673f3216..0897de7a99 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java @@ -69,6 +69,10 @@ class CanonicalLaunchGrpcAuthWiringTest { GET_COMPLETE_LAUNCH_BINDING_METHOD); private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String WORLD_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String ENTITY_MANAGEMENT_URI = + "spiffe://firemud/ns/test/sa/entity-management-service"; private static final String OTHER_NAMESPACE_GAME_SESSION_URI = "spiffe://firemud/ns/other/sa/game-session-service"; private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; @@ -173,6 +177,115 @@ void workloadPeerMustMatchNamespaceAndServiceEvenWhenMethodSkipsBearerValidation } } + @Test + void worldAndEntityPeersAreLimitedToTheirDeclaredLaunchReadHandlers() { + AuthTokenInterceptor interceptor = interceptor(); + Harness harness = harness(); + when(harness.launchDescriptorService() + .getLaunchDescriptor( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString())) + .thenThrow(new IllegalArgumentException("intentional exact read probe")); + when(harness.completeLaunchBindingService() + .getCompleteLaunchBinding( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString())) + .thenThrow(new IllegalArgumentException("intentional complete read probe")); + + DispatchResult worldDescriptorRead = + dispatchHandler( + interceptor, + harness, + WORLD_MANAGEMENT_URI, + new Metadata(), + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor); + DispatchResult worldCompleteRead = + dispatchHandler( + interceptor, + harness, + WORLD_MANAGEMENT_URI, + new Metadata(), + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding); + DispatchResult entityCompleteRead = + dispatchHandler( + interceptor, + harness, + ENTITY_MANAGEMENT_URI, + new Metadata(), + GET_COMPLETE_LAUNCH_BINDING_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetCompleteLaunchBindingResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getCompleteLaunchBinding); + + assertAllowedHandlerReached(worldDescriptorRead); + assertAllowedHandlerReached(worldCompleteRead); + assertAllowedHandlerReached(entityCompleteRead); + verify(harness.launchDescriptorService()) + .getLaunchDescriptor( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString()); + verify(harness.completeLaunchBindingService(), org.mockito.Mockito.times(2)) + .getCompleteLaunchBinding( + any(UUID.class), + any(UUID.class), + anyString(), + anyString(), + anyString(), + anyString()); + + assertDenied( + interceptor, + identity(WORLD_MANAGEMENT_URI), + new Metadata(), + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + identity(ENTITY_MANAGEMENT_URI), + new Metadata(), + RESOLVE_LAUNCH_DESCRIPTOR_METHOD, + ResolveLaunchDescriptorRequest.getDefaultInstance(), + ResolveLaunchDescriptorResponse.getDefaultInstance(), + resolveRequest(), + GameDesignGrpcService::resolveLaunchDescriptor, + response -> response.getError().getCode()); + assertDenied( + interceptor, + identity(ENTITY_MANAGEMENT_URI), + new Metadata(), + GET_LAUNCH_DESCRIPTOR_METHOD, + GetLaunchDescriptorRequest.getDefaultInstance(), + GetLaunchDescriptorResponse.getDefaultInstance(), + readRequest(), + GameDesignGrpcService::getLaunchDescriptor, + response -> response.getError().getCode()); + } + @Test void playerJwtCannotSubstituteForMissingGameSessionPeerIdentity() { JwtUtil jwtUtil = new JwtUtil("valid-test-player-jwt-secret-123456", 60_000L); @@ -268,6 +381,12 @@ private static void assert harness.launchDescriptorService(), harness.completeLaunchBindingService()); } + private static void assertAllowedHandlerReached(DispatchResult result) { + assertThat(result.dispatched()).isTrue(); + assertThat(result.closedStatus()).isNull(); + assertThat(result.response()).isNotNull(); + } + private static DispatchResult dispatchHandler( AuthTokenInterceptor interceptor, From 57953d2be3a6bfd00a430837e9d9b1587bddeea4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:38:08 +1300 Subject: [PATCH 05/34] Bind canonical roster selection to immutable snapshot evidence --- .../api-contracts.md | 2 + .../v1/entity_management_service.proto | 30 +++++++++-- ...icalGameplayRosterProtoDescriptorTest.java | 50 +++++++++++++++++++ 3 files changed, 79 insertions(+), 3 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 47464c1037..be9e177e62 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,6 +6,8 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status +The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes it on success, and returns `FAILED_PRECONDITION` if it is stale or the selected actor is absent from it. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. + The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. The live `CharacterController`, `InventoryController`, `EquipmentController`, and `FriendController` REST handlers are also legacy direct adapters. They remain runtime-reachable behind baseline bearer authentication and their implemented tenant-access checks. diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 3996021eff..558083936b 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -37,10 +37,21 @@ service EntityManagementService { } // Canonical gameplay roster discovery is a separate non-admitting boundary. This wire contract -// does not authorize the legacy numeric ListCharactersByAccount RPC for canonical gameplay. +// does not authorize the legacy numeric ListCharactersByAccount RPC for canonical gameplay. A +// valid ListPreseededRoster response may contain zero actors; that is a successful lookup. These +// RPCs use canonical non-OK gRPC statuses rather than in-response errors: malformed requests are +// INVALID_ARGUMENT, stale snapshots or selections not present in the bound snapshot are +// FAILED_PRECONDITION, unauthorized callers are UNAUTHENTICATED or PERMISSION_DENIED as +// applicable, and unavailable dependencies are UNAVAILABLE. No partial success is returned. service CanonicalGameplayRosterService { + // Returns the persisted preseeded roster for the exact expected target. A successful response + // includes its immutable snapshot UUID and digest, including when the roster is empty. rpc ListPreseededRoster(CanonicalGameplayRosterRequest) returns (CanonicalGameplayRosterResponse); + // Reads the selected assignment only if the supplied snapshot UUID and digest still identify + // the roster from which selected_character_uuid was chosen. The response echoes that exact + // snapshot reference. A changed snapshot or selection absent from it fails with + // FAILED_PRECONDITION. rpc ReadSelectedPreseededAssignment(CanonicalGameplayRosterSelectedAssignmentRequest) returns (CanonicalGameplayRosterSelectedAssignmentResponse); } @@ -85,7 +96,14 @@ message CanonicalGameplayRosterResponse { string snapshot_uuid = 3; string snapshot_digest = 4; repeated CanonicalGameplayRosterActor actors = 5; - shared.v1.ErrorDetail error = 6; + reserved 6; + reserved "error"; +} + +// Immutable identity and content digest of one exact roster snapshot. +message CanonicalGameplayRosterSnapshotReference { + string snapshot_uuid = 1; + string snapshot_digest = 2; } message CanonicalGameplayRosterActor { @@ -99,6 +117,9 @@ message CanonicalGameplayRosterSelectedAssignmentRequest { string canonical_account_uuid = 2; string selected_character_uuid = 3; CanonicalGameplayRosterTarget expected_target = 4; + // Exact snapshot_uuid and snapshot_digest returned by ListPreseededRoster. Retries must reuse + // these values and may not silently select against a changed roster. + CanonicalGameplayRosterSnapshotReference expected_snapshot = 5; } message CanonicalGameplayRosterSelectedAssignmentResponse { @@ -108,7 +129,10 @@ message CanonicalGameplayRosterSelectedAssignmentResponse { CanonicalGameplayRosterTarget target = 4; string assignment_uuid = 5; string intent_digest = 6; - shared.v1.ErrorDetail error = 7; + reserved 7; + reserved "error"; + // Exact snapshot reference supplied by the caller and validated by this operation. + CanonicalGameplayRosterSnapshotReference snapshot = 8; } enum CanonicalGameplayRosterActorKind { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java new file mode 100644 index 0000000000..1bb8daa592 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.common.entity; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayRosterProtoDescriptorTest { + @Test + void selectedAssignmentRoundTripsTheExactTypedSnapshotReference() { + FieldDescriptor expectedSnapshot = + CanonicalGameplayRosterSelectedAssignmentRequest.getDescriptor().findFieldByNumber(5); + FieldDescriptor snapshot = + CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor().findFieldByNumber(8); + + assertThat(expectedSnapshot.getName()).isEqualTo("expected_snapshot"); + assertThat(expectedSnapshot.getMessageType()) + .isEqualTo(CanonicalGameplayRosterSnapshotReference.getDescriptor()); + assertThat(snapshot.getName()).isEqualTo("snapshot"); + assertThat(snapshot.getMessageType()) + .isEqualTo(CanonicalGameplayRosterSnapshotReference.getDescriptor()); + + Descriptor snapshotDescriptor = CanonicalGameplayRosterSnapshotReference.getDescriptor(); + assertThat(snapshotDescriptor.findFieldByNumber(1).getName()).isEqualTo("snapshot_uuid"); + assertThat(snapshotDescriptor.findFieldByNumber(2).getName()).isEqualTo("snapshot_digest"); + } + + @Test + void canonicalRosterResponsesHaveNoInResponseErrorAndReserveItsSlot() { + assertErrorSlotReserved(CanonicalGameplayRosterResponse.getDescriptor(), 6); + assertErrorSlotReserved(CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor(), 7); + assertThat(CanonicalGameplayRosterResponse.getDescriptor().findFieldByNumber(6)).isNull(); + assertThat( + CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor() + .findFieldByNumber(8) + .getName()) + .isEqualTo("snapshot"); + } + + private static void assertErrorSlotReserved(Descriptor descriptor, int fieldNumber) { + assertThat(descriptor.toProto().getReservedRangeList()) + .anySatisfy(range -> assertThat(range.getStart()).isEqualTo(fieldNumber)); + assertThat(descriptor.toProto().getReservedNameList()).contains("error"); + } +} From b9be3928dfcc74b52b47da284ac77bab85bb90a0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:51:50 +1300 Subject: [PATCH 06/34] Bind preseeded roster reads to trusted player context and policy --- .../api-contracts.md | 5 +-- .../game-session-service/api-contracts.md | 2 ++ .../system-architecture-transactions.md | 13 +++---- .../v1/entity_management_service.proto | 34 +++++++++++++------ ...icalGameplayRosterProtoDescriptorTest.java | 15 ++++++++ 5 files changed, 51 insertions(+), 18 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index be9e177e62..d3393450d9 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,7 +6,7 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes it on success, and returns `FAILED_PRECONDITION` if it is stale or the selected actor is absent from it. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. +The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes it on success, and returns `FAILED_PRECONDITION` if it is stale or the selected actor is absent from it. Both require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. @@ -41,10 +41,11 @@ curl http://localhost:8080/ping ## gRPC - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. +- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – separate target wire contract for the `PRESEEDED_ONLY` pre-admission roster branch. Both carry `shared.v1.PlayerExecutionContext`; the first binds the authenticated account/session/request and prospective tenant/realm/namespace/scope/instance target, while the second additionally binds `context.character_id` to the selected UUID and the exact roster snapshot. The exact same-namespace Game Session workload mTLS identity is allowlisted. These reads are not actor admission or a session-binding shortcut, and their proto has no handler or activation yet. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. The current request path and enforcement do not yet prove this complete target boundary, so it remains an implementation/proof gap rather than a claim about live enforcement. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. - `QueryInventory(QueryInventoryRequest) returns (QueryInventoryResponse)` – the current response is an unpaged repeated `InventoryItem items[]` projection. The live handler emits `item_id`, `item_name`, `item_description`, and `quantity`, and conditionally emits `container_instance_id`, `item_instance_id`, and `visible_ref` when those values are present. This projection does not establish complete instance-aware identity or stack/concurrency safety: rich pagination, complete holder-local stack uniqueness, find-then-create concurrency, and explicit-family duplicate handling remain target/proof gaps documented in [Runtime and Data](./runtime-and-data.md#implementation-status). -- `ListCharactersByAccount` (target-state policy/descriptor/template/namespace fields) – returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates the account-to-character association before returning any roster or visibility result; an account identifier is ownership evidence, not controller identity. The target response includes exactly one published v1 entry policy (`PLAYER_CREATED`, `PRESEEDED_ONLY`, or `AUTO_PROVISIONED`) plus only its policy-applicable versioned identity: a descriptor identity/version for `PLAYER_CREATED`, a template identity/version for `AUTO_PROVISIONED`, and neither descriptor nor template fields for `PRESEEDED_ONLY`; it echoes the resolved namespace/scope. It also returns one immutable roster snapshot identity and digest for the exact target, policy/version, and ordered roster; an exact unchanged snapshot reuses both values, while a roster or policy/version change advances the identity or digest. Callers bind that snapshot for selection and retry and reject a changed snapshot rather than silently selecting a different actor. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results are explicit: policy determines the zero-result next action, one may be selected automatically, and many require explicit selection. A roster is discovery evidence, not admission authority. The current proto surface has none of the target policy, descriptor/template, namespace, or roster-snapshot fields and does not prove this boundary. +- `ListCharactersByAccount` (broader target-state policy/descriptor/template/namespace behavior) – the eventual policy-aware roster contract returns only persisted actors valid for the trusted account selector and resolved `{tenantId, playableStateNamespaceId, playableStateScope}` target. Entity validates account-to-character ownership; account identity is ownership evidence, not controller identity. The target response includes the exact published v1 entry policy and only its applicable versioned identity: descriptor/version for `PLAYER_CREATED`, template/version for `AUTO_PROVISIONED`, neither for `PRESEEDED_ONLY`; it echoes namespace/scope and returns an immutable roster snapshot identity/digest for the exact target, policy/version, and ordered roster. `gameInstanceId` is a fresh active-runtime fence, not durable lookup identity. Zero, one, and many results follow policy-specific next actions; a roster is discovery evidence, not admission authority. The separate `CanonicalGameplayRosterService` wire above currently specifies only the `PRESEEDED_ONLY` branch. `PLAYER_CREATED` and `AUTO_PROVISIONED` remain later-owned target branches, and the legacy numeric `ListCharactersByAccount` method is not trusted for canonical gameplay. Current handlers do not prove these target contracts. - `AutoProvisionCharacter` (target-state) – after explicit entry, idempotently provisions at most one actor from the published realm template using the trusted `{tenantId, accountId, playableStateNamespaceId}` as the at-most-one uniqueness tuple. The request carries explicit `entryPolicy=AUTO_PROVISIONED`, the unchanged discovered-entry object and `discoveredEntryDigest`, the applicable exact template identity/version, a caller-stable `autoProvisionRequestId` that is stable and unique only within that exact `{tenantId, accountId, playableStateNamespaceId}` target scope, canonical `mutationDigest`, and an explicit absent-creation-input marker following ADR 0140's fixed-position presence encoding. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks it against the canonical snapshot and applicable template identity/version. Entity recomputes the mutation digest over the immutable trusted target, `entryPolicy`, exact template identity/version, and absent-input marker, and durably guards the operation by `{tenantId, accountId, playableStateNamespaceId, autoProvisionRequestId}` separately from the at-most-one-actor constraint; these operation-guard and actor-uniqueness constraints remain distinct. An actor-uniqueness race between distinct request IDs has one winner; each loser transactionally rereads and validates the exact target, policy, template provenance, and digest, durably stores its own guard result, and returns/replays the same actor only on exact match. A loser with mismatched provenance or digest stores a terminal `IDEMPOTENCY_CONFLICT` outcome and never replaces or allocates another actor. `playableStateScope` is only server-validated routing/authorization-fence evidence and is not an alternate key; `gameInstanceId` is the replaceable active-runtime fence. The same target-scoped guard with the same digest exact-replays the persisted actor, including under concurrent delivery; the same scoped guard with a changed digest-bound intent returns `IDEMPOTENCY_CONFLICT` before allocation. A different tenant, account, or namespace selects a different target-scoped guard and must not conflict solely because the text request ID is reused; no global request registry is implied. The current surface and proof are not implemented. - `QueryActorState` – returns gameplay-attested actor resources and active conditions for a scoped character. - `ApplyActorCondition` – **target-state request:** applies a gameplay-attested active condition or transient action state for a scoped character. The canonical target request carries a dedicated operation-unique `effectId`, separate source provenance, optional expiry, and the exact release-pinned typed effect declaration/reference and digest resolved by the server-side gameplay path; caller-defined effect JSON is not mutation authority. The target mutation persists the frozen definition/release and its server-resolved typed applied-effect snapshot and digest, never a caller-supplied payload. The current request still accepts transitional `effectPayloadJson`, so this typed-plan/no-caller-payload boundary is not live enforcement yet. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 44ed3630df..c0b07e0052 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -30,6 +30,8 @@ For script transitions, the live boundary includes the exact `scriptPinEpoch` an Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. +The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This wire currently has no handler or activation, and its policy does not authorize other roster branches or actor admission. + For target gameplay forwarding, `PlayerExecutionContext` carries the server-resolved `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId}` binding and, for region-scoped work, its `{regionId, regionEpoch}` fence as one context. Game Session forwards the namespace and scope unchanged and validates exact context/request equality on every downstream response or mutation result; it never accepts a caller-selected namespace or substitutes a current one after admission. The current context/forwarding wire is narrower in places and does not yet carry or prove this complete namespace-plus-fence tuple, so that path remains an implementation/proof gap and must fail closed on missing authority. It also communicates game lifecycle changes to other microservices over gRPC so they can react to game instances starting, stopping, or changing runtime configuration. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index 58ec423939..dcc649c22c 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -250,9 +250,9 @@ These workflows: - Modify **persistent storage (PostgreSQL)** across multiple services - Require compensation and persisted step status, but not durable workflow execution -For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses Entity's `ListCharactersByAccount` against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. +For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses its later-owned policy-aware Entity roster contract against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. The separate `CanonicalGameplayRosterService.ListPreseededRoster` wire implements only the pre-admission `PRESEEDED_ONLY` lookup; `PLAYER_CREATED` remains a later-owned target branch, and neither it nor `AUTO_PROVISIONED` may fall back to the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `ListCharactersByAccount` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; a retry must validate that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. +`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `CanonicalGameplayRosterService.ListPreseededRoster` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; a retry calls `ReadSelectedPreseededAssignment` with that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. The separate wire accepts only `PRESEEDED_ONLY`; other policy values fail with `FAILED_PRECONDITION`. `PLAYER_CREATED` remains a later-owned policy-aware roster branch, and `AUTO_PROVISIONED` remains its owner-defined idempotent existing-actor operation; neither branch may use the legacy numeric `ListCharactersByAccount` RPC as canonical gameplay authority. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. If a workflow needs restart-safe continuation, durable waits/timers, or operator-visible in-flight state that survives one service lifetime, it should use the shared Temporal substrate described in [Temporal Control-Plane Workflows](./system-architecture-temporal-workflows.md) instead of extending `SagaRunner` toward durable workflow behavior. @@ -359,7 +359,7 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): boundCreateCharacterRequestId, boundMutationDigest, boundCanonicalCreationInput) # replay before fresh-roster rejection return stored-or-replayed result - rosterSnapshot = Entity.ListCharactersByAccount(discoveredEntry, discoveredEntryDigest) + rosterSnapshot = Entity.ListCharactersByAccount(discoveredEntry, discoveredEntryDigest) # later-owned target contract; legacy numeric RPC is not canonical authority if retrying roster-selection step: require rosterSnapshot.identity == boundRosterSnapshot.identity require rosterSnapshot.digest == boundRosterSnapshot.digest @@ -396,11 +396,12 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): Entity.AutoProvisionCharacter(discoveredEntry, discoveredEntryDigest, autoProvisionRequestId, mutationDigest, canonicalCreationInput) PRESEEDED_ONLY: require creation input is absent - rosterSnapshot = Entity.ListCharactersByAccount(discoveredEntry, discoveredEntryDigest) if retrying selection step: - require rosterSnapshot.identity == boundRosterSnapshot.identity - require rosterSnapshot.digest == boundRosterSnapshot.digest + assignment = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, boundRosterSnapshot.reference, selectedCharacterId) + require assignment.snapshot == boundRosterSnapshot.reference + rosterSnapshot = boundRosterSnapshot else: + rosterSnapshot = Entity.CanonicalGameplayRosterService.ListPreseededRoster(discoveredEntry, discoveredEntryDigest) bind rosterSnapshot.identity and rosterSnapshot.digest to sagaStep roster = rosterSnapshot.roster if roster is zero: diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 558083936b..66971a72b0 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -4,6 +4,7 @@ package entity_management.v1; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; +import "shared/v1/player_execution_context.proto"; option java_package = "net.firedevops.firemud.entitymanagement.v1"; option java_multiple_files = true; @@ -36,22 +37,33 @@ service EntityManagementService { returns (ValidateEntityUpgradeMappingsResponse); } -// Canonical gameplay roster discovery is a separate non-admitting boundary. This wire contract -// does not authorize the legacy numeric ListCharactersByAccount RPC for canonical gameplay. A -// valid ListPreseededRoster response may contain zero actors; that is a successful lookup. These -// RPCs use canonical non-OK gRPC statuses rather than in-response errors: malformed requests are -// INVALID_ARGUMENT, stale snapshots or selections not present in the bound snapshot are -// FAILED_PRECONDITION, unauthorized callers are UNAUTHENTICATED or PERMISSION_DENIED as -// applicable, and unavailable dependencies are UNAVAILABLE. No partial success is returned. +// Canonical gameplay roster discovery is a pre-admission, non-admitting boundary. Both methods +// are restricted to PRESEEDED_ONLY; other policy values are non-authorizing and fail with +// FAILED_PRECONDITION. This wire contract does not authorize the legacy numeric +// ListCharactersByAccount RPC for canonical gameplay. A valid ListPreseededRoster response may +// contain zero actors; that is a successful lookup. These RPCs use canonical non-OK gRPC statuses +// rather than in-response errors: malformed requests are INVALID_ARGUMENT, stale snapshots or +// selections not present in the bound snapshot are FAILED_PRECONDITION, unauthorized callers are +// UNAUTHENTICATED or PERMISSION_DENIED as applicable, and unavailable dependencies are +// UNAVAILABLE. No partial success is returned. service CanonicalGameplayRosterService { - // Returns the persisted preseeded roster for the exact expected target. A successful response - // includes its immutable snapshot UUID and digest, including when the roster is empty. + // Returns the persisted preseeded roster for the exact expected target. The server requires an + // authenticated, server-derived PlayerExecutionContext and exact same-namespace Game Session + // mTLS caller allowlisting. Context account_id equals canonical_account_uuid; request_id equals + // request_uuid; tenant_id, realm_id, playable_state_namespace_id, playable_state_scope, and + // game_instance_id equal the corresponding expected_target values; session_id identifies the + // authenticated session. No character_id is selected yet. The target policy must be + // PRESEEDED_ONLY. These equality checks do not require an additional Account lookup. A + // successful response includes its immutable snapshot UUID and digest, including when the + // roster is empty. rpc ListPreseededRoster(CanonicalGameplayRosterRequest) returns (CanonicalGameplayRosterResponse); // Reads the selected assignment only if the supplied snapshot UUID and digest still identify // the roster from which selected_character_uuid was chosen. The response echoes that exact // snapshot reference. A changed snapshot or selection absent from it fails with - // FAILED_PRECONDITION. + // FAILED_PRECONDITION. It has the same authenticated context and exact target equality + // requirements as ListPreseededRoster, and context.character_id must equal + // selected_character_uuid. The target policy must be PRESEEDED_ONLY. rpc ReadSelectedPreseededAssignment(CanonicalGameplayRosterSelectedAssignmentRequest) returns (CanonicalGameplayRosterSelectedAssignmentResponse); } @@ -60,6 +72,7 @@ message CanonicalGameplayRosterRequest { string request_uuid = 1; string canonical_account_uuid = 2; CanonicalGameplayRosterTarget expected_target = 3; + shared.v1.PlayerExecutionContext player_execution_context = 4; } message CanonicalGameplayRosterTarget { @@ -120,6 +133,7 @@ message CanonicalGameplayRosterSelectedAssignmentRequest { // Exact snapshot_uuid and snapshot_digest returned by ListPreseededRoster. Retries must reuse // these values and may not silently select against a changed roster. CanonicalGameplayRosterSnapshotReference expected_snapshot = 5; + shared.v1.PlayerExecutionContext player_execution_context = 6; } message CanonicalGameplayRosterSelectedAssignmentResponse { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java index 1bb8daa592..6fde8fe528 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java @@ -4,13 +4,22 @@ import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; class CanonicalGameplayRosterProtoDescriptorTest { + @Test + void canonicalRosterRequestsCarryTheTypedPlayerExecutionContext() { + assertPlayerExecutionContextField(CanonicalGameplayRosterRequest.getDescriptor(), 4); + assertPlayerExecutionContextField( + CanonicalGameplayRosterSelectedAssignmentRequest.getDescriptor(), 6); + } + @Test void selectedAssignmentRoundTripsTheExactTypedSnapshotReference() { FieldDescriptor expectedSnapshot = @@ -47,4 +56,10 @@ private static void assertErrorSlotReserved(Descriptor descriptor, int fieldNumb .anySatisfy(range -> assertThat(range.getStart()).isEqualTo(fieldNumber)); assertThat(descriptor.toProto().getReservedNameList()).contains("error"); } + + private static void assertPlayerExecutionContextField(Descriptor descriptor, int fieldNumber) { + FieldDescriptor context = descriptor.findFieldByNumber(fieldNumber); + assertThat(context.getName()).isEqualTo("player_execution_context"); + assertThat(context.getMessageType()).isEqualTo(PlayerExecutionContext.getDescriptor()); + } } From d722db67a8d9ac8d4744942d5d4187a3d7a7deb1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:06:34 +1300 Subject: [PATCH 07/34] Close canonical launch wire and retained proof compilation --- .../game-design/v1/game_design_service.proto | 1 + ...redWorldLaunchDescriptorGrpcCodecTest.java | 18 ++ ...edWorldReleaseAttestationSelectorTest.java | 290 ++++++++++++++++++ .../service/impl/GameDesignGrpcService.java | 7 +- .../CanonicalLaunchGrpcAuthWiringTest.java | 46 +-- .../TenantIdentityGrpcAuthWiringTest.java | 3 +- .../impl/GameDesignGrpcServiceAuthTest.java | 9 +- .../GameDesignGrpcServiceHelpTopicTest.java | 3 +- ...esignGrpcServiceSettingsAuthorityTest.java | 3 +- .../impl/GameDesignGrpcServiceTest.java | 33 +- .../impl/LaunchDescriptorServiceImplTest.java | 1 + .../service/impl/GameInstanceServiceImpl.java | 2 +- ...ayRosterOwnerReadInterceptorChainTest.java | 6 - ...signmentOwnerReadInterceptorChainTest.java | 6 - .../impl/GameInstanceServiceImplTest.java | 48 ++- 15 files changed, 396 insertions(+), 80 deletions(-) create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java diff --git a/protos/game-design/v1/game_design_service.proto b/protos/game-design/v1/game_design_service.proto index f475f8a2c7..94127900ec 100644 --- a/protos/game-design/v1/game_design_service.proto +++ b/protos/game-design/v1/game_design_service.proto @@ -650,6 +650,7 @@ message ParticipantDigest { string applied_commit_id = 3; string content_digest = 4; int32 digest_schema_version = 5; + optional string ability_schema_digest = 6; } enum VersionLifecycleState { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index fdbd2ad25e..6d114a5794 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -448,6 +448,24 @@ void completeReadRejectsMissingConflictingAndUnknownEvidenceAtEveryMessageLevel( .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Release-attestation evidence is invalid") .hasRootCauseMessage("Participant digest schema is unsupported for its owner"); + assertThatThrownBy( + () -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setReleaseAttestation( + good.getReleaseAttestation().toBuilder() + .setParticipantDigests( + 2, + good + .getReleaseAttestation() + .getParticipantDigests(2) + .toBuilder() + .setAbilitySchemaDigest("sha256:" + "e".repeat(64)))) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Complete launch binding evidence is invalid") + .hasRootCauseMessage("Evidence digest does not match the exact release attestation"); } private static void assertFlatDuplicateRejected(LaunchDescriptor descriptor) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java new file mode 100644 index 0000000000..f4fde9e072 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -0,0 +1,290 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AuthoredWorldReleaseAttestationSelectorTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void v2BindsCompleteOriginalEvidenceInItsOwnDomainAndSurvivesStoredReadback() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var stored = JSON.writeValueAsString(release); + var readback = JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class); + + assertThat(release.schemaVersion()).isEqualTo(2); + assertThat(readback).isEqualTo(release); + readback.requireValid(descriptor); + assertThat( + new String( + AuthoredWorldReleaseAttestationEvidence.evidencePreimage(release), + StandardCharsets.UTF_8)) + .startsWith("49:game-design-authored-world-release-attestation/v2") + .contains("worldStartLocationEvidence.canonicalBytesBase64") + .endsWith(Base64.getEncoder().encodeToString(selector.canonicalBytes())); + assertThat(readback.worldStartLocationEvidence().selectorReceiptBytes()) + .containsExactly(selector.selectorReceiptBytes()); + assertThat(readback.worldStartLocationEvidence().originalAccountBindingBytes()) + .containsExactly(selector.originalAccountBindingBytes()); + assertThat(readback.worldStartLocationEvidence().appliedResultBytes()) + .containsExactly(selector.appliedResultBytes()); + } + + @Test + void v1BytesAndDigestRemainUnchangedAndCannotBePromotedBySupplyingASelector() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var current = release(descriptor, selector); + var old = + AuthoredWorldReleaseAttestationEvidence.create( + current.targetNamespace(), + current.descriptorResultDigest(), + current.canonicalTenantId(), + current.canonicalVersionId(), + current.worldSlug(), + current.authoredWorldSourceOperationId(), + current.authoredWorldSourceEvidenceDigest(), + current.launchDescriptorId(), + current.publishedReleaseBundleRef(), + current.versionStateEpoch(), + current.publishWorkflowId(), + current.commitId(), + current.participantDigests(), + current.manifestHash(), + current.manifestSchemaVersion(), + current.requiredManifestAssetKeys(), + current.artifactDigests(), + current.commandDefinitions(), + current.generationConfigRevision()); + String stored = JSON.writeValueAsString(old); + assertThat(stored).doesNotContain("worldStartLocationEvidence"); + assertThat( + JSON.writeValueAsString( + JSON.readValue(stored, AuthoredWorldReleaseAttestationEvidence.class))) + .isEqualTo(stored); + assertThat( + AuthoredWorldLaunchDescriptorGrpcCodec.toReleaseAttestation(old) + .hasWorldStartLocationEvidence()) + .isFalse(); + assertThat(old.evidenceDigest()).isNotEqualTo(current.evidenceDigest()); + assertThatThrownBy(() -> copy(old, 1, selector)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 2, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(current, 3, selector)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> copy(old, 2, selector).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void selectorSubstitutionAtAnOtherwiseValidCheckpointChangesTheDigest() throws Exception { + var selector = selectorEvidence(); + var descriptor = descriptor(selector); + var release = release(descriptor, selector); + var request = selector.request(); + var other = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + UUID.randomUUID(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + request.appliedCommitId(), + request.contentDigest(), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThat(release(descriptor, other).evidenceDigest()).isNotEqualTo(release.evidenceDigest()); + assertThatThrownBy(() -> copy(release, 2, other).requireValid()) + .isInstanceOf(IllegalArgumentException.class); + var wrongCheckpoint = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + request.intakeRequestId(), + request.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + "other-workflow", + request.appliedCommitId(), + "c".repeat(64), + request.digestSchemaVersion(), + request.worldAffectedTuples()), + selector.selectorReceiptBytes(), + selector.originalAccountBindingBytes(), + selector.appliedResultBytes()); + assertThatThrownBy(() -> copy(release, 2, wrongCheckpoint)) + .isInstanceOf(IllegalArgumentException.class); + } + + static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { + var terminal = + WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); + var applied = + WorldDraftTerminalReadGrpcCodecTest.committedFreshGraphReadbackForStartLocationEvidenceTest( + terminal); + var account = terminal.accountBinding(); + var draft = + DraftCommitBinding.fromStored( + new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); + var tuples = + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var request = + new WorldPublishedStartLocationEvidence.Request( + "test", + account.tenantId(), + account.versionId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + "publication-request", + "a".repeat(64), + 5L, + "publish-workflow", + account.commitId().toString(), + "b".repeat(64), + 3, + tuples); + var result = JSON.readTree(applied.result()); + return new WorldPublishedStartLocationEvidence( + request, + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + applied.fullBinding(), + applied.result()); + } + + static AuthoredWorldLaunchDescriptorEvidence descriptor( + WorldPublishedStartLocationEvidence selector) { + var request = + new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + "launch-control-request", + selector.request().canonicalTenantId(), + "synthetic-world", + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + "sha256:" + "b".repeat(64), + 19L, + false, + null, + false, + null, + false, + null, + false, + null); + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "descriptor", + 42L, + false, + null, + "{}", + "generation", + 9L, + 7L, + "release", + false, + null); + } + + static AuthoredWorldReleaseAttestationEvidence release( + AuthoredWorldLaunchDescriptorEvidence descriptor, + WorldPublishedStartLocationEvidence selector) { + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .toList(); + return AuthoredWorldReleaseAttestationEvidence.create( + descriptor.targetNamespace(), + descriptor.resultDigest(), + descriptor.canonicalTenantId(), + selector.request().canonicalVersionId(), + descriptor.worldSlug(), + descriptor.authoredWorldSourceOperationId(), + descriptor.authoredWorldSourceEvidenceDigest(), + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + participants, + "sha256:" + "d".repeat(64), + 1, + List.of(), + List.of(), + List.of("LOOK"), + descriptor.generationConfigRevision(), + selector); + } + + private static AuthoredWorldReleaseAttestationEvidence copy( + AuthoredWorldReleaseAttestationEvidence old, + int schema, + WorldPublishedStartLocationEvidence selector) { + return new AuthoredWorldReleaseAttestationEvidence( + schema, + old.targetNamespace(), + old.descriptorResultDigest(), + old.canonicalTenantId(), + old.canonicalVersionId(), + old.worldSlug(), + old.authoredWorldSourceOperationId(), + old.authoredWorldSourceEvidenceDigest(), + old.launchDescriptorId(), + old.publishedReleaseBundleRef(), + old.versionStateEpoch(), + old.publishWorkflowId(), + old.commitId(), + old.participantDigests(), + old.manifestHash(), + old.manifestSchemaVersion(), + old.requiredManifestAssetKeys(), + old.artifactDigests(), + old.commandDefinitions(), + old.generationConfigRevision(), + old.evidenceDigest(), + selector); + } +} diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 2784f13eaa..2b281d9a74 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -26,8 +26,8 @@ import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; import net.firedevops.firemud.gamedesign.dto.VersionDto; -import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; @@ -2154,8 +2154,7 @@ private String launchDescriptorErrorCode(String message, boolean allowSchemaUnsu || message.startsWith("LAUNCH_DESCRIPTOR_NOT_FOUND")) { return "NOT_FOUND"; } - if (message.startsWith("AUTHORED_WORLD_SOURCE_") - || message.startsWith("LAUNCH_DESCRIPTOR_")) { + if (message.startsWith("AUTHORED_WORLD_SOURCE_") || message.startsWith("LAUNCH_DESCRIPTOR_")) { return "FAILED_PRECONDITION"; } return "INVALID_ARGUMENT"; @@ -2217,7 +2216,7 @@ private net.firedevops.firemud.gamedesign.v1.LaunchDescriptor toProtoLaunchDescr } return net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId(descriptor.launchDescriptorId()) - .setCanonicalTenantId(descriptor.tenantId()) + .setCanonicalTenantId(descriptor.canonicalTenantId()) .setGameTemplateId(descriptor.gameTemplateId()) .setControlPlaneRequestId(descriptor.controlPlaneRequestId()) .setVersionId(descriptor.versionId()) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java index 0897de7a99..5697328952 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java @@ -67,8 +67,7 @@ class CanonicalLaunchGrpcAuthWiringTest { RESOLVE_LAUNCH_DESCRIPTOR_METHOD, GET_LAUNCH_DESCRIPTOR_METHOD, GET_COMPLETE_LAUNCH_BINDING_METHOD); - private static final String GAME_SESSION_URI = - "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; private static final String WORLD_MANAGEMENT_URI = "spiffe://firemud/ns/test/sa/world-management-service"; private static final String ENTITY_MANAGEMENT_URI = @@ -87,7 +86,8 @@ void sameNamespaceGameSessionPeerReachesEachRealCanonicalLaunchHandlerWithoutBea Harness harness = harness(); when(harness.launchDescriptorService().resolveLaunchDescriptor(any())) .thenThrow(new IllegalStateException("intentional owner read probe")); - when(harness.launchDescriptorService() + when(harness + .launchDescriptorService() .getLaunchDescriptor( any(UUID.class), any(UUID.class), @@ -96,7 +96,8 @@ void sameNamespaceGameSessionPeerReachesEachRealCanonicalLaunchHandlerWithoutBea anyString(), anyString())) .thenThrow(new IllegalArgumentException("intentional exact read probe")); - when(harness.completeLaunchBindingService() + when(harness + .completeLaunchBindingService() .getCompleteLaunchBinding( any(UUID.class), any(UUID.class), @@ -152,20 +153,10 @@ void sameNamespaceGameSessionPeerReachesEachRealCanonicalLaunchHandlerWithoutBea verify(harness.launchDescriptorService()).resolveLaunchDescriptor(any()); verify(harness.launchDescriptorService()) .getLaunchDescriptor( - any(UUID.class), - any(UUID.class), - anyString(), - anyString(), - anyString(), - anyString()); + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString()); verify(harness.completeLaunchBindingService()) .getCompleteLaunchBinding( - any(UUID.class), - any(UUID.class), - anyString(), - anyString(), - anyString(), - anyString()); + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString()); } @Test @@ -181,7 +172,8 @@ void workloadPeerMustMatchNamespaceAndServiceEvenWhenMethodSkipsBearerValidation void worldAndEntityPeersAreLimitedToTheirDeclaredLaunchReadHandlers() { AuthTokenInterceptor interceptor = interceptor(); Harness harness = harness(); - when(harness.launchDescriptorService() + when(harness + .launchDescriptorService() .getLaunchDescriptor( any(UUID.class), any(UUID.class), @@ -190,7 +182,8 @@ void worldAndEntityPeersAreLimitedToTheirDeclaredLaunchReadHandlers() { anyString(), anyString())) .thenThrow(new IllegalArgumentException("intentional exact read probe")); - when(harness.completeLaunchBindingService() + when(harness + .completeLaunchBindingService() .getCompleteLaunchBinding( any(UUID.class), any(UUID.class), @@ -239,20 +232,10 @@ void worldAndEntityPeersAreLimitedToTheirDeclaredLaunchReadHandlers() { assertAllowedHandlerReached(entityCompleteRead); verify(harness.launchDescriptorService()) .getLaunchDescriptor( - any(UUID.class), - any(UUID.class), - anyString(), - anyString(), - anyString(), - anyString()); + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString()); verify(harness.completeLaunchBindingService(), org.mockito.Mockito.times(2)) .getCompleteLaunchBinding( - any(UUID.class), - any(UUID.class), - anyString(), - anyString(), - anyString(), - anyString()); + any(UUID.class), any(UUID.class), anyString(), anyString(), anyString(), anyString()); assertDenied( interceptor, @@ -377,8 +360,7 @@ private static void assert assertThat(result.closedStatus()).isNull(); assertThat(result.response()).isNotNull(); assertThat(errorCode.apply(result.response())).isEqualTo("PERMISSION_DENIED"); - verifyNoInteractions( - harness.launchDescriptorService(), harness.completeLaunchBindingService()); + verifyNoInteractions(harness.launchDescriptorService(), harness.completeLaunchBindingService()); } private static void assertAllowedHandlerReached(DispatchResult result) { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index 17d1699f9d..d740b517e5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -80,8 +80,7 @@ class TenantIdentityGrpcAuthWiringTest { GameTenantCreationDigest.requestDigest("test", REQUEST_ID, SOURCE_KEY, "Fresh Realm", null); @Test - void defaultAndProductionProfilesKeepExactReadAllowlistAndRequireClientTls() - throws IOException { + void defaultAndProductionProfilesKeepExactReadAllowlistAndRequireClientTls() throws IOException { for (String file : List.of("application.yml", "application-prod.yml")) { GrpcConfiguration config = load(file); assertThat(config.publicMethods()).containsExactlyElementsOf(ALLOWLISTED_METHODS); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java index f8b554fcdb..7c489a27f9 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceAuthTest.java @@ -57,7 +57,8 @@ void adminMethodsReturnPermissionDeniedErrorDetail() { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), - Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), + Mockito.mock( + net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -173,7 +174,8 @@ void launchAttestationReadAndCanonicalResolveRequireWorkloadIdentity() { Mockito.mock(RevisionService.class), versionService, launchDescriptorService, - Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), + Mockito.mock( + net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), @@ -212,8 +214,7 @@ public void onCompleted() {} AtomicReference descriptorRef = new AtomicReference<>(); GrpcPeerIdentity peer = - GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service") - .orElseThrow(); + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/game-session-service").orElseThrow(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) .run( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java index 760db9b802..5a9b56d0ce 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceHelpTopicTest.java @@ -38,7 +38,8 @@ class GameDesignGrpcServiceHelpTopicTest { Mockito.mock(RevisionService.class), Mockito.mock(VersionService.class), Mockito.mock(LaunchDescriptorService.class), - Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), + Mockito.mock( + net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), Mockito.mock(TemplateRemapSetService.class), Mockito.mock(VersionAssetArtifactService.class), Mockito.mock(SettingsAuthorityService.class), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java index a95a14bbef..c5f15d91f8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceSettingsAuthorityTest.java @@ -59,7 +59,8 @@ void setUp() { revisionService, versionService, launchDescriptorService, - Mockito.mock(net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), + Mockito.mock( + net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService.class), templateRemapSetService, versionAssetArtifactService, settingsAuthorityService, diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 18afc2ef10..0cb2b9a9f8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import com.google.protobuf.UnknownFieldSet; import io.grpc.Context; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -10,7 +11,6 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; -import com.google.protobuf.UnknownFieldSet; import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminRoleGuard; @@ -29,8 +29,8 @@ import net.firedevops.firemud.gamedesign.model.PublishGateFailureCode; import net.firedevops.firemud.gamedesign.model.TemplateRemapSetStatus; import net.firedevops.firemud.gamedesign.model.VersionLifecycleState; -import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.CompleteLaunchBindingService; +import net.firedevops.firemud.gamedesign.service.GameAuthoredHelpTopicService; import net.firedevops.firemud.gamedesign.service.LaunchDescriptorService; import net.firedevops.firemud.gamedesign.service.PingService; import net.firedevops.firemud.gamedesign.service.PublishAttemptPendingReconciliationException; @@ -48,14 +48,14 @@ import net.firedevops.firemud.gamedesign.v1.CreateTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestRequest; import net.firedevops.firemud.gamedesign.v1.GetDesignControlPlaneDigestResponse; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; +import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedPluginVersionResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; -import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorRequest; -import net.firedevops.firemud.gamedesign.v1.GetLaunchDescriptorResponse; import net.firedevops.firemud.gamedesign.v1.GetTemplateRemapSetRequest; import net.firedevops.firemud.gamedesign.v1.GetTemplateRemapSetResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateRequest; @@ -1232,7 +1232,8 @@ void getLaunchDescriptorReturnsExactBoundReadback() { .build(); AtomicReference ref = new AtomicReference<>(); underLaunchPeer( - "world-management-service", () -> service.getLaunchDescriptor(readRequest, observerFor(ref))); + "world-management-service", + () -> service.getLaunchDescriptor(readRequest, observerFor(ref))); assertEquals(readRequestId.toString(), ref.get().getRequestId()); assertEquals("ld-1", ref.get().getLaunchDescriptor().getLaunchDescriptorId()); @@ -1328,8 +1329,7 @@ void completeLaunchBindingRejectsUnknownFieldsBeforeOwnerRead() { AtomicReference ref = new AtomicReference<>(); underLaunchPeer( - "game-session-service", - () -> service.getCompleteLaunchBinding(request, observerFor(ref))); + "game-session-service", () -> service.getCompleteLaunchBinding(request, observerFor(ref))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); Mockito.verifyNoInteractions(completeLaunchBindingService); @@ -1363,10 +1363,10 @@ void completeLaunchBindingPreservesTypedOwnerDenial() { AtomicReference ref = new AtomicReference<>(); underLaunchPeer( - "game-session-service", - () -> service.getCompleteLaunchBinding(request, observerFor(ref))); + "game-session-service", () -> service.getCompleteLaunchBinding(request, observerFor(ref))); - assertEquals("COMPLETE_LAUNCH_BINDING_RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); + assertEquals( + "COMPLETE_LAUNCH_BINDING_RELEASE_BUNDLE_NOT_FOUND", ref.get().getError().getCode()); Mockito.verify(completeLaunchBindingService) .getCompleteLaunchBinding( readRequestId, @@ -1379,7 +1379,8 @@ void completeLaunchBindingPreservesTypedOwnerDenial() { @Test void resolveLaunchDescriptorRejectsNonCanonicalTenantUuidBeforeOwnerRead() { - var request = resolveRequest("cp-invalid-uuid").toBuilder().setCanonicalTenantId("not-a-uuid").build(); + var request = + resolveRequest("cp-invalid-uuid").toBuilder().setCanonicalTenantId("not-a-uuid").build(); AtomicReference ref = new AtomicReference<>(); underLaunchPeer( "game-session-service", () -> service.resolveLaunchDescriptor(request, observerFor(ref))); @@ -1703,13 +1704,6 @@ private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } - private void underLaunchPeer(String serviceName, Runnable operation) { - ReflectionTestUtils.setField(service, "workloadNamespace", "test"); - GrpcPeerIdentity peer = - GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/" + serviceName).orElseThrow(); - Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(operation); - } - private AuthoredWorldLaunchDescriptorEvidence.Request launchRequest( String controlPlaneRequestId) { return new AuthoredWorldLaunchDescriptorEvidence.Request( @@ -1747,8 +1741,7 @@ private AuthoredWorldLaunchDescriptorEvidence launchEvidence( null); } - private ResolvedLaunchDescriptorDto launchDto( - AuthoredWorldLaunchDescriptorEvidence evidence) { + private ResolvedLaunchDescriptorDto launchDto(AuthoredWorldLaunchDescriptorEvidence evidence) { return new ResolvedLaunchDescriptorDto( evidence.launchDescriptorId(), evidence.canonicalTenantId().toString(), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index e1cddd1826..0be5f1a490 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -37,6 +37,7 @@ import net.firedevops.firemud.gamedesign.repository.VersionRepository; import net.firedevops.firemud.gamedesign.service.PublishedReleaseBundleService; import net.firedevops.firemud.gamedesign.service.TemplateRemapSetService; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; 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 b090816e15..e5729df82e 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 @@ -1272,7 +1272,7 @@ private ResolvedLaunchDescriptor preflightLaunch(StartSessionRequest request) { } return new ResolvedLaunchDescriptor( descriptor.getLaunchDescriptorId(), - requirePositiveExternalId(descriptor.getTenantId(), "tenantId"), + requirePositiveExternalId(descriptor.getCanonicalTenantId(), "tenantId"), descriptor.getGameTemplateId(), descriptor.getControlPlaneRequestId(), descriptor.getVersionId(), 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 d7752e1908..ed1b644f1e 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,12 +118,6 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { assertThat(configured) .containsExactly( "game_session.v1.GameSessionService/Ping", - "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", - "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", - "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof", METHOD, "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead") .doesNotContain("game_session.v1.*"); 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 0628659fb2..8ae7a022bc 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,12 +124,6 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { assertThat(configured) .containsExactly( "game_session.v1.GameSessionService/Ping", - "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof", - "game_session.v1.GameSessionControlPlaneService/GetPublishedRealmAdmissionOwnerRead", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameplayAdmissionDecision", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalGameInstanceLaunchAssociation", - "game_session.v1.GameSessionControlPlaneService/GetRuntimeRegionInitializationCheckpoint", - "game_session.v1.GameSessionControlPlaneService/GetCanonicalInitialAdmissionOwnerProof", "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", METHOD) .doesNotContain("game_session.v1.*"); 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 6b3aab6ed1..db61158b6c 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 @@ -148,6 +148,47 @@ void legacyNumericLaunchFailsClosedBeforeMutation() { assertNumericLaunchDeniedWithoutMutation(request); } + @Test + void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-canonical-tenant", 42L); + doReturn( + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId("ld-cp-canonical-tenant") + .setCanonicalTenantId("123e4567-e89b-12d3-a456-426614174000") + .setGameTemplateId(request.gameTemplateId()) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setVersionId(11L) + .setScriptPatchVersion("") + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setVersionStateEpoch(77L) + .setReleaseBundleId(77L) + .setPublishedReleaseBundleRef("prb:1:11:77") + .build()) + .build()) + .when(gameDesignClient) + .resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + + Map before = new HashMap<>(); + store.forEach((id, instance) -> before.put(id, copyOf(instance))); + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.startSession(request)); + + assertEquals("tenantId must be numeric", error.getMessage()); + org.assertj.core.api.Assertions.assertThat(store).usingRecursiveComparison().isEqualTo(before); + verify(gameDesignClient) + .resolveLaunchDescriptor( + request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); + verify(gameDesignClient).getPublishedReleaseBundle(request.tenantId(), 11L); + verify(gameDesignClient).getVersionAssetArtifactState(request.tenantId(), 11L); + verify(gameDesignClient).getVersionState(request.tenantId(), 11L); + verifyNoMoreInteractions(gameDesignClient); + verifyNoInteractions(repository, worldManagementClient, stateService); + } + @Test void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-1", 42L); @@ -392,7 +433,7 @@ void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-pinned") - .setTenantId("1") + .setCanonicalTenantId("1") .setGameTemplateId(3L) .setControlPlaneRequestId("cp-pinned") .setVersionId(11L) @@ -1430,7 +1471,8 @@ private void configureLaunchPreflight() { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-" + invocation.getArgument(2, String.class)) - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setCanonicalTenantId( + Long.toString(invocation.getArgument(0, Long.class))) .setGameTemplateId(invocation.getArgument(1, Long.class)) .setControlPlaneRequestId(invocation.getArgument(2, String.class)) .setVersionId(11L) @@ -1541,7 +1583,7 @@ void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparatio .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-cp-launch-tenant") - .setTenantId("0") + .setCanonicalTenantId("0") .setGameTemplateId(3L) .setControlPlaneRequestId("cp-launch-tenant") .setVersionId(11L) From a6efc8fe192de77192f062c454697234ebd5e101 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:10:02 +1300 Subject: [PATCH 08/34] Keep roster selection readback non-authorizing --- .../api-contracts.md | 4 ++-- .../game-session-service/api-contracts.md | 2 +- .../system-architecture-transactions.md | 11 ++++++++--- .../v1/entity_management_service.proto | 19 +++++++++++-------- ...icalGameplayRosterProtoDescriptorTest.java | 18 ++++++++++++++++++ 5 files changed, 40 insertions(+), 14 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index d3393450d9..dea1eea61b 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,7 +6,7 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes it on success, and returns `FAILED_PRECONDITION` if it is stale or the selected actor is absent from it. Both require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. +The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot discovery bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. Its response does not mint an assignment receipt or prove admission; any later assignment/admission write and authoritative readback remain with the owning downstream operation. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. @@ -41,7 +41,7 @@ curl http://localhost:8080/ping ## gRPC - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. -- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – separate target wire contract for the `PRESEEDED_ONLY` pre-admission roster branch. Both carry `shared.v1.PlayerExecutionContext`; the first binds the authenticated account/session/request and prospective tenant/realm/namespace/scope/instance target, while the second additionally binds `context.character_id` to the selected UUID and the exact roster snapshot. The exact same-namespace Game Session workload mTLS identity is allowlisted. These reads are not actor admission or a session-binding shortcut, and their proto has no handler or activation yet. +- `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – separate target wire contract for the `PRESEEDED_ONLY` pre-admission roster branch. Both carry `shared.v1.PlayerExecutionContext`; its scope string is exactly `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The first binds the authenticated account/session/request and prospective tenant/realm/namespace/scope/instance target, while the second additionally binds `context.character_id` to the selected UUID and exact roster snapshot. The selection response echoes discovery bindings only; it mints no assignment receipt or admission proof, which remain with the owning downstream write/readback. The exact same-namespace Game Session workload mTLS identity is allowlisted. These reads are not actor admission or a session-binding shortcut, and their proto has no handler or activation yet. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Entity-owned allocation and persistence of a primary controllable actor after the caller has passed Account membership/grant/realm admission. The target request carries the resolved `{accountId, tenantId, worldSlug, realmSlug}`, stable `playableStateNamespaceId`, the `playableStateScope` supplied only as authoritative realm-snapshot/attestation evidence, active `gameInstanceId`, explicit `entryPolicy=PLAYER_CREATED`, exact published descriptor identity/version, player creation input, and proof of the catalog/admission-pointer snapshot. Entity rejects a missing or mismatched policy before allocation or replay, and cross-checks the policy against the canonical snapshot and the applicable descriptor identity/version. It also carries caller-stable `createCharacterRequestId` and canonical `mutationDigest`; Entity recomputes the digest over the immutable trusted target, `entryPolicy`, exact descriptor/version, and creation input. The durable operation guard key is `{tenantId, playableStateNamespaceId, accountId, createCharacterRequestId}`. Within one local transaction, Entity admits and locks that guard plus digest, serializes the `PLAYER_CREATED` zero-roster boundary on `{tenantId, playableStateNamespaceId, accountId}`, and rereads the roster against the unchanged policy and descriptor/version before allocation. Only a still-empty roster may allocate; concurrent distinct request identities cannot both cross a stale zero-roster observation. Entity then atomically persists the allocated `{accountId, tenantId, playableStateNamespaceId, characterId}` association and replayable response. The same guard and digest exact-replay the original response; the same guard with a different digest returns `IDEMPOTENCY_CONFLICT` before allocation. Callers cannot choose or derive `playableStateScope`; Entity must reject caller-derived evidence and validate the exact immutable namespace/scope pair. A scope change under one namespace is rejected and never creates a second or split actor record. Entity allocates `characterId` only after the operation guard, validates the namespace/scope and active-instance fence, and never derives identity from account/name/hash or delegates character ownership to Account. Durable persistence/keying remains `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` remains separately validated immutable routing/authorization evidence, `gameInstanceId` is only the replaceable active-runtime fence, and neither is a durable character-identity dimension. Entity Management does not expose a direct player REST route. The current request path and enforcement do not yet prove this complete target boundary, so it remains an implementation/proof gap rather than a claim about live enforcement. - `UpdateEntity(UpdateEntityRequest) returns (UpdateEntityResponse)` – updates mutable character state for the requested `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, characterId}` target. `playableStateScope` must be the authoritative realm-snapshot/attestation result; callers cannot choose or derive it, and Entity validates the exact immutable namespace/scope pair before mutation. A caller-selected or changed scope, missing/mismatched namespace or scope, stale snapshot, caller-asserted instance, or global `characterId` is rejected rather than updating or splitting records. Target state also requires a fresh, server-resolved active-instance authorization fence for that exact namespace/scope and instance, checked atomically immediately before mutation. The current request path does not yet carry and prove the complete fresh fence, so it remains an implementation/proof gap and must not be treated as target enforcement. - `QueryInventory(QueryInventoryRequest) returns (QueryInventoryResponse)` – the current response is an unpaged repeated `InventoryItem items[]` projection. The live handler emits `item_id`, `item_name`, `item_description`, and `quantity`, and conditionally emits `container_instance_id`, `item_instance_id`, and `visible_ref` when those values are present. This projection does not establish complete instance-aware identity or stack/concurrency safety: rich pagination, complete holder-local stack uniqueness, find-then-create concurrency, and explicit-family duplicate handling remain target/proof gaps documented in [Runtime and Data](./runtime-and-data.md#implementation-status). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index c0b07e0052..5ac122863b 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -30,7 +30,7 @@ For script transitions, the live boundary includes the exact `scriptPinEpoch` an Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. -The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This wire currently has no handler or activation, and its policy does not authorize other roster branches or actor admission. +The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality; context `playable_state_scope` is the exact text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. Its response echoes discovery bindings only and mints no assignment receipt or admission proof. Any later assignment/admission write and authoritative readback remain with the owning downstream operation. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This wire currently has no handler or activation, and its policy does not authorize other roster branches or actor admission. For target gameplay forwarding, `PlayerExecutionContext` carries the server-resolved `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId}` binding and, for region-scoped work, its `{regionId, regionEpoch}` fence as one context. Game Session forwards the namespace and scope unchanged and validates exact context/request equality on every downstream response or mutation result; it never accepts a caller-selected namespace or substitutes a current one after admission. The current context/forwarding wire is narrower in places and does not yet carry or prove this complete namespace-plus-fence tuple, so that path remains an implementation/proof gap and must fail closed on missing authority. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index dcc649c22c..9b6b1d981c 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -252,7 +252,7 @@ These workflows: For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses its later-owned policy-aware Entity roster contract against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. The separate `CanonicalGameplayRosterService.ListPreseededRoster` wire implements only the pre-admission `PRESEEDED_ONLY` lookup; `PLAYER_CREATED` remains a later-owned target branch, and neither it nor `AUTO_PROVISIONED` may fall back to the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `CanonicalGameplayRosterService.ListPreseededRoster` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; a retry calls `ReadSelectedPreseededAssignment` with that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. The separate wire accepts only `PRESEEDED_ONLY`; other policy values fail with `FAILED_PRECONDITION`. `PLAYER_CREATED` remains a later-owned policy-aware roster branch, and `AUTO_PROVISIONED` remains its owner-defined idempotent existing-actor operation; neither branch may use the legacy numeric `ListCharactersByAccount` RPC as canonical gameplay authority. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. +`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `CanonicalGameplayRosterService.ListPreseededRoster` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; a retry calls `ReadSelectedPreseededAssignment` with that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. The response echoes request/account/selected-character/target/snapshot discovery bindings only: it mints no assignment receipt and proves no admission. Any later assignment/admission write and authoritative readback remain with the owning downstream operation. The separate wire accepts only `PRESEEDED_ONLY`; other policy values fail with `FAILED_PRECONDITION`. `PLAYER_CREATED` remains a later-owned policy-aware roster branch, and `AUTO_PROVISIONED` remains its owner-defined idempotent existing-actor operation; neither branch may use the legacy numeric `ListCharactersByAccount` RPC as canonical gameplay authority. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. If a workflow needs restart-safe continuation, durable waits/timers, or operator-visible in-flight state that survives one service lifetime, it should use the shared Temporal substrate described in [Temporal Control-Plane Workflows](./system-architecture-temporal-workflows.md) instead of extending `SagaRunner` toward durable workflow behavior. @@ -397,8 +397,13 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): PRESEEDED_ONLY: require creation input is absent if retrying selection step: - assignment = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, boundRosterSnapshot.reference, selectedCharacterId) - require assignment.snapshot == boundRosterSnapshot.reference + selectionReadback = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, boundRosterSnapshot.reference, selectedCharacterId) + require selectionReadback.request_uuid == boundRequest.request_uuid + require selectionReadback.canonical_account_uuid == boundRequest.canonical_account_uuid + require selectionReadback.selected_character_uuid == selectedCharacterId + require selectionReadback.target == boundRequest.expected_target + require selectionReadback.snapshot == boundRosterSnapshot.reference + # discovery binding only; assignment/admission write and readback are downstream rosterSnapshot = boundRosterSnapshot else: rosterSnapshot = Entity.CanonicalGameplayRosterService.ListPreseededRoster(discoveredEntry, discoveredEntryDigest) diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 66971a72b0..69a7bb6fd1 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -52,10 +52,11 @@ service CanonicalGameplayRosterService { // mTLS caller allowlisting. Context account_id equals canonical_account_uuid; request_id equals // request_uuid; tenant_id, realm_id, playable_state_namespace_id, playable_state_scope, and // game_instance_id equal the corresponding expected_target values; session_id identifies the - // authenticated session. No character_id is selected yet. The target policy must be - // PRESEEDED_ONLY. These equality checks do not require an additional Account lookup. A - // successful response includes its immutable snapshot UUID and digest, including when the - // roster is empty. + // authenticated session. Context playable_state_scope is the exact text "SHARED" or + // "ISOLATED" corresponding to the target enum value; numeric enum text is invalid. No + // character_id is selected yet. The target policy must be PRESEEDED_ONLY. These equality + // checks do not require an additional Account lookup. A successful response includes its + // immutable snapshot UUID and digest, including when the roster is empty. rpc ListPreseededRoster(CanonicalGameplayRosterRequest) returns (CanonicalGameplayRosterResponse); // Reads the selected assignment only if the supplied snapshot UUID and digest still identify @@ -141,11 +142,13 @@ message CanonicalGameplayRosterSelectedAssignmentResponse { string canonical_account_uuid = 2; string selected_character_uuid = 3; CanonicalGameplayRosterTarget target = 4; - string assignment_uuid = 5; - string intent_digest = 6; + reserved 5, 6; reserved 7; - reserved "error"; - // Exact snapshot reference supplied by the caller and validated by this operation. + reserved "assignment_uuid", "intent_digest", "error"; + // Exact snapshot reference supplied by the caller and validated by this operation. The + // response echoes discovery bindings only; it does not mint an assignment receipt or prove + // admission. Any later assignment/admission write and its authoritative readback belong to + // the owning downstream operation. CanonicalGameplayRosterSnapshotReference snapshot = 8; } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java index 6fde8fe528..780b51b380 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java @@ -51,6 +51,24 @@ void canonicalRosterResponsesHaveNoInResponseErrorAndReserveItsSlot() { .isEqualTo("snapshot"); } + @Test + void selectedAssignmentResponseReservesUnsupportedAssignmentReceiptSlots() { + Descriptor response = CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor(); + + assertThat(response.findFieldByNumber(5)).isNull(); + assertThat(response.findFieldByNumber(6)).isNull(); + for (int fieldNumber : new int[] {5, 6}) { + assertThat(response.toProto().getReservedRangeList()) + .anySatisfy( + range -> { + assertThat(range.getStart()).isLessThanOrEqualTo(fieldNumber); + assertThat(range.getEnd()).isGreaterThan(fieldNumber); + }); + } + assertThat(response.toProto().getReservedNameList()) + .contains("assignment_uuid", "intent_digest"); + } + private static void assertErrorSlotReserved(Descriptor descriptor, int fieldNumber) { assertThat(descriptor.toProto().getReservedRangeList()) .anySatisfy(range -> assertThat(range.getStart()).isEqualTo(fieldNumber)); From 881bffb18bdf6b81aec5743f41de50dd69d8c909 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:22:22 +1300 Subject: [PATCH 09/34] Bind roster consumer reads to typed player context and exact snapshot --- .../client/CanonicalGameplayRosterClient.java | 139 +++++-- .../CanonicalGameplayRosterClientTest.java | 339 ++++++++++++++---- 2 files changed, 389 insertions(+), 89 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java index f927385853..3aabfd8733 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -33,11 +33,13 @@ import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; @@ -105,18 +107,21 @@ protected CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlock /** * Reads one complete Entity snapshot for an exact current published route. The result is * discovery evidence only: it does not establish Account membership, admission, or PLAY. - */ + */ public PreseededRosterSnapshot listPreseededRoster( - CanonicalPublishedPlayerRoute publishedRoute, UUID canonicalAccountUuid) { + CanonicalPublishedPlayerRoute publishedRoute, + PlayerExecutionContext playerExecutionContext) { Objects.requireNonNull(publishedRoute, "publishedRoute"); - requireNonNil(canonicalAccountUuid, "canonicalAccountUuid"); CanonicalGameplayRosterTarget expectedTarget = toExpectedTarget(publishedRoute); + UUID canonicalAccountUuid = + validatePlayerExecutionContext(playerExecutionContext, expectedTarget, false); + UUID requestUuid = parseContextUuid(playerExecutionContext.getRequestId(), "request_id"); CanonicalGameplayRosterRequest request = CanonicalGameplayRosterRequest.newBuilder() - // This random UUID identifies only the read request; actor identity comes from Entity. - .setRequestUuid(UUID.randomUUID().toString()) + .setRequestUuid(requestUuid.toString()) .setCanonicalAccountUuid(canonicalAccountUuid.toString()) .setExpectedTarget(expectedTarget) + .setPlayerExecutionContext(playerExecutionContext) .build(); var currentStub = stub(); @@ -131,17 +136,25 @@ public PreseededRosterSnapshot listPreseededRoster( } /** - * Reads Entity's owner-issued assignment reference for one actor selected from the exact - * previously validated SHARED PRESEEDED_ONLY roster snapshot. This point-in-time reference is not - * Account eligibility or admission evidence; the later World hold revalidates assignment. + * Reads Entity's owner-issued assignment reference for the actor selected in the typed context + * from the exact previously validated SHARED PRESEEDED_ONLY roster snapshot. This point-in-time + * reference is not Account eligibility or admission evidence; the later World hold revalidates + * assignment. */ public VerifiedPreseededAssignment readSelectedPreseededAssignment( - PreseededRosterSnapshot roster, UUID selectedCharacterUuid) { + PreseededRosterSnapshot roster, PlayerExecutionContext playerExecutionContext) { requireOutsideTransactionAndSynchronization(); Objects.requireNonNull(roster, "roster"); - requireNonNil(selectedCharacterUuid, "selectedCharacterUuid"); requireValidSelectedRosterSnapshot(roster); CanonicalGameplayRosterTarget expectedTarget = roster.target(); + UUID contextAccountUuid = + validatePlayerExecutionContext(playerExecutionContext, expectedTarget, true); + if (!roster.canonicalAccountUuid().equals(contextAccountUuid)) { + throw new IllegalArgumentException( + "Player execution context account does not match the validated Entity roster"); + } + UUID selectedCharacterUuid = + parseContextUuid(playerExecutionContext.getCharacterId(), "character_id"); long actorMatches = roster.actors().stream() .filter(actor -> actor.characterUuid().equals(selectedCharacterUuid)) @@ -151,13 +164,18 @@ public VerifiedPreseededAssignment readSelectedPreseededAssignment( "Selected character must occur exactly once in the validated Entity roster"); } - UUID requestUuid = UUID.randomUUID(); + UUID requestUuid = parseContextUuid(playerExecutionContext.getRequestId(), "request_id"); CanonicalGameplayRosterSelectedAssignmentRequest request = CanonicalGameplayRosterSelectedAssignmentRequest.newBuilder() .setRequestUuid(requestUuid.toString()) .setCanonicalAccountUuid(roster.canonicalAccountUuid().toString()) .setSelectedCharacterUuid(selectedCharacterUuid.toString()) .setExpectedTarget(expectedTarget) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.snapshotUuid().toString()) + .setSnapshotDigest(roster.snapshotDigest())) + .setPlayerExecutionContext(playerExecutionContext) .build(); var currentStub = stub(); @@ -171,6 +189,78 @@ public VerifiedPreseededAssignment readSelectedPreseededAssignment( return validateSelectedAssignmentResponse(requestUuid, roster, selectedCharacterUuid, response); } + private static UUID validatePlayerExecutionContext( + PlayerExecutionContext context, + CanonicalGameplayRosterTarget expectedTarget, + boolean selectedCharacterRequired) { + if (context == null) { + throw new IllegalArgumentException("Player execution context is required"); + } + if (!context.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Player execution context contains unknown fields"); + } + + UUID accountUuid = parseContextUuid(context.getAccountId(), "account_id"); + parseContextUuid(context.getSessionId(), "session_id"); + parseContextUuid(context.getRequestId(), "request_id"); + requireContextUuidEquals(context.getTenantId(), expectedTarget.getTenantUuid(), "tenant_id"); + requireContextUuidEquals(context.getRealmId(), expectedTarget.getRealmUuid(), "realm_id"); + requireContextUuidEquals( + context.getPlayableStateNamespaceId(), + expectedTarget.getPlayableStateNamespaceUuid(), + "playable_state_namespace_id"); + requireContextUuidEquals( + context.getGameInstanceId(), expectedTarget.getGameInstanceUuid(), "game_instance_id"); + + PlayableStateScope contextScope = + switch (context.getPlayableStateScope()) { + case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + default -> + throw new IllegalArgumentException( + "Player execution context playable_state_scope must be exact SHARED or ISOLATED"); + }; + if (contextScope != expectedTarget.getPlayableStateScope()) { + throw new IllegalArgumentException( + "Player execution context playable_state_scope does not match the expected target"); + } + + if (selectedCharacterRequired) { + parseContextUuid(context.getCharacterId(), "character_id"); + } else if (!context.getCharacterId().isEmpty()) { + throw new IllegalArgumentException( + "Initial roster reads must not select an actor in player execution context"); + } + return accountUuid; + } + + private static void requireContextUuidEquals(String value, String expected, String fieldName) { + UUID parsed = parseContextUuid(value, fieldName); + if (!parsed.toString().equals(expected)) { + throw new IllegalArgumentException( + "Player execution context " + fieldName + " does not match the expected target"); + } + } + + private static UUID parseContextUuid(String value, String fieldName) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Player execution context " + fieldName + " is required"); + } + UUID parsed; + try { + parsed = UUID.fromString(value); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Player execution context " + fieldName + " must be a canonical non-nil UUID", + malformed); + } + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException( + "Player execution context " + fieldName + " must be a canonical non-nil UUID"); + } + return parsed; + } + private static void requireOutsideTransactionAndSynchronization() { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { @@ -230,15 +320,6 @@ private static VerifiedPreseededAssignment validateSelectedAssignmentResponse( if (!response.getUnknownFields().asMap().isEmpty()) { throw invalidSelectedAssignmentResponse("response contains unknown fields"); } - if (response.hasError()) { - if (!response.getError().getUnknownFields().asMap().isEmpty()) { - throw invalidSelectedAssignmentResponse("error contains unknown fields"); - } - String code = response.getError().getCode(); - throw new IllegalStateException( - "Entity selected assignment read failed" - + (code == null || code.isBlank() ? "" : ": " + code)); - } if (!requestUuid.toString().equals(response.getRequestUuid())) { throw invalidSelectedAssignmentResponse("response changed the request correlation"); } @@ -253,6 +334,18 @@ private static VerifiedPreseededAssignment validateSelectedAssignmentResponse( || !roster.target().equals(response.getTarget())) { throw invalidSelectedAssignmentResponse("response changed the complete expected target"); } + if (!response.hasSnapshot() + || !response.getSnapshot().getUnknownFields().asMap().isEmpty()) { + throw invalidSelectedAssignmentResponse("response snapshot is absent or malformed"); + } + UUID echoedSnapshotUuid = + parseCanonicalUuid(response.getSnapshot().getSnapshotUuid(), "snapshot_uuid"); + String echoedSnapshotDigest = response.getSnapshot().getSnapshotDigest(); + if (!roster.snapshotUuid().equals(echoedSnapshotUuid) + || !roster.snapshotDigest().equals(echoedSnapshotDigest)) { + throw invalidSelectedAssignmentResponse( + "response changed the exact roster snapshot UUID or digest"); + } UUID assignmentOperationId = parseCanonicalUuid(response.getAssignmentUuid(), "assignment_uuid"); String intentDigest = response.getIntentDigest(); @@ -281,12 +374,6 @@ private static PreseededRosterSnapshot validateResponse( if (response == null) { throw invalidResponse("response is absent"); } - if (response.hasError()) { - String code = response.getError().getCode(); - throw new IllegalStateException( - "Entity canonical gameplay roster read failed" - + (code == null || code.isBlank() ? "" : ": " + code)); - } if (!response.getUnknownFields().asMap().isEmpty()) { throw invalidResponse("response contains unknown fields"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java index d930818393..5fbed290dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java @@ -4,7 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -42,6 +42,7 @@ import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; @@ -50,6 +51,7 @@ import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; @@ -58,6 +60,9 @@ class CanonicalGameplayRosterClientTest { private static final String NAMESPACE = "test"; private static final UUID TENANT_UUID = uuid("11111111-1111-4111-8111-111111111111"); private static final UUID ACCOUNT_UUID = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID SESSION_UUID = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + private static final UUID LIST_REQUEST_UUID = uuid("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + private static final UUID SELECT_REQUEST_UUID = uuid("ffffffff-ffff-4fff-8fff-ffffffffffff"); private static final UUID ACTOR_UUID = uuid("77777777-7777-4777-8777-777777777777"); private static final UUID SNAPSHOT_UUID = uuid("88888888-8888-4888-8888-888888888888"); private static final UUID ASSIGNMENT_UUID = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); @@ -88,7 +93,7 @@ void sendsExactPublishedTargetWithAccountAndValidatesSourceSnapshot() throws Exc }); var client = newClient(stub); - var roster = client.listPreseededRoster(route, ACCOUNT_UUID); + var roster = client.listPreseededRoster(route, listContext()); assertThat(roster.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); assertThat(roster.snapshotUuid()).isEqualTo(SNAPSHOT_UUID); @@ -110,10 +115,105 @@ void sendsExactPublishedTargetWithAccountAndValidatesSourceSnapshot() throws Exc .isEqualTo(request.getRequestUuid()); assertThat(request.getCanonicalAccountUuid()).isEqualTo(ACCOUNT_UUID.toString()); assertThat(request.getExpectedTarget()).isEqualTo(roster.target()); + assertThat(request.getRequestUuid()).isEqualTo(listContext().getRequestId()); + assertThat(request.hasPlayerExecutionContext()).isTrue(); + assertThat(request.getPlayerExecutionContext()).isEqualTo(listContext()); assertThat(request.getExpectedTarget().getPublishedPolicyDigest()) .isEqualTo(route.selectedPolicyEvidence().policyDigest().substring("sha256:".length())); } + @Test + void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() { + var stub = mockStub(); + var client = newClient(stub); + var unknown = + UnknownFieldSet.newBuilder() + .addField(101, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + + assertThatThrownBy(() -> client.listPreseededRoster(publishedRoute(), null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("context is required"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setAccountId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setSessionId("").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("session_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setRequestId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext() + .toBuilder() + .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("playable_state_namespace_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setTenantId(ACCOUNT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenant_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setRealmId(ACCOUNT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("realm_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setGameInstanceId(ACCOUNT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("game_instance_id"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setPlayableStateScope("2").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact SHARED or ISOLATED"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setPlayableStateScope("ISOLATED").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("does not match the expected target"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setCharacterId(ACTOR_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must not select an actor"); + assertThatThrownBy( + () -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("unknown fields"); + + verify(stub, never()).listPreseededRoster(any()); + } + @Test void matchesEntityOwnedRosterDigestV3GoldenVector() throws Exception { var target = @@ -168,7 +268,7 @@ void rejectsChangedAccountAndCompleteTargetEcho() throws Exception { .build(); }); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("canonical account UUID"); @@ -184,7 +284,7 @@ void rejectsChangedAccountAndCompleteTargetEcho() throws Exception { }) .when(stub) .listPreseededRoster(any()); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("complete expected target"); } @@ -215,7 +315,7 @@ void rejectsDuplicateMalformedAndUnsupportedActors() throws Exception { .build(); }); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("duplicate character UUID"); @@ -233,7 +333,7 @@ void rejectsDuplicateMalformedAndUnsupportedActors() throws Exception { }) .when(stub) .listPreseededRoster(any()); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("display name is malformed"); @@ -255,13 +355,13 @@ void rejectsDuplicateMalformedAndUnsupportedActors() throws Exception { }) .when(stub) .listPreseededRoster(any()); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unsupported actor kind"); } @Test - void rejectsBadSnapshotDigestAndEntityApplicationErrors() throws Exception { + void rejectsBadSnapshotDigestAndPropagatesEntityTransportFailures() throws Exception { var stub = mockStub(); when(stub.listPreseededRoster(any())) .thenAnswer( @@ -275,7 +375,7 @@ void rejectsBadSnapshotDigestAndEntityApplicationErrors() throws Exception { .addActors(actor(ACTOR_UUID, "Pilot One")) .build(); }); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("snapshot_digest does not bind"); @@ -291,22 +391,16 @@ void rejectsBadSnapshotDigestAndEntityApplicationErrors() throws Exception { }) .when(stub) .listPreseededRoster(any()); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("snapshot_uuid is not a canonical non-nil UUID"); - doReturn( - CanonicalGameplayRosterResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("OWNER_EVIDENCE_UNAVAILABLE") - .setMessage("not returned as roster data")) - .build()) - .when(stub) - .listPreseededRoster(any()); - assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("OWNER_EVIDENCE_UNAVAILABLE"); + var transportFailure = + Status.UNAVAILABLE.withDescription("owner unavailable").asRuntimeException(); + doThrow(transportFailure).when(stub).listPreseededRoster(any()); + assertThatThrownBy( + () -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + .isSameAs(transportFailure); } @Test @@ -321,7 +415,7 @@ void readsExactSelectedAssignmentAndReturnsBoundNonAdmissionCapability() throws return selectedAssignmentResponse(request); }); - var verified = client.readSelectedPreseededAssignment(roster, ACTOR_UUID); + var verified = client.readSelectedPreseededAssignment(roster, selectedContext()); assertThat(verified.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); assertThat(verified.selectedCharacterUuid()).isEqualTo(ACTOR_UUID); @@ -337,15 +431,95 @@ void readsExactSelectedAssignmentAndReturnsBoundNonAdmissionCapability() throws var request = requestCaptor.getValue(); UUID requestUuid = UUID.fromString(request.getRequestUuid()); assertThat(requestUuid.toString()).isEqualTo(request.getRequestUuid()); - assertThat(requestUuid.version()).isEqualTo(4); - assertThat(requestUuid.variant()).isEqualTo(2); - assertThat(requestUuid).isNotIn(ACCOUNT_UUID, ACTOR_UUID, SNAPSHOT_UUID, ASSIGNMENT_UUID); + assertThat(requestUuid).isEqualTo(SELECT_REQUEST_UUID); assertThat(request.getCanonicalAccountUuid()).isEqualTo(ACCOUNT_UUID.toString()); assertThat(request.getSelectedCharacterUuid()).isEqualTo(ACTOR_UUID.toString()); assertThat(request.getExpectedTarget()).isEqualTo(roster.target()); + assertThat(request.getExpectedSnapshot()) + .isEqualTo( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.snapshotUuid().toString()) + .setSnapshotDigest(roster.snapshotDigest()) + .build()); + assertThat(request.getPlayerExecutionContext()).isEqualTo(selectedContext()); verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); } + @Test + void rejectsSelectedContextAccountNamespaceAndActorSubstitutionBeforeRpc() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, selectedContext().toBuilder().setAccountId(TENANT_UUID.toString()).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("account does not match"); + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, + selectedContext().toBuilder() + .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("playable_state_namespace_id"); + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, + selectedContext().toBuilder() + .setCharacterId(SNAPSHOT_UUID.toString()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exactly once"); + assertThatThrownBy( + () -> + client.readSelectedPreseededAssignment( + roster, selectedContext().toBuilder().setRequestId("not-a-uuid").build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request_id"); + + verify(stub, never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsSelectedReadbackSnapshotUuidOrDigestSubstitution() throws Exception { + var stub = mockStub(); + var client = newClient(stub); + var roster = validatedRoster(client, stub); + var responseNumber = new AtomicInteger(); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + var response = selectedAssignmentResponse(request).toBuilder(); + return switch (responseNumber.getAndIncrement()) { + case 0 -> + response + .setSnapshot( + request.getExpectedSnapshot().toBuilder() + .setSnapshotUuid(ASSIGNMENT_UUID.toString())) + .build(); + default -> + response + .setSnapshot( + request.getExpectedSnapshot().toBuilder() + .setSnapshotDigest("a".repeat(64))) + .build(); + }; + }); + + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact roster snapshot UUID or digest"); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact roster snapshot UUID or digest"); + } + @Test void rejectsChangedAssignmentCorrelationAccountActorAndCompleteTarget() throws Exception { var stub = mockStub(); @@ -368,22 +542,22 @@ void rejectsChangedAssignmentCorrelationAccountActorAndCompleteTarget() throws E }; }); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("request correlation"); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("canonical account UUID"); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("selected character UUID"); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("complete expected target"); } @Test - void rejectsUnknownFieldsErrorsAndMissingSelectedAssignmentFields() throws Exception { + void rejectsUnknownFieldsAndMissingSelectedAssignmentFields() throws Exception { var stub = mockStub(); var client = newClient(stub); var roster = validatedRoster(client, stub); @@ -399,48 +573,56 @@ void rejectsUnknownFieldsErrorsAndMissingSelectedAssignmentFields() throws Excep .setUnknownFields(unknown) .build(); }); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unknown fields"); + var transportFailure = + Status.FAILED_PRECONDITION.withDescription("roster snapshot changed").asRuntimeException(); + doThrow(transportFailure).when(stub).readSelectedPreseededAssignment(any()); + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) + .isSameAs(transportFailure); + doAnswer( - invocation -> - CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("SELECTED_ASSIGNMENT_UNAVAILABLE") - .setMessage("not assignment data")) - .build()) + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder().clearTarget().build(); + }) .when(stub) .readSelectedPreseededAssignment(any()); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("SELECTED_ASSIGNMENT_UNAVAILABLE"); + .hasMessageContaining("complete expected target"); doAnswer( - invocation -> - CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() - .setError( - net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() - .setCode("SELECTED_ASSIGNMENT_UNAVAILABLE") - .setUnknownFields(unknown)) - .build()) + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder().clearSnapshot().build(); + }) .when(stub) .readSelectedPreseededAssignment(any()); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("error contains unknown fields"); + .hasMessageContaining("response snapshot is absent"); doAnswer( invocation -> { CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); - return selectedAssignmentResponse(request).toBuilder().clearTarget().build(); + var unknownSnapshot = + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.snapshotUuid().toString()) + .setSnapshotDigest(roster.snapshotDigest()) + .setUnknownFields(unknown) + .build(); + return selectedAssignmentResponse(request).toBuilder() + .setSnapshot(unknownSnapshot) + .build(); }) .when(stub) .readSelectedPreseededAssignment(any()); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("complete expected target"); + .hasMessageContaining("response snapshot is absent or malformed"); doAnswer( invocation -> { @@ -451,7 +633,7 @@ void rejectsUnknownFieldsErrorsAndMissingSelectedAssignmentFields() throws Excep }) .when(stub) .readSelectedPreseededAssignment(any()); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("complete expected target"); } @@ -477,7 +659,7 @@ void rejectsNilOrMalformedAssignmentReferenceAndIntentDigest() throws Exception }) .when(stub) .readSelectedPreseededAssignment(any()); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("assignment_uuid"); } @@ -493,7 +675,7 @@ void rejectsNilOrMalformedAssignmentReferenceAndIntentDigest() throws Exception }) .when(stub) .readSelectedPreseededAssignment(any()); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("intent_digest"); } @@ -517,10 +699,10 @@ void rejectsAbsentOrDuplicateSelectedActorInRosterInput() throws Exception { new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"), new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"))); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(absentRoster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(absentRoster, selectedContext())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exactly once"); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(duplicateRoster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(duplicateRoster, selectedContext())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate actor"); verify(stub, never()).readSelectedPreseededAssignment(any()); @@ -534,7 +716,7 @@ void refusesSelectedAssignmentReadInsideTransactionOrSynchronization() throws Ex try { TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("transaction or synchronization"); } finally { @@ -543,7 +725,7 @@ void refusesSelectedAssignmentReadInsideTransactionOrSynchronization() throws Ex try { TransactionSynchronizationManager.initSynchronization(); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, ACTOR_UUID)) + assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("transaction or synchronization"); } finally { @@ -556,7 +738,13 @@ void refusesSelectedAssignmentReadInsideTransactionOrSynchronization() throws Ex void rejectsNilAccountBeforeClientUseAndRequiresWorkloadMtls() { var factory = mock(GrpcChannelFactory.class); var uninitialized = newClientWithoutStub(factory); - assertThatThrownBy(() -> uninitialized.listPreseededRoster(publishedRoute(), new UUID(0L, 0L))) + assertThatThrownBy( + () -> + uninitialized.listPreseededRoster( + publishedRoute(), + listContext().toBuilder() + .setAccountId(new UUID(0L, 0L).toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil"); verifyNoInteractions(factory); @@ -608,11 +796,35 @@ void rejectsResponsesFromOtherEntityWorkloadIdentity() throws Exception { .thenReturn(call); var client = newClientWithChannel(channel); - assertThatThrownBy(() -> client.listPreseededRoster(publishedRoute(), ACCOUNT_UUID)) + assertThatThrownBy(() -> client.listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(StatusRuntimeException.class) .hasMessageContaining("UNAUTHENTICATED"); } + private static PlayerExecutionContext listContext() { + return playerExecutionContext(LIST_REQUEST_UUID, ""); + } + + private static PlayerExecutionContext selectedContext() { + return playerExecutionContext(SELECT_REQUEST_UUID, ACTOR_UUID.toString()); + } + + private static PlayerExecutionContext playerExecutionContext( + UUID requestUuid, String characterId) { + CanonicalPlayableTarget route = publishedRoute().route(); + return PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT_UUID.toString()) + .setTenantId(route.canonicalTenantId().toString()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setGameInstanceId(route.canonicalGameInstanceId().toString()) + .setCharacterId(characterId) + .setSessionId(SESSION_UUID.toString()) + .setRealmId(route.realmId().toString()) + .setRequestId(requestUuid.toString()) + .setPlayableStateScope(route.playableStateScope()) + .build(); + } + private static CanonicalPublishedPlayerRoute publishedRoute() { var fixture = PublishedRealmPolicyEvidenceFixture.fixture( @@ -684,7 +896,7 @@ private static CanonicalGameplayRosterClient.PreseededRosterSnapshot validatedRo .addActors(actor(ACTOR_UUID, "Pilot One")) .build(); }); - return client.listPreseededRoster(publishedRoute(), ACCOUNT_UUID); + return client.listPreseededRoster(publishedRoute(), listContext()); } private static CanonicalGameplayRosterSelectedAssignmentResponse selectedAssignmentResponse( @@ -694,6 +906,7 @@ private static CanonicalGameplayRosterSelectedAssignmentResponse selectedAssignm .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) .setTarget(request.getExpectedTarget()) + .setSnapshot(request.getExpectedSnapshot()) .setAssignmentUuid(ASSIGNMENT_UUID.toString()) .setIntentDigest("c".repeat(64)) .build(); From 32924d7160732a2fd17bab7305584bb077ddf150 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:25:36 +1300 Subject: [PATCH 10/34] Define roster selection as original persisted Entity assignment evidence --- .../api-contracts.md | 4 +++- .../game-session-service/api-contracts.md | 2 +- .../system-architecture-transactions.md | 14 ++++++++++-- .../v1/entity_management_service.proto | 14 +++++++----- ...icalGameplayRosterProtoDescriptorTest.java | 22 ++++++++----------- 5 files changed, 34 insertions(+), 22 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index dea1eea61b..170937331c 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,7 +6,9 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot discovery bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. Its response does not mint an assignment receipt or prove admission; any later assignment/admission write and authoritative readback remain with the owning downstream operation. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. +The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. + +The `ReadSelectedPreseededAssignment` `intent_digest` is the lowercase hexadecimal SHA-256 of Entity's immutable assignment-intent preimage. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. UUIDs use canonical `UUID.toString()` form, counters use base-10 decimal text, and scope/policy values use their canonical enum names. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest is the original persisted operation-intent digest, not a digest of current owner evidence or current Account state. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 5ac122863b..2e13bb6f0d 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -30,7 +30,7 @@ For script transitions, the live boundary includes the exact `scriptPinEpoch` an Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. -The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality; context `playable_state_scope` is the exact text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. Its response echoes discovery bindings only and mints no assignment receipt or admission proof. Any later assignment/admission write and authoritative readback remain with the owning downstream operation. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This wire currently has no handler or activation, and its policy does not authorize other roster branches or actor admission. +The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality; context `playable_state_scope` is the exact text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. Its response echoes discovery bindings and returns the original assignment operation UUID and immutable intent digest from Entity's unique matching committed receipt. Game Session binds and reuses that original reference for later owner revalidation; it does not mint an assignment identity or treat the reference as admission proof or current Account eligibility. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This wire currently has no handler or activation, and its policy does not authorize other roster branches or actor admission. For target gameplay forwarding, `PlayerExecutionContext` carries the server-resolved `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId}` binding and, for region-scoped work, its `{regionId, regionEpoch}` fence as one context. Game Session forwards the namespace and scope unchanged and validates exact context/request equality on every downstream response or mutation result; it never accepts a caller-selected namespace or substitutes a current one after admission. The current context/forwarding wire is narrower in places and does not yet carry or prove this complete namespace-plus-fence tuple, so that path remains an implementation/proof gap and must fail closed on missing authority. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index 9b6b1d981c..e91fecf781 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -252,7 +252,7 @@ These workflows: For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses its later-owned policy-aware Entity roster contract against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. The separate `CanonicalGameplayRosterService.ListPreseededRoster` wire implements only the pre-admission `PRESEEDED_ONLY` lookup; `PLAYER_CREATED` remains a later-owned target branch, and neither it nor `AUTO_PROVISIONED` may fall back to the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `CanonicalGameplayRosterService.ListPreseededRoster` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; a retry calls `ReadSelectedPreseededAssignment` with that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. The response echoes request/account/selected-character/target/snapshot discovery bindings only: it mints no assignment receipt and proves no admission. Any later assignment/admission write and authoritative readback remain with the owning downstream operation. The separate wire accepts only `PRESEEDED_ONLY`; other policy values fail with `FAILED_PRECONDITION`. `PLAYER_CREATED` remains a later-owned policy-aware roster branch, and `AUTO_PROVISIONED` remains its owner-defined idempotent existing-actor operation; neither branch may use the legacy numeric `ListCharactersByAccount` RPC as canonical gameplay authority. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. +`AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `CanonicalGameplayRosterService.ListPreseededRoster` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; `ReadSelectedPreseededAssignment` requires that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. The response echoes request/account/selected-character/target/snapshot bindings and returns Entity's original assignment operation UUID and immutable intent digest from the unique matching committed receipt. The saga binds and retries with that unchanged reference so the later placement owner can revalidate the original assignment; the reference is neither minted by this read nor evidence of admission or current Account eligibility. The separate wire accepts only `PRESEEDED_ONLY`; other policy values fail with `FAILED_PRECONDITION`. `PLAYER_CREATED` remains a later-owned policy-aware roster branch, and `AUTO_PROVISIONED` remains its owner-defined idempotent existing-actor operation; neither branch may use the legacy numeric `ListCharactersByAccount` RPC as canonical gameplay authority. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. If a workflow needs restart-safe continuation, durable waits/timers, or operator-visible in-flight state that survives one service lifetime, it should use the shared Temporal substrate described in [Temporal Control-Plane Workflows](./system-architecture-temporal-workflows.md) instead of extending `SagaRunner` toward durable workflow behavior. @@ -403,7 +403,9 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): require selectionReadback.selected_character_uuid == selectedCharacterId require selectionReadback.target == boundRequest.expected_target require selectionReadback.snapshot == boundRosterSnapshot.reference - # discovery binding only; assignment/admission write and readback are downstream + require selectionReadback.assignment_uuid == boundAssignmentUuid + require selectionReadback.intent_digest == boundIntentDigest + # original persisted reference only; placement owner must revalidate it rosterSnapshot = boundRosterSnapshot else: rosterSnapshot = Entity.CanonicalGameplayRosterService.ListPreseededRoster(discoveredEntry, discoveredEntryDigest) @@ -419,6 +421,14 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): resolvedSelectedCharacter = require actor matching selectedCharacterId in unchanged roster/snapshot bind resolvedSelectedCharacter.characterId to sagaStep select resolvedSelectedCharacter # lookup/selection only; no actor mutation + if not retrying selection step: + selectionReadback = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, rosterSnapshot.reference, selectedCharacterId) + require selectionReadback.request_uuid == boundRequest.request_uuid + require selectionReadback.canonical_account_uuid == boundRequest.canonical_account_uuid + require selectionReadback.selected_character_uuid == selectedCharacterId + require selectionReadback.target == boundRequest.expected_target + require selectionReadback.snapshot == rosterSnapshot.reference + bind selectionReadback.assignment_uuid and selectionReadback.intent_digest to sagaStep retries reuse the same discoveredEntry, discoveredEntryDigest, branch, applicable roster snapshot identity/digest, and resolved selectedCharacterId; an entered PLAYER_CREATED create step replays Entity before any fresh roster rejection, and each actor mutation reuses its operation request identity, mutationDigest, and canonicalCreationInput, while a changed input or roster snapshot fails closed ``` diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 69a7bb6fd1..eda2eb2236 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -142,13 +142,17 @@ message CanonicalGameplayRosterSelectedAssignmentResponse { string canonical_account_uuid = 2; string selected_character_uuid = 3; CanonicalGameplayRosterTarget target = 4; - reserved 5, 6; + // Original non-nil operation identity and immutable intent digest from the unique committed + // ASSIGNED PRESEEDED PLAYER receipt matching this exact account, actor, target, and owner proof. + // This read returns persisted owner evidence; it never mints an assignment identity or digest. + string assignment_uuid = 5; + string intent_digest = 6; reserved 7; - reserved "assignment_uuid", "intent_digest", "error"; + reserved "error"; // Exact snapshot reference supplied by the caller and validated by this operation. The - // response echoes discovery bindings only; it does not mint an assignment receipt or prove - // admission. Any later assignment/admission write and its authoritative readback belong to - // the owning downstream operation. + // response echoes that binding alongside the original persisted assignment reference. The + // reference does not prove admission or current Account eligibility; placement must revalidate + // it with its owning Entity write/readback contract. CanonicalGameplayRosterSnapshotReference snapshot = 8; } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java index 780b51b380..f1222d4ef0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/CanonicalGameplayRosterProtoDescriptorTest.java @@ -52,21 +52,17 @@ void canonicalRosterResponsesHaveNoInResponseErrorAndReserveItsSlot() { } @Test - void selectedAssignmentResponseReservesUnsupportedAssignmentReceiptSlots() { + void selectedAssignmentResponseCarriesTheOriginalAssignmentReference() { Descriptor response = CanonicalGameplayRosterSelectedAssignmentResponse.getDescriptor(); - assertThat(response.findFieldByNumber(5)).isNull(); - assertThat(response.findFieldByNumber(6)).isNull(); - for (int fieldNumber : new int[] {5, 6}) { - assertThat(response.toProto().getReservedRangeList()) - .anySatisfy( - range -> { - assertThat(range.getStart()).isLessThanOrEqualTo(fieldNumber); - assertThat(range.getEnd()).isGreaterThan(fieldNumber); - }); - } - assertThat(response.toProto().getReservedNameList()) - .contains("assignment_uuid", "intent_digest"); + assertThat(response.findFieldByNumber(5).getName()).isEqualTo("assignment_uuid"); + assertThat(response.findFieldByNumber(5).getType()).isEqualTo(FieldDescriptor.Type.STRING); + assertThat(response.findFieldByNumber(6).getName()).isEqualTo("intent_digest"); + assertThat(response.findFieldByNumber(6).getType()).isEqualTo(FieldDescriptor.Type.STRING); + assertThat(response.findFieldByNumber(7)).isNull(); + assertThat(response.toProto().getReservedRangeList()) + .anySatisfy(range -> assertThat(range.getStart()).isEqualTo(7)); + assertThat(response.toProto().getReservedNameList()).contains("error"); } private static void assertErrorSlotReserved(Descriptor descriptor, int fieldNumber) { From 377b0561313a8f6ee93cd29f3716f8af933293e3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:36:25 +1300 Subject: [PATCH 11/34] Format roster consumer and complete focused rejection fixture --- .../client/CanonicalGameplayRosterClient.java | 13 ++++---- .../CanonicalGameplayRosterClientTest.java | 30 ++++++++----------- 2 files changed, 18 insertions(+), 25 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java index 3aabfd8733..52f43c5732 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -33,8 +33,8 @@ import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; -import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; @@ -107,10 +107,9 @@ protected CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlock /** * Reads one complete Entity snapshot for an exact current published route. The result is * discovery evidence only: it does not establish Account membership, admission, or PLAY. - */ + */ public PreseededRosterSnapshot listPreseededRoster( - CanonicalPublishedPlayerRoute publishedRoute, - PlayerExecutionContext playerExecutionContext) { + CanonicalPublishedPlayerRoute publishedRoute, PlayerExecutionContext playerExecutionContext) { Objects.requireNonNull(publishedRoute, "publishedRoute"); CanonicalGameplayRosterTarget expectedTarget = toExpectedTarget(publishedRoute); UUID canonicalAccountUuid = @@ -251,8 +250,7 @@ private static UUID parseContextUuid(String value, String fieldName) { parsed = UUID.fromString(value); } catch (IllegalArgumentException malformed) { throw new IllegalArgumentException( - "Player execution context " + fieldName + " must be a canonical non-nil UUID", - malformed); + "Player execution context " + fieldName + " must be a canonical non-nil UUID", malformed); } if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { throw new IllegalArgumentException( @@ -334,8 +332,7 @@ private static VerifiedPreseededAssignment validateSelectedAssignmentResponse( || !roster.target().equals(response.getTarget())) { throw invalidSelectedAssignmentResponse("response changed the complete expected target"); } - if (!response.hasSnapshot() - || !response.getSnapshot().getUnknownFields().asMap().isEmpty()) { + if (!response.hasSnapshot() || !response.getSnapshot().getUnknownFields().asMap().isEmpty()) { throw invalidSelectedAssignmentResponse("response snapshot is absent or malformed"); } UUID echoedSnapshotUuid = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java index 5fbed290dd..a64ba478a8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java @@ -42,8 +42,8 @@ import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; -import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; @@ -123,7 +123,7 @@ void sendsExactPublishedTargetWithAccountAndValidatesSourceSnapshot() throws Exc } @Test - void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() { + void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() throws Exception { var stub = mockStub(); var client = newClient(stub); var unknown = @@ -156,8 +156,7 @@ void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() { () -> client.listPreseededRoster( publishedRoute(), - listContext() - .toBuilder() + listContext().toBuilder() .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) .build())) .isInstanceOf(IllegalArgumentException.class) @@ -186,8 +185,7 @@ void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() { assertThatThrownBy( () -> client.listPreseededRoster( - publishedRoute(), - listContext().toBuilder().setPlayableStateScope("2").build())) + publishedRoute(), listContext().toBuilder().setPlayableStateScope("2").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact SHARED or ISOLATED"); assertThatThrownBy( @@ -398,8 +396,7 @@ void rejectsBadSnapshotDigestAndPropagatesEntityTransportFailures() throws Excep var transportFailure = Status.UNAVAILABLE.withDescription("owner unavailable").asRuntimeException(); doThrow(transportFailure).when(stub).listPreseededRoster(any()); - assertThatThrownBy( - () -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) + assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isSameAs(transportFailure); } @@ -454,7 +451,8 @@ void rejectsSelectedContextAccountNamespaceAndActorSubstitutionBeforeRpc() throw assertThatThrownBy( () -> client.readSelectedPreseededAssignment( - roster, selectedContext().toBuilder().setAccountId(TENANT_UUID.toString()).build())) + roster, + selectedContext().toBuilder().setAccountId(TENANT_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("account does not match"); assertThatThrownBy( @@ -470,9 +468,7 @@ roster, selectedContext().toBuilder().setAccountId(TENANT_UUID.toString()).build () -> client.readSelectedPreseededAssignment( roster, - selectedContext().toBuilder() - .setCharacterId(SNAPSHOT_UUID.toString()) - .build())) + selectedContext().toBuilder().setCharacterId(SNAPSHOT_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exactly once"); assertThatThrownBy( @@ -699,10 +695,12 @@ void rejectsAbsentOrDuplicateSelectedActorInRosterInput() throws Exception { new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"), new CanonicalGameplayRosterClient.RosterActor(ACTOR_UUID, "Pilot One"))); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(absentRoster, selectedContext())) + assertThatThrownBy( + () -> client.readSelectedPreseededAssignment(absentRoster, selectedContext())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exactly once"); - assertThatThrownBy(() -> client.readSelectedPreseededAssignment(duplicateRoster, selectedContext())) + assertThatThrownBy( + () -> client.readSelectedPreseededAssignment(duplicateRoster, selectedContext())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate actor"); verify(stub, never()).readSelectedPreseededAssignment(any()); @@ -742,9 +740,7 @@ void rejectsNilAccountBeforeClientUseAndRequiresWorkloadMtls() { () -> uninitialized.listPreseededRoster( publishedRoute(), - listContext().toBuilder() - .setAccountId(new UUID(0L, 0L).toString()) - .build())) + listContext().toBuilder().setAccountId(new UUID(0L, 0L).toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil"); verifyNoInteractions(factory); From 0676d79a1c839f9fc009bb030149fff30c62072f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:39:50 +1300 Subject: [PATCH 12/34] feat(game-session): compose non-admitting owner roster selection --- .../game-session-service/api-contracts.md | 2 + .../player-access-and-session.md | 2 +- ...CanonicalPlayerRouteReadConfiguration.java | 11 + ...nonicalGameplayRosterSelectionService.java | 263 +++++++ ...nicalPlayerRouteReadConfigurationTest.java | 9 + ...calGameplayRosterSelectionServiceTest.java | 659 ++++++++++++++++++ 6 files changed, 945 insertions(+), 1 deletion(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 8de052b028..4d8626c2c8 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -67,6 +67,8 @@ Encoding is closed and unambiguous: strings use strict UTF-8 with a signed 32-bi Entity consumer code remains outside this Game Session source slice. The read itself is not permission to mutate actor data; Account remains the identity and membership authority, and this source method is not `JOIN` or `PLAY` admission. +Game Session also exposes a default-off `CanonicalGameplayRosterSelectionService` composition for its existing typed Entity roster reads. It accepts a `PlayerExecutionContext` already constructed from authenticated Game Session state, binds its tenant, realm, namespace, scope, and instance to the current published route, and accepts only a one-based ordinal from the validated Entity snapshot. It rereads the exact published route after each Entity read and returns only a selection menu, denial, or Entity's original assignment reference. This source-only composition consumes the existing Entity methods but does not establish membership or admission, persist a selection, bind a session, or activate `PLAY` or `LOOK`; Entity remains the assignment-evidence owner, including later revalidation. + 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 workload leaf and CA fingerprints; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the published 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). 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). ## Session Front-End and Lease-Owner Routing diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index b24c1698b7..0fddc617b9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Game Session now carries a default-off source path for current route and published-policy evidence, with exact Entity-only roster and preseeded-assignment reads. Focused proof sources cover default-off and enabled route-reader composition (real reader beans with controlled repository/channel doubles), owner-caller guards, source clients, and actor selection using an isolated fixture. They were not run in this extraction and do not establish database or live owner-RPC execution. Entity consumer wiring and `PLAY`/`LOOK` activation remain outside this slice; `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java index dda265fb34..e14e9cb902 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfiguration.java @@ -4,10 +4,12 @@ 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.gamesession.client.CanonicalGameplayRosterClient; import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionService; import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; import org.springframework.beans.factory.ObjectProvider; @@ -74,4 +76,13 @@ CanonicalPublishedPlayerRouteReadService canonicalPublishedPlayerRouteReadServic return new CanonicalPublishedPlayerRouteReadService( workloadNamespace, routeReader, catalogRepository, launchRepository, policyClient); } + + @Bean + CanonicalGameplayRosterSelectionService canonicalGameplayRosterSelectionService( + CanonicalPlayerRouteReadService routeReader, + CanonicalPublishedPlayerRouteReadService publishedRouteReader, + CanonicalGameplayRosterClient rosterClient) { + return new CanonicalGameplayRosterSelectionService( + routeReader, publishedRouteReader, rosterClient); + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java new file mode 100644 index 0000000000..1db9799b5c --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.StatusRuntimeException; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.command.text.CanonicalGameplayActorSelection; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Non-admitting composition of the current published route and Entity's preseeded roster reads. The + * execution context must already have been constructed from authenticated Game Session state; this + * unsigned scope carrier is not authentication, Account eligibility, or gameplay authority. + */ +public final class CanonicalGameplayRosterSelectionService { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final CanonicalPlayerRouteReadService routeReader; + private final CanonicalPublishedPlayerRouteReadService publishedRouteReader; + private final CanonicalGameplayRosterClient rosterClient; + + public CanonicalGameplayRosterSelectionService( + CanonicalPlayerRouteReadService routeReader, + CanonicalPublishedPlayerRouteReadService publishedRouteReader, + CanonicalGameplayRosterClient rosterClient) { + this.routeReader = Objects.requireNonNull(routeReader, "routeReader"); + this.publishedRouteReader = + Objects.requireNonNull(publishedRouteReader, "publishedRouteReader"); + this.rosterClient = Objects.requireNonNull(rosterClient, "rosterClient"); + } + + /** + * Reads a route-bound roster, accepts only an optional one-based ordinal, and obtains Entity's + * original selected-assignment reference. No result from this method authorizes or activates + * gameplay. + */ + public Result select(PlayerExecutionContext authenticatedContext, String selector) { + if (hasAmbientTransaction()) { + return new Denied(Denial.AMBIENT_TRANSACTION); + } + Optional accountUuid = validateContext(authenticatedContext); + if (accountUuid.isEmpty()) { + return new Denied(Denial.INVALID_CONTEXT); + } + + CanonicalPublishedPlayerRoute current; + try { + CanonicalPlayableTarget selectedTarget = + routeReader.readCurrentTarget(parseCanonicalUuid(authenticatedContext.getTenantId())); + if (selectedTarget == null || !matchesContext(authenticatedContext, selectedTarget)) { + return new Denied(Denial.ROUTE_MISMATCH); + } + current = publishedRouteReader.readCurrent(selectedTarget); + if (current == null || !matchesContext(authenticatedContext, current.route())) { + return new Denied(Denial.ROUTE_MISMATCH); + } + } catch (RuntimeException unavailableOrInvalid) { + return new Denied(routeFailure(unavailableOrInvalid)); + } + + CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot; + try { + snapshot = rosterClient.listPreseededRoster(current, authenticatedContext); + } catch (StatusRuntimeException unavailable) { + return new Denied(Denial.ROSTER_UNAVAILABLE); + } catch (RuntimeException invalidOrUnavailable) { + return new Denied(Denial.INVALID_ROSTER_PROOF); + } + if (snapshot == null) { + return new Denied(Denial.INVALID_ROSTER_PROOF); + } + + Denial listFreshnessFailure = requireExactCurrentRoute(current); + if (listFreshnessFailure != null) { + return new Denied(listFreshnessFailure); + } + + Optional validated = + CanonicalGameplayActorSelection.validate(snapshot, accountUuid.orElseThrow(), current); + if (validated.isEmpty()) { + return new Denied(Denial.INVALID_ROSTER_PROOF); + } + + CanonicalGameplayActorSelection.SelectionResult selection = + CanonicalGameplayActorSelection.select(validated.orElseThrow(), selector); + if (selection instanceof CanonicalGameplayActorSelection.SelectionRequired required) { + return new SelectionRequired(required.choices()); + } + if (selection instanceof CanonicalGameplayActorSelection.Denied denied) { + return new Denied(mapSelectionDenial(denied.reason())); + } + + CanonicalGameplayActorSelection.Selected selected = + (CanonicalGameplayActorSelection.Selected) selection; + PlayerExecutionContext selectedContext = + authenticatedContext.toBuilder() + .setRequestId(UUID.randomUUID().toString()) + .setCharacterId(selected.characterUuid().toString()) + .build(); + + CanonicalGameplayRosterClient.VerifiedPreseededAssignment ownerReference; + try { + ownerReference = rosterClient.readSelectedPreseededAssignment(snapshot, selectedContext); + } catch (StatusRuntimeException unavailable) { + return new Denied(Denial.ASSIGNMENT_UNAVAILABLE); + } catch (RuntimeException invalidOrUnavailable) { + return new Denied(Denial.INVALID_ASSIGNMENT_PROOF); + } + if (!matchesOwnerReference(ownerReference, selected)) { + return new Denied(Denial.INVALID_ASSIGNMENT_PROOF); + } + + Denial assignmentFreshnessFailure = requireExactCurrentRoute(current); + if (assignmentFreshnessFailure != null) { + return new Denied(assignmentFreshnessFailure); + } + return new SelectedOwnerReference(ownerReference, selected.displayName(), selected.ordinal()); + } + + private Denial requireExactCurrentRoute(CanonicalPublishedPlayerRoute expected) { + try { + CanonicalPublishedPlayerRoute current = publishedRouteReader.readCurrent(expected.route()); + return expected.equals(current) ? null : Denial.ROUTE_CHANGED; + } catch (RuntimeException unavailableOrInvalid) { + return routeFailure(unavailableOrInvalid); + } + } + + private static Denial routeFailure(RuntimeException failure) { + if (failure instanceof CanonicalPublishedPlayerRouteReadService.StaleAuthorityException) { + return Denial.ROUTE_CHANGED; + } + if (failure instanceof CanonicalPlayerRouteReadService.ReadUnavailableException + || failure instanceof CanonicalPublishedPlayerRouteReadService.StorageUnavailableException + || failure + instanceof CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + || failure instanceof StatusRuntimeException) { + return Denial.ROUTE_UNAVAILABLE; + } + return Denial.INVALID_ROUTE_PROOF; + } + + private static Optional validateContext(PlayerExecutionContext context) { + if (context == null || !context.getUnknownFields().asMap().isEmpty()) { + return Optional.empty(); + } + try { + UUID accountUuid = parseCanonicalUuid(context.getAccountId()); + parseCanonicalUuid(context.getSessionId()); + parseCanonicalUuid(context.getRequestId()); + parseCanonicalUuid(context.getTenantId()); + parseCanonicalUuid(context.getRealmId()); + parseCanonicalUuid(context.getPlayableStateNamespaceId()); + parseCanonicalUuid(context.getGameInstanceId()); + if ((!"SHARED".equals(context.getPlayableStateScope()) + && !"ISOLATED".equals(context.getPlayableStateScope())) + || !context.getCharacterId().isEmpty()) { + return Optional.empty(); + } + return Optional.of(accountUuid); + } catch (IllegalArgumentException malformed) { + return Optional.empty(); + } + } + + private static UUID parseCanonicalUuid(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Canonical UUID is required"); + } + UUID parsed = UUID.fromString(value); + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical UUID is malformed"); + } + return parsed; + } + + private static boolean matchesContext( + PlayerExecutionContext context, CanonicalPlayableTarget route) { + return context.getTenantId().equals(route.canonicalTenantId().toString()) + && context.getRealmId().equals(route.realmId().toString()) + && context.getPlayableStateNamespaceId().equals(route.playableStateNamespaceId().toString()) + && context.getPlayableStateScope().equals(route.playableStateScope()) + && context.getGameInstanceId().equals(route.canonicalGameInstanceId().toString()); + } + + private static boolean matchesOwnerReference( + CanonicalGameplayRosterClient.VerifiedPreseededAssignment ownerReference, + CanonicalGameplayActorSelection.Selected selected) { + return ownerReference != null + && ownerReference.canonicalAccountUuid().equals(selected.canonicalAccountUuid()) + && ownerReference.selectedCharacterUuid().equals(selected.characterUuid()) + && ownerReference.target().equals(selected.target()) + && ownerReference.rosterSnapshotUuid().equals(selected.rosterSnapshotUuid()) + && ownerReference.rosterSnapshotDigest().equals(selected.rosterSnapshotDigest()); + } + + private static Denial mapSelectionDenial(CanonicalGameplayActorSelection.Denial reason) { + return switch (reason) { + case INVALID_SNAPSHOT -> Denial.INVALID_ROSTER_PROOF; + case NO_PRESEEDED_ACTOR -> Denial.NO_PRESEEDED_ACTOR; + case INVALID_SELECTOR -> Denial.INVALID_SELECTOR; + case SELECTOR_OUT_OF_RANGE -> Denial.SELECTOR_OUT_OF_RANGE; + }; + } + + private static boolean hasAmbientTransaction() { + return TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive(); + } + + public sealed interface Result permits SelectedOwnerReference, SelectionRequired, Denied {} + + /** + * Entity's original committed owner reference, still only source evidence for later revalidation. + */ + public record SelectedOwnerReference( + CanonicalGameplayRosterClient.VerifiedPreseededAssignment ownerReference, + String displayName, + int ordinal) + implements Result { + public SelectedOwnerReference { + Objects.requireNonNull(ownerReference, "ownerReference"); + Objects.requireNonNull(displayName, "displayName"); + if (ordinal < 1) { + throw new IllegalArgumentException("ordinal must be one-based"); + } + } + } + + public record SelectionRequired(List choices) + implements Result { + public SelectionRequired { + choices = List.copyOf(Objects.requireNonNull(choices, "choices")); + } + } + + public record Denied(Denial reason) implements Result { + public Denied { + Objects.requireNonNull(reason, "reason"); + } + } + + public enum Denial { + AMBIENT_TRANSACTION, + INVALID_CONTEXT, + ROUTE_UNAVAILABLE, + INVALID_ROUTE_PROOF, + ROUTE_MISMATCH, + ROUTE_CHANGED, + ROSTER_UNAVAILABLE, + INVALID_ROSTER_PROOF, + NO_PRESEEDED_ACTOR, + INVALID_SELECTOR, + SELECTOR_OUT_OF_RANGE, + ASSIGNMENT_UNAVAILABLE, + INVALID_ASSIGNMENT_PROOF + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java index 8435699239..9b4d1bf107 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java @@ -18,11 +18,13 @@ 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.gamesession.client.CanonicalGameplayRosterClient; import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; import net.firedevops.firemud.gamesession.config.CanonicalPlayerRouteReadConfiguration; import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionService; import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; import org.junit.jupiter.api.Test; @@ -41,6 +43,7 @@ void defaultConfigurationLeavesCanonicalRosterRouteSourceUnregistered() { assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); }); } @@ -55,6 +58,7 @@ void explicitlyDisabledConfigurationLeavesCanonicalRosterRouteSourceUnregistered assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); }); } @@ -83,6 +87,8 @@ void enabledConfigurationComposesRealRouteSourcesWithFileBackedTlsAndExactTarget .withBean(ServiceEndpointsProperties.class, () -> endpoints) .withBean(CommonGrpcClientProperties.class, () -> tlsProperties) .withBean(GrpcChannelFactory.class, () -> channelFactory) + .withBean( + CanonicalGameplayRosterClient.class, () -> mock(CanonicalGameplayRosterClient.class)) .withBean( GameSessionCanonicalRealmCatalogRepository.class, () -> mock(GameSessionCanonicalRealmCatalogRepository.class)) @@ -101,6 +107,7 @@ void enabledConfigurationComposesRealRouteSourcesWithFileBackedTlsAndExactTarget assertThat(context).hasSingleBean(GameDesignPublishedRealmPolicyClient.class); assertThat(context).hasSingleBean(CanonicalPlayerRouteReadService.class); assertThat(context).hasSingleBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).hasSingleBean(CanonicalGameplayRosterSelectionService.class); assertThat( Mockito.mockingDetails( context.getBean(GameDesignPublishedRealmPolicyClient.class)) @@ -141,6 +148,8 @@ void enabledConfigurationRejectsInvalidNamespaceBeforeOpeningChannel(@TempDir Pa .withBean(ServiceEndpointsProperties.class, ServiceEndpointsProperties::new) .withBean(CommonGrpcClientProperties.class, () -> tlsProperties) .withBean(GrpcChannelFactory.class, () -> channelFactory) + .withBean( + CanonicalGameplayRosterClient.class, () -> mock(CanonicalGameplayRosterClient.class)) .withBean( GameSessionCanonicalRealmCatalogRepository.class, () -> mock(GameSessionCanonicalRealmCatalogRepository.class)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java new file mode 100644 index 0000000000..1087168c04 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -0,0 +1,659 @@ +package unit.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +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.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +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.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.command.text.CanonicalGameplayActorSelection; +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.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +class CanonicalGameplayRosterSelectionServiceTest { + private static final UUID ACCOUNT = uuid("66666666-6666-4666-8666-666666666666"); + private static final UUID FIRST_ACTOR = uuid("77777777-7777-4777-8777-777777777777"); + private static final UUID SECOND_ACTOR = uuid("99999999-9999-4999-8999-999999999999"); + private static final UUID SNAPSHOT = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID ASSIGNMENT = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + + @Test + void returnsMenuForMultipleActorsThenReadsOnlyTheSelectedOrdinalOwnerReference() + throws Exception { + var harness = harness(twoActors()); + + var menu = + harness + .service() + .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null); + + assertThat(menu) + .isEqualTo( + new CanonicalGameplayRosterSelectionService.SelectionRequired( + List.of( + new CanonicalGameplayActorSelection.Choice(1, "Pilot One"), + new CanonicalGameplayActorSelection.Choice(2, "Pilot Two")))); + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + + PlayerExecutionContext input = context(harness.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"); + var selected = harness.service().select(input, "2"); + + assertThat(selected) + .isInstanceOfSatisfying( + CanonicalGameplayRosterSelectionService.SelectedOwnerReference.class, + result -> { + assertThat(result.displayName()).isEqualTo("Pilot Two"); + assertThat(result.ordinal()).isEqualTo(2); + assertThat(result.ownerReference().canonicalAccountUuid()).isEqualTo(ACCOUNT); + assertThat(result.ownerReference().selectedCharacterUuid()).isEqualTo(SECOND_ACTOR); + assertThat(result.ownerReference().assignmentOperationId()).isEqualTo(ASSIGNMENT); + assertThat(result.ownerReference().rosterSnapshotUuid()).isEqualTo(SNAPSHOT); + }); + + var requestCaptor = + org.mockito.ArgumentCaptor.forClass(CanonicalGameplayRosterSelectedAssignmentRequest.class); + verify(harness.stub()).readSelectedPreseededAssignment(requestCaptor.capture()); + PlayerExecutionContext selectedContext = requestCaptor.getValue().getPlayerExecutionContext(); + assertThat(selectedContext.getRequestId()).isNotEqualTo(input.getRequestId()); + assertThat(selectedContext.getAccountId()).isEqualTo(input.getAccountId()); + assertThat(selectedContext.getSessionId()).isEqualTo(input.getSessionId()); + assertThat(selectedContext.getTenantId()).isEqualTo(input.getTenantId()); + assertThat(selectedContext.getRealmId()).isEqualTo(input.getRealmId()); + assertThat(selectedContext.getPlayableStateNamespaceId()) + .isEqualTo(input.getPlayableStateNamespaceId()); + assertThat(selectedContext.getPlayableStateScope()).isEqualTo(input.getPlayableStateScope()); + assertThat(selectedContext.getGameInstanceId()).isEqualTo(input.getGameInstanceId()); + assertThat(selectedContext.getCharacterId()).isEqualTo(SECOND_ACTOR.toString()); + assertThat(requestCaptor.getValue().getSelectedCharacterUuid()) + .isEqualTo(SECOND_ACTOR.toString()); + + verify(harness.catalogRepository(), atLeastOnce()) + .readUniqueVisiblePublicProduction("test", harness.route().canonicalTenantId()); + verify(harness.admissionRepository(), atLeastOnce()) + .readCurrentOpenSnapshotForRealm( + "test", harness.route().canonicalTenantId(), harness.route().realmId()); + verify(harness.launchRepository(), atLeastOnce()) + .readForInitialAdmission( + "test", + harness.route().canonicalTenantId(), + harness.route().realmId(), + harness.route().canonicalGameInstanceId()); + verify(harness.policyClient(), atLeastOnce()) + .listPublishedRealmEntryPolicies( + harness.route().canonicalTenantId(), harness.route().canonicalVersionId()); + verify(harness.stub(), atLeastOnce()).listPreseededRoster(any()); + verify(harness.stub(), atLeastOnce()).withDeadlineAfter(5L, TimeUnit.SECONDS); + verifyNoMoreInteractions( + harness.catalogRepository(), + harness.admissionRepository(), + harness.launchRepository(), + harness.policyClient(), + harness.stub()); + } + + @Test + void deniesTenantNamespaceRealmAndInstanceContextMismatchesBeforeEntityRead() throws Exception { + var harness = harness(oneActor()); + PlayerExecutionContext valid = context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + + assertDenied( + harness + .service() + .select( + valid.toBuilder() + .setPlayableStateNamespaceId( + uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(), + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + assertDenied( + harness + .service() + .select( + valid.toBuilder() + .setGameInstanceId(uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(), + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + assertDenied( + harness + .service() + .select( + valid.toBuilder() + .setRealmId(uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(), + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + + verify(harness.stub(), never()).listPreseededRoster(any()); + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsAnEntitySnapshotWithAnotherAccountOrTargetBeforeSelectedRead() throws Exception { + var accountMismatch = harness(oneActor()); + doAnswer( + invocation -> + rosterResponse( + invocation.getArgument(0), + uuid("12121212-1212-4212-8212-121212121212"), + oneActor())) + .when(accountMismatch.stub()) + .listPreseededRoster(any()); + + assertDenied( + accountMismatch + .service() + .select(context(accountMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + verify(accountMismatch.stub(), never()).readSelectedPreseededAssignment(any()); + + var targetMismatch = harness(oneActor()); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + CanonicalGameplayRosterTarget changedTarget = + request.getExpectedTarget().toBuilder() + .setGameInstanceUuid(uuid("12121212-1212-4212-8212-121212121212").toString()) + .build(); + return rosterResponse(request, ACCOUNT, changedTarget, oneActor()); + }) + .when(targetMismatch.stub()) + .listPreseededRoster(any()); + + assertDenied( + targetMismatch + .service() + .select(context(targetMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + verify(targetMismatch.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void returnsExplicitSelectionAndSelectorDenialsWithoutAssignmentReads() throws Exception { + var multiple = harness(twoActors()); + assertThat( + multiple + .service() + .select(context(multiple.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null)) + .isInstanceOf(CanonicalGameplayRosterSelectionService.SelectionRequired.class); + assertDenied( + multiple + .service() + .select(context(multiple.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), "Pilot Two"), + CanonicalGameplayRosterSelectionService.Denial.INVALID_SELECTOR); + verify(multiple.stub(), never()).readSelectedPreseededAssignment(any()); + + var empty = harness(List.of()); + assertDenied( + empty + .service() + .select(context(empty.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + CanonicalGameplayRosterSelectionService.Denial.NO_PRESEEDED_ACTOR); + verify(empty.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsMovedRouteAfterRosterAndAfterAssignmentNetworkEvidence() throws Exception { + var changedAfterList = harness(oneActor()); + configureRouteMovement(changedAfterList, 3); + assertDenied( + changedAfterList + .service() + .select( + context(changedAfterList.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + verify(changedAfterList.stub(), never()).readSelectedPreseededAssignment(any()); + + var changedAfterAssignment = harness(oneActor()); + configureRouteMovement(changedAfterAssignment, 5); + assertDenied( + changedAfterAssignment + .service() + .select( + context(changedAfterAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + verify(changedAfterAssignment.stub()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsChangedAssignmentSnapshotAndUnavailableEntityBackend() throws Exception { + var changedSnapshot = harness(oneActor()); + doAnswer( + invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return assignmentResponse(request, true); + }) + .when(changedSnapshot.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + changedSnapshot + .service() + .select(context(changedSnapshot.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); + + var unavailable = harness(oneActor()); + doThrow(Status.UNAVAILABLE.withDescription("Entity offline").asRuntimeException()) + .when(unavailable.stub()) + .listPreseededRoster(any()); + assertDenied( + unavailable + .service() + .select(context(unavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); + verify(unavailable.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void deniesAmbientTransactionBeforeAnyRouteOrOwnerRead() throws Exception { + var harness = harness(oneActor()); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertDenied( + harness + .service() + .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + CanonicalGameplayRosterSelectionService.Denial.AMBIENT_TRANSACTION); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions( + harness.catalogRepository(), + harness.admissionRepository(), + harness.launchRepository(), + harness.policyClient(), + harness.stub()); + } + + private static TestHarness harness(List actors) + throws Exception { + CanonicalPublishedPlayerRoute published = + PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + CanonicalPlayableTarget route = published.route(); + PublishedRealmEntryPolicySetEvidence policySet = published.policySetEvidence(); + TargetProof policyTarget = policySet.target(); + + UUID sourceRegistrationRequest = uuid("abababab-abab-4bab-8bab-abababababab"); + UUID sourceOperation = uuid("acacacac-acac-4cac-8cac-acacacacacac"); + String sourceRequestDigest = + AuthoredWorldSourceDigest.requestDigest( + route.targetNamespace(), + sourceRegistrationRequest, + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.worldDisplayName()); + String sourceEvidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + route.targetNamespace(), + sourceRegistrationRequest, + sourceOperation, + sourceRequestDigest, + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.worldDisplayName(), + policyTarget.sourceGameRowId(), + policyTarget.sourceGameTenantKey(), + policyTarget.sourceProvenanceKind()); + AuthoredWorldSourceEvidence source = + new AuthoredWorldSourceEvidence( + 1, + route.targetNamespace(), + sourceRegistrationRequest, + sourceOperation, + sourceRequestDigest, + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.worldDisplayName(), + policyTarget.sourceGameRowId(), + policyTarget.sourceGameTenantKey(), + policyTarget.sourceProvenanceKind(), + sourceEvidenceDigest); + IntakeReceipt receipt = mock(IntakeReceipt.class); + when(receipt.source()).thenReturn(source); + CanonicalRealmCatalogSnapshot catalog = + new CanonicalRealmCatalogSnapshot( + route.targetNamespace(), + route.canonicalTenantId(), + "tenant-key", + route.worldSlug(), + route.realmId(), + route.realmSlug(), + route.realmDisplayName(), + true, + true, + route.playableStateScope(), + route.playableStateNamespaceId(), + route.characterCreationPolicy(), + route.catalogRevision(), + uuid("adadadad-adad-4dad-8dad-adadadadadad"), + "a".repeat(64), + "sha256:" + "b".repeat(64), + receipt); + + var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); + var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); + var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + when(catalogRepository.readUniqueVisiblePublicProduction( + route.targetNamespace(), route.canonicalTenantId())) + .thenReturn(Optional.of(catalog)); + when(admissionRepository.readCurrentOpenSnapshotForRealm( + route.targetNamespace(), route.canonicalTenantId(), route.realmId())) + .thenReturn(currentOpenSnapshot(route)); + + var descriptor = mock(AuthoredWorldLaunchDescriptorEvidence.class); + var release = mock(AuthoredWorldReleaseAttestationEvidence.class); + var binding = mock(CompleteLaunchBindingEvidence.class); + when(binding.descriptor()).thenReturn(descriptor); + when(binding.releaseAttestation()).thenReturn(release); + when(descriptor.targetNamespace()).thenReturn(route.targetNamespace()); + when(descriptor.canonicalTenantId()).thenReturn(route.canonicalTenantId()); + when(descriptor.worldSlug()).thenReturn(route.worldSlug()); + when(descriptor.authoredWorldSourceOperationId()).thenReturn(sourceOperation); + when(descriptor.authoredWorldSourceEvidenceDigest()).thenReturn(sourceEvidenceDigest); + when(descriptor.versionId()).thenReturn(route.runtimeVersionId()); + when(descriptor.versionStateEpoch()).thenReturn(policySet.publicationVersionStateEpoch()); + when(descriptor.publishedReleaseBundleRef()).thenReturn(policySet.publishedReleaseBundleRef()); + when(descriptor.controlPlaneRequestId()).thenReturn("launch-request"); + when(descriptor.launchDescriptorId()).thenReturn("launch-descriptor"); + when(release.targetNamespace()).thenReturn(route.targetNamespace()); + when(release.canonicalTenantId()).thenReturn(route.canonicalTenantId()); + when(release.canonicalVersionId()).thenReturn(route.canonicalVersionId()); + when(release.worldSlug()).thenReturn(route.worldSlug()); + when(release.authoredWorldSourceOperationId()).thenReturn(sourceOperation); + when(release.authoredWorldSourceEvidenceDigest()).thenReturn(sourceEvidenceDigest); + when(release.publishedReleaseBundleRef()).thenReturn(policySet.publishedReleaseBundleRef()); + when(release.versionStateEpoch()).thenReturn(policySet.publicationVersionStateEpoch()); + when(release.commitId()).thenReturn(policySet.sourceCommitId().toString()); + when(release.publishWorkflowId()).thenReturn(policySet.publishWorkflowId()); + when(release.manifestHash()).thenReturn(policySet.manifestHash()); + + CanonicalGameInstanceLaunchAssociation association = + mock(CanonicalGameInstanceLaunchAssociation.class); + when(association.targetNamespace()).thenReturn(route.targetNamespace()); + when(association.gameSessionTenantId()).thenReturn(route.gameSessionTenantId()); + when(association.tenantAssociationOperationId()) + .thenReturn(uuid("aeaeaeae-aeae-4eae-8eae-aeaeaeaeaeae")); + when(association.canonicalTenantId()).thenReturn(route.canonicalTenantId()); + when(association.gameInstanceUuid()).thenReturn(route.canonicalGameInstanceId()); + when(association.worldSlug()).thenReturn(route.worldSlug()); + when(association.playableStateNamespaceId()).thenReturn(route.playableStateNamespaceId()); + when(association.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(association.publicProduction()).thenReturn(true); + when(association.controlPlaneRequestId()).thenReturn("launch-request"); + when(association.launchDescriptorId()).thenReturn("launch-descriptor"); + when(association.capturedStartingRowVersion()).thenReturn(1L); + when(association.currentRowVersion()).thenReturn(2L); + when(association.launchBindingEvidence()).thenReturn(binding); + when(association.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + CanonicalInitialAdmissionLaunchTarget launch = + mock(CanonicalInitialAdmissionLaunchTarget.class); + when(launch.association()).thenReturn(association); + when(launch.realmId()).thenReturn(route.realmId()); + when(launch.gameInstanceId()).thenReturn(route.gameInstanceId()); + when(launch.runtimeVersionId()).thenReturn(route.runtimeVersionId()); + when(launch.canonicalVersionId()).thenReturn(route.canonicalVersionId()); + when(launchRepository.readForInitialAdmission( + route.targetNamespace(), + route.canonicalTenantId(), + route.realmId(), + route.canonicalGameInstanceId())) + .thenReturn(Optional.of(launch)); + + var routeReader = + new CanonicalPlayerRouteReadService( + route.targetNamespace(), catalogRepository, admissionRepository, launchRepository); + var policyClient = mock(GameDesignPublishedRealmPolicyClient.class); + when(policyClient.listPublishedRealmEntryPolicies( + route.canonicalTenantId(), route.canonicalVersionId())) + .thenReturn(policySet); + var publishedRouteReader = + new CanonicalPublishedPlayerRouteReadService( + route.targetNamespace(), + routeReader, + catalogRepository, + launchRepository, + policyClient); + + var stub = + mock(CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.listPreseededRoster(any())) + .thenAnswer(invocation -> rosterResponse(invocation.getArgument(0), ACCOUNT, actors)); + when(stub.readSelectedPreseededAssignment(any())) + .thenAnswer(invocation -> assignmentResponse(invocation.getArgument(0), false)); + CanonicalGameplayRosterClient rosterClient = rosterClient(stub); + var service = + new CanonicalGameplayRosterSelectionService( + routeReader, publishedRouteReader, rosterClient); + return new TestHarness( + service, + route, + catalogRepository, + admissionRepository, + launchRepository, + policyClient, + stub); + } + + private static void configureRouteMovement(TestHarness harness, int initialReadCount) { + CanonicalInitialAdmissionOwnerProof initialProof = proof(harness.route(), 7L); + CanonicalInitialAdmissionOwnerProof changedProof = proof(harness.route(), 8L); + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot initial = + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot( + initialProof, harness.route().admissionPointerSnapshotDigest()); + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot changed = + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(changedProof, "e".repeat(64)); + AtomicInteger reads = new AtomicInteger(); + when(harness + .admissionRepository() + .readCurrentOpenSnapshotForRealm( + harness.route().targetNamespace(), + harness.route().canonicalTenantId(), + harness.route().realmId())) + .thenAnswer(invocation -> reads.incrementAndGet() <= initialReadCount ? initial : changed); + } + + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentOpenSnapshot( + CanonicalPlayableTarget route) { + return new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot( + proof(route, route.pointerVersion()), route.admissionPointerSnapshotDigest()); + } + + private static CanonicalInitialAdmissionOwnerProof proof( + CanonicalPlayableTarget route, long pointerVersion) { + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + route.initialAdmissionRequestId(), + route.initialAdmissionRequestDigest(), + route.targetNamespace(), + route.canonicalTenantId(), + route.worldSlug(), + route.realmId(), + route.playableStateNamespaceId(), + route.playableStateScope(), + route.canonicalGameInstanceId(), + route.canonicalVersionId(), + route.activeWorldEpoch(), + route.catalogRevision(), + route.initialAdmissionOriginKind(), + route.expectedPriorPointerVersion(), + route.holdId(), + route.holdFence(), + route.holdBindingDigest(), + pointerVersion, + route.auditEventId(), + route.ownerProofDigest(), + false, + route.ownerProofTerminalAt()); + } + + private static CanonicalGameplayRosterResponse rosterResponse( + CanonicalGameplayRosterRequest request, + UUID account, + List actors) + throws Exception { + return rosterResponse(request, account, request.getExpectedTarget(), actors); + } + + private static CanonicalGameplayRosterResponse rosterResponse( + CanonicalGameplayRosterRequest request, + UUID account, + CanonicalGameplayRosterTarget target, + List actors) + throws Exception { + Method calculateDigest = + CanonicalGameplayRosterClient.class.getDeclaredMethod( + "calculateSnapshotDigest", UUID.class, CanonicalGameplayRosterTarget.class, List.class); + calculateDigest.setAccessible(true); + String digest = (String) calculateDigest.invoke(null, account, target, actors); + var builder = + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(account.toString()) + .setTarget(target) + .setSnapshotUuid(SNAPSHOT.toString()) + .setSnapshotDigest(digest); + for (CanonicalGameplayRosterClient.RosterActor actor : actors) { + builder.addActors( + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(actor.characterUuid().toString()) + .setDisplayName(actor.displayName()) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER)); + } + return builder.build(); + } + + private static CanonicalGameplayRosterSelectedAssignmentResponse assignmentResponse( + CanonicalGameplayRosterSelectedAssignmentRequest request, boolean changedSnapshot) { + CanonicalGameplayRosterSelectedAssignmentResponse.Builder response = + CanonicalGameplayRosterSelectedAssignmentResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshot(request.getExpectedSnapshot()) + .setAssignmentUuid(ASSIGNMENT.toString()) + .setIntentDigest("c".repeat(64)); + if (changedSnapshot) { + response.setSnapshot( + request.getExpectedSnapshot().toBuilder() + .setSnapshotUuid(uuid("12121212-1212-4212-8212-121212121212").toString())); + } + return response.build(); + } + + private static CanonicalGameplayRosterClient rosterClient( + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("game-session-client.crt"); + tls.setPrivateKey("game-session-client.key"); + tls.setCaCert("entity-management-ca.crt"); + var client = + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "test"); + Field stubField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + stubField.setAccessible(true); + stubField.set(client, stub); + return client; + } + + private static PlayerExecutionContext context(CanonicalPlayableTarget route, String requestId) { + return PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT.toString()) + .setTenantId(route.canonicalTenantId().toString()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setGameInstanceId(route.canonicalGameInstanceId().toString()) + .setCharacterId("") + .setSessionId("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setRealmId(route.realmId().toString()) + .setRequestId(requestId) + .setPlayableStateScope(route.playableStateScope()) + .build(); + } + + private static List oneActor() { + return List.of(new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One")); + } + + private static List twoActors() { + return List.of( + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One"), + new CanonicalGameplayRosterClient.RosterActor(SECOND_ACTOR, "Pilot Two")); + } + + private static void assertDenied( + CanonicalGameplayRosterSelectionService.Result result, + CanonicalGameplayRosterSelectionService.Denial reason) { + assertThat(result).isEqualTo(new CanonicalGameplayRosterSelectionService.Denied(reason)); + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } + + private record TestHarness( + CanonicalGameplayRosterSelectionService service, + CanonicalPlayableTarget route, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + CanonicalInitialAdmissionRepository admissionRepository, + CanonicalGameInstanceLaunchAssociationRepository launchRepository, + GameDesignPublishedRealmPolicyClient policyClient, + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) {} +} From 3e2e406a2c04178632a18bc9b3c85b79e5f17d10 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:04:37 +1300 Subject: [PATCH 13/34] Align roster owner adapter fixture with sealed policy namespace --- .../impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java index a578ef08e9..5eb294e5bc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java @@ -32,7 +32,7 @@ import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; class CanonicalGameplayRosterOwnerReadGrpcAdapterTest { - private static final String NAMESPACE = "gameplay"; + private static final String NAMESPACE = "test"; private static final String ENTITY_SERVICE = "entity-management-service"; private static final UUID ACCOUNT = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); From 69366253fe4b396159c81f5a185d14078a3c95cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:48:41 +1300 Subject: [PATCH 14/34] Distinguish canonical launch wire from target plugin extensions --- .../game-design-service/game-templates.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 5fe7c4e939..a47705f895 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -218,12 +218,14 @@ Required deterministic failure vocabulary for the first implementation slice: These are application-level launch-preflight outcomes, not transport failures. Retries for the same `controlPlaneRequestId` must return the same deterministic business result until callers intentionally start a new launch attempt with a new `controlPlaneRequestId`. -Illustrative control-plane schema: +The current authored-world launch-binding wire contract is defined in the [Game Design API contract](./api-contracts.md#authored-world-launch-binding) and [Game Design proto](../../../../protos/game-design/v1/game_design_service.proto). `ResolveLaunchDescriptorRequest` is source-qualified by `canonical_tenant_id`, `world_slug`, `authored_world_source_operation_id`, and `expected_authored_world_source_evidence_digest`; its response carries the complete authored-world binding evidence. Plugin-selection and named rollback-target fields are not part of this current wire contract. -- Request: `ResolveLaunchDescriptorRequest { tenantId, gameTemplateId, controlPlaneRequestId, requestedRuntimeFlags?, requestedScriptPatchVersion?, requestedPluginSelection?: { mode: EMPTY | EXPLICIT | REUSE_ROLLBACK_TARGET, enabledPluginVersions[]? { pluginId, pluginVersionId } }, sourceVersionId?, targetVersionId?, rollbackTargetLaunchDescriptorId? }` -- Response: `ResolveLaunchDescriptorResponse { launchDescriptorId, tenantId, gameTemplateId, versionId, scriptPatchVersion (nullable; explicit null when no patch is pinned), pluginSelectionMode, enabledPluginVersions[] { pluginId, pluginVersionId }, runtimeFlags, generationConfigRevision, versionStateEpoch, remapSetId?, publishedReleaseBundleRef }` +Target-only plugin-selection and rollback illustration (not the current wire contract): -The exact transport schema may evolve, but every implementation must preserve the same contract shape: +- Request extension: `requestedPluginSelection?: { mode: EMPTY | EXPLICIT | REUSE_ROLLBACK_TARGET, enabledPluginVersions[]? { pluginId, pluginVersionId } }`, `rollbackTargetLaunchDescriptorId?`. +- Response extension: `pluginSelectionMode`, `enabledPluginVersions[] { pluginId, pluginVersionId }`. + +These target-only fields do not replace or relax the current authored-world source binding. If implemented, their transport must preserve the following plugin-selection semantics: - request fields identify the template, the launch attempt identity, and any caller-supplied runtime overrides that are allowed to participate in deterministic resolution; - response fields are the immutable resolved values consumed by launch-time workflows; From b7597d872f7af7ddfdaa42476454072d0f1c08c2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:03:42 +1300 Subject: [PATCH 15/34] Bind roster ordinal selections to the displayed snapshot --- ...nonicalGameplayRosterSelectionService.java | 46 ++++- ...calGameplayRosterSelectionServiceTest.java | 172 ++++++++++++++++-- 2 files changed, 195 insertions(+), 23 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java index 1db9799b5c..c4e43044c3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java @@ -5,6 +5,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.regex.Pattern; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; import net.firedevops.firemud.gamesession.command.text.CanonicalGameplayActorSelection; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; @@ -19,6 +20,7 @@ */ public final class CanonicalGameplayRosterSelectionService { private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern SNAPSHOT_DIGEST = Pattern.compile("[0-9a-f]{64}"); private final CanonicalPlayerRouteReadService routeReader; private final CanonicalPublishedPlayerRouteReadService publishedRouteReader; @@ -36,10 +38,14 @@ public CanonicalGameplayRosterSelectionService( /** * Reads a route-bound roster, accepts only an optional one-based ordinal, and obtains Entity's - * original selected-assignment reference. No result from this method authorizes or activates - * gameplay. + * original selected-assignment reference. An explicit ordinal must carry the identity returned + * with its menu so a refreshed roster cannot silently rebind that choice. No result from this + * method authorizes or activates gameplay. */ - public Result select(PlayerExecutionContext authenticatedContext, String selector) { + public Result select( + PlayerExecutionContext authenticatedContext, + String selector, + SelectionMenuIdentity expectedMenuIdentity) { if (hasAmbientTransaction()) { return new Denied(Denial.AMBIENT_TRANSACTION); } @@ -89,12 +95,23 @@ public Result select(PlayerExecutionContext authenticatedContext, String selecto CanonicalGameplayActorSelection.SelectionResult selection = CanonicalGameplayActorSelection.select(validated.orElseThrow(), selector); if (selection instanceof CanonicalGameplayActorSelection.SelectionRequired required) { - return new SelectionRequired(required.choices()); + return new SelectionRequired( + required.choices(), + new SelectionMenuIdentity(snapshot.snapshotUuid(), snapshot.snapshotDigest())); } if (selection instanceof CanonicalGameplayActorSelection.Denied denied) { return new Denied(mapSelectionDenial(denied.reason())); } + if (selector != null && !selector.isBlank()) { + if (expectedMenuIdentity == null) { + return new Denied(Denial.MISSING_MENU_IDENTITY); + } + if (!expectedMenuIdentity.matches(snapshot)) { + return new Denied(Denial.STALE_MENU_IDENTITY); + } + } + CanonicalGameplayActorSelection.Selected selected = (CanonicalGameplayActorSelection.Selected) selection; PlayerExecutionContext selectedContext = @@ -232,10 +249,27 @@ public record SelectedOwnerReference( } } - public record SelectionRequired(List choices) + public record SelectionMenuIdentity(UUID snapshotUuid, String snapshotDigest) { + public SelectionMenuIdentity { + Objects.requireNonNull(snapshotUuid, "snapshotUuid"); + Objects.requireNonNull(snapshotDigest, "snapshotDigest"); + if (NIL_UUID.equals(snapshotUuid) || !SNAPSHOT_DIGEST.matcher(snapshotDigest).matches()) { + throw new IllegalArgumentException("Selection menu identity is malformed"); + } + } + + private boolean matches(CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot) { + return snapshotUuid.equals(snapshot.snapshotUuid()) + && snapshotDigest.equals(snapshot.snapshotDigest()); + } + } + + public record SelectionRequired( + List choices, SelectionMenuIdentity menuIdentity) implements Result { public SelectionRequired { choices = List.copyOf(Objects.requireNonNull(choices, "choices")); + Objects.requireNonNull(menuIdentity, "menuIdentity"); } } @@ -257,6 +291,8 @@ public enum Denial { NO_PRESEEDED_ACTOR, INVALID_SELECTOR, SELECTOR_OUT_OF_RANGE, + MISSING_MENU_IDENTITY, + STALE_MENU_IDENTITY, ASSIGNMENT_UNAVAILABLE, INVALID_ASSIGNMENT_PROOF } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index 1087168c04..e9d2b03278 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -66,6 +66,7 @@ class CanonicalGameplayRosterSelectionServiceTest { private static final UUID FIRST_ACTOR = uuid("77777777-7777-4777-8777-777777777777"); private static final UUID SECOND_ACTOR = uuid("99999999-9999-4999-8999-999999999999"); private static final UUID SNAPSHOT = uuid("88888888-8888-4888-8888-888888888888"); + private static final UUID CHANGED_SNAPSHOT = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); private static final UUID ASSIGNMENT = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); @Test @@ -76,18 +77,21 @@ void returnsMenuForMultipleActorsThenReadsOnlyTheSelectedOrdinalOwnerReference() var menu = harness .service() - .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null); + .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); - assertThat(menu) + assertThat(menu).isInstanceOf(CanonicalGameplayRosterSelectionService.SelectionRequired.class); + var requiredMenu = (CanonicalGameplayRosterSelectionService.SelectionRequired) menu; + assertThat(requiredMenu.choices()) .isEqualTo( - new CanonicalGameplayRosterSelectionService.SelectionRequired( - List.of( - new CanonicalGameplayActorSelection.Choice(1, "Pilot One"), - new CanonicalGameplayActorSelection.Choice(2, "Pilot Two")))); + List.of( + new CanonicalGameplayActorSelection.Choice(1, "Pilot One"), + new CanonicalGameplayActorSelection.Choice(2, "Pilot Two"))); + assertThat(requiredMenu.menuIdentity().snapshotUuid()).isEqualTo(SNAPSHOT); + assertThat(requiredMenu.menuIdentity().snapshotDigest()).matches("[0-9a-f]{64}"); verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); PlayerExecutionContext input = context(harness.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"); - var selected = harness.service().select(input, "2"); + var selected = harness.service().select(input, "2", requiredMenu.menuIdentity()); assertThat(selected) .isInstanceOfSatisfying( @@ -117,6 +121,8 @@ void returnsMenuForMultipleActorsThenReadsOnlyTheSelectedOrdinalOwnerReference() assertThat(selectedContext.getCharacterId()).isEqualTo(SECOND_ACTOR.toString()); assertThat(requestCaptor.getValue().getSelectedCharacterUuid()) .isEqualTo(SECOND_ACTOR.toString()); + assertThat(requestCaptor.getValue().getExpectedSnapshot().getSnapshotDigest()) + .isEqualTo(requiredMenu.menuIdentity().snapshotDigest()); verify(harness.catalogRepository(), atLeastOnce()) .readUniqueVisiblePublicProduction("test", harness.route().canonicalTenantId()); @@ -155,6 +161,7 @@ void deniesTenantNamespaceRealmAndInstanceContextMismatchesBeforeEntityRead() th .setPlayableStateNamespaceId( uuid("12121212-1212-4212-8212-121212121212").toString()) .build(), + null, null), CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); assertDenied( @@ -164,6 +171,7 @@ void deniesTenantNamespaceRealmAndInstanceContextMismatchesBeforeEntityRead() th valid.toBuilder() .setGameInstanceId(uuid("12121212-1212-4212-8212-121212121212").toString()) .build(), + null, null), CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); assertDenied( @@ -173,6 +181,7 @@ void deniesTenantNamespaceRealmAndInstanceContextMismatchesBeforeEntityRead() th valid.toBuilder() .setRealmId(uuid("12121212-1212-4212-8212-121212121212").toString()) .build(), + null, null), CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); @@ -195,7 +204,10 @@ void rejectsAnEntitySnapshotWithAnotherAccountOrTargetBeforeSelectedRead() throw assertDenied( accountMismatch .service() - .select(context(accountMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + .select( + context(accountMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); verify(accountMismatch.stub(), never()).readSelectedPreseededAssignment(any()); @@ -215,7 +227,10 @@ void rejectsAnEntitySnapshotWithAnotherAccountOrTargetBeforeSelectedRead() throw assertDenied( targetMismatch .service() - .select(context(targetMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + .select( + context(targetMismatch.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); verify(targetMismatch.stub(), never()).readSelectedPreseededAssignment(any()); } @@ -226,24 +241,128 @@ void returnsExplicitSelectionAndSelectorDenialsWithoutAssignmentReads() throws E assertThat( multiple .service() - .select(context(multiple.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null)) + .select( + context(multiple.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null)) .isInstanceOf(CanonicalGameplayRosterSelectionService.SelectionRequired.class); assertDenied( multiple .service() - .select(context(multiple.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), "Pilot Two"), + .select( + context(multiple.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "Pilot Two", + null), CanonicalGameplayRosterSelectionService.Denial.INVALID_SELECTOR); + assertDenied( + multiple + .service() + .select(context(multiple.route(), "abababab-abab-4bab-8bab-abababababab"), "3", null), + CanonicalGameplayRosterSelectionService.Denial.SELECTOR_OUT_OF_RANGE); verify(multiple.stub(), never()).readSelectedPreseededAssignment(any()); var empty = harness(List.of()); assertDenied( empty .service() - .select(context(empty.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + .select(context(empty.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), CanonicalGameplayRosterSelectionService.Denial.NO_PRESEEDED_ACTOR); verify(empty.stub(), never()).readSelectedPreseededAssignment(any()); } + @Test + void requiresASelectionMenuIdentityForValidExplicitOrdinals() throws Exception { + var harness = harness(twoActors()); + var menu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + harness + .service() + .select( + context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); + + assertDenied( + harness + .service() + .select(context(harness.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), "2", null), + CanonicalGameplayRosterSelectionService.Denial.MISSING_MENU_IDENTITY); + assertDenied( + harness + .service() + .select( + context(harness.route(), "abababab-abab-4bab-8bab-abababababab"), + "2", + new CanonicalGameplayRosterSelectionService.SelectionMenuIdentity( + menu.menuIdentity().snapshotUuid(), "0".repeat(64))), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + } + + @Test + void rejectsChangedMenuSnapshotUuidAndReorderedRosterBeforeAssignmentRead() throws Exception { + var changedUuid = harness(twoActors()); + AtomicInteger changedUuidReads = new AtomicInteger(); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + UUID snapshotUuid = + changedUuidReads.getAndIncrement() == 0 ? SNAPSHOT : CHANGED_SNAPSHOT; + return rosterResponse( + request, ACCOUNT, request.getExpectedTarget(), twoActors(), snapshotUuid); + }) + .when(changedUuid.stub()) + .listPreseededRoster(any()); + var uuidMenu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + changedUuid + .service() + .select( + context(changedUuid.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null); + assertDenied( + changedUuid + .service() + .select( + context(changedUuid.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "1", + uuidMenu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + verify(changedUuid.stub(), never()).readSelectedPreseededAssignment(any()); + + var reorderedRoster = harness(twoActors()); + AtomicInteger reorderedReads = new AtomicInteger(); + List reorderedActors = + List.of( + new CanonicalGameplayRosterClient.RosterActor(SECOND_ACTOR, "Pilot Two"), + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One")); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + List actors = + reorderedReads.getAndIncrement() == 0 ? twoActors() : reorderedActors; + return rosterResponse( + request, ACCOUNT, request.getExpectedTarget(), actors, SNAPSHOT); + }) + .when(reorderedRoster.stub()) + .listPreseededRoster(any()); + var reorderedMenu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + reorderedRoster + .service() + .select( + context(reorderedRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null); + assertDenied( + reorderedRoster + .service() + .select( + context(reorderedRoster.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "1", + reorderedMenu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + verify(reorderedRoster.stub(), never()).readSelectedPreseededAssignment(any()); + } + @Test void rejectsMovedRouteAfterRosterAndAfterAssignmentNetworkEvidence() throws Exception { var changedAfterList = harness(oneActor()); @@ -252,7 +371,9 @@ void rejectsMovedRouteAfterRosterAndAfterAssignmentNetworkEvidence() throws Exce changedAfterList .service() .select( - context(changedAfterList.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + context(changedAfterList.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); verify(changedAfterList.stub(), never()).readSelectedPreseededAssignment(any()); @@ -263,6 +384,7 @@ void rejectsMovedRouteAfterRosterAndAfterAssignmentNetworkEvidence() throws Exce .service() .select( context(changedAfterAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, null), CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); verify(changedAfterAssignment.stub()).readSelectedPreseededAssignment(any()); @@ -281,7 +403,10 @@ void rejectsChangedAssignmentSnapshotAndUnavailableEntityBackend() throws Except assertDenied( changedSnapshot .service() - .select(context(changedSnapshot.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + .select( + context(changedSnapshot.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); var unavailable = harness(oneActor()); @@ -291,7 +416,8 @@ void rejectsChangedAssignmentSnapshotAndUnavailableEntityBackend() throws Except assertDenied( unavailable .service() - .select(context(unavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + .select( + context(unavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); verify(unavailable.stub(), never()).readSelectedPreseededAssignment(any()); } @@ -304,7 +430,7 @@ void deniesAmbientTransactionBeforeAnyRouteOrOwnerRead() throws Exception { assertDenied( harness .service() - .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null), + .select(context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), CanonicalGameplayRosterSelectionService.Denial.AMBIENT_TRANSACTION); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -549,7 +675,7 @@ private static CanonicalGameplayRosterResponse rosterResponse( UUID account, List actors) throws Exception { - return rosterResponse(request, account, request.getExpectedTarget(), actors); + return rosterResponse(request, account, request.getExpectedTarget(), actors, SNAPSHOT); } private static CanonicalGameplayRosterResponse rosterResponse( @@ -558,6 +684,16 @@ private static CanonicalGameplayRosterResponse rosterResponse( CanonicalGameplayRosterTarget target, List actors) throws Exception { + return rosterResponse(request, account, target, actors, SNAPSHOT); + } + + private static CanonicalGameplayRosterResponse rosterResponse( + CanonicalGameplayRosterRequest request, + UUID account, + CanonicalGameplayRosterTarget target, + List actors, + UUID snapshotUuid) + throws Exception { Method calculateDigest = CanonicalGameplayRosterClient.class.getDeclaredMethod( "calculateSnapshotDigest", UUID.class, CanonicalGameplayRosterTarget.class, List.class); @@ -567,7 +703,7 @@ private static CanonicalGameplayRosterResponse rosterResponse( CanonicalGameplayRosterResponse.newBuilder() .setCanonicalAccountUuid(account.toString()) .setTarget(target) - .setSnapshotUuid(SNAPSHOT.toString()) + .setSnapshotUuid(snapshotUuid.toString()) .setSnapshotDigest(digest); for (CanonicalGameplayRosterClient.RosterActor actor : actors) { builder.addActors( From 05851d516bc7de05e76d5663bbd0377e866458a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 13:17:52 +1300 Subject: [PATCH 16/34] Reject malformed launch runtime flags before sealing success --- .../impl/LaunchDescriptorServiceImpl.java | 24 +++- .../impl/LaunchDescriptorServiceImplTest.java | 112 ++++++++++++++++++ 2 files changed, 133 insertions(+), 3 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 48bc3d421f..83b4008895 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -31,6 +31,8 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @Service @@ -653,13 +655,13 @@ private String resolveRuntimeFlagsJson( normalizeBlank(template.getDefaultRuntimeFlagsJson()) == null ? "{}" : template.getDefaultRuntimeFlagsJson(); + requireRuntimeFlagsObjectJson(templateFlags); String requested = - request.requestedRuntimeFlagsJsonPresent() - ? normalizeBlank(request.requestedRuntimeFlagsJson()) - : null; + request.requestedRuntimeFlagsJsonPresent() ? request.requestedRuntimeFlagsJson() : null; if (requested == null) { return templateFlags; } + requireRuntimeFlagsObjectJson(requested); if (!"{}".equals(templateFlags)) { throw denial( "INVALID_TEMPLATE_CONFIGURATION", "template-owned runtime flags cannot be overridden"); @@ -667,6 +669,22 @@ private String resolveRuntimeFlagsJson( return requested; } + private void requireRuntimeFlagsObjectJson(String runtimeFlagsJson) { + final JsonNode runtimeFlags; + try { + runtimeFlags = + objectMapper + .readerFor(JsonNode.class) + .with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .readValue(runtimeFlagsJson); + } catch (Exception invalidJson) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); + } + if (runtimeFlags == null || !runtimeFlags.isObject()) { + throw denial("INVALID_TEMPLATE_CONFIGURATION", "runtime flags must be a JSON object"); + } + } + private void requireReadyScriptPatch(String scriptPatchVersion) { if (scriptPatchVersion != null && !scriptPatchVersion.isBlank()) { throw denial( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 0be5f1a490..0ffb9af54e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -178,6 +178,7 @@ void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { assertEquals("genrev-1", resolved.generationConfigRevision()); assertEquals(17L, resolved.versionStateEpoch()); assertEquals(11L, resolved.releaseBundleId()); + assertEquals("{}", resolved.runtimeFlagsJson()); assertEquals(PUBLISHED_RELEASE_BUNDLE_REF, resolved.publishedReleaseBundleRef()); assertNotNull(resolved.authoredWorldBinding()); assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); @@ -193,6 +194,78 @@ void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { .findLaunchConfigByTenantIdAndId(CANONICAL_TENANT_ID.toString(), 9L); } + @Test + void malformedRequestedRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + String requestedFlags = "{\"pvpEnabled\":false} trailing"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-requested-runtime-flags", 9L, requestedFlags); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void malformedTemplateRuntimeFlagsFreezeConfigurationDenialWithoutSuccessfulDescriptor() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-invalid-template-flags", 9L); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("not-json"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); + + verify(publishedReleaseBundleService, never()) + .getPublishedReleaseBundle(PRIVATE_SOURCE_TENANT_KEY, 7L); + } + + @Test + void nonObjectRuntimeFlagsCannotBeBoundAsLaunchConfiguration() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-non-object-runtime-flags", 9L, "[]"); + stubSuccessfulLaunch(request, 7L, 11L); + + assertFrozenRuntimeFlagsDenial(request); + } + + @Test + void validRequestedRuntimeFlagsPreserveOriginalJsonAndRequestDigest() { + String requestedFlags = "{ \"pvpEnabled\" : false }"; + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-valid-requested-runtime-flags", 9L, requestedFlags); + stubSuccessfulLaunch(request, 7L, 11L); + AtomicReference inserted = new AtomicReference<>(); + when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) + .thenAnswer( + invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + inserted.set(descriptor); + return descriptor; + }); + + var resolved = service.resolveLaunchDescriptor(request); + + assertEquals(requestedFlags, resolved.runtimeFlagsJson()); + assertEquals(request.requestDigest(), resolved.authoredWorldBinding().requestDigest()); + assertEquals(requestedFlags, inserted.get().getRuntimeFlagsJson()); + assertEquals(resolved.authoredWorldBinding().resultDigest(), inserted.get().getResultDigest()); + } + + @Test + void requestedRuntimeFlagsStillCannotOverrideTemplateOwnedValues() { + AuthoredWorldLaunchDescriptorEvidence.Request request = + request("cp-template-owned-runtime-flags", 9L, "{\"pvpEnabled\":false}"); + GameTemplateLaunchConfigView template = stubTemplate(request, 7L, null); + when(template.getDefaultRuntimeFlagsJson()).thenReturn("{\"pvpEnabled\":true}"); + stubSource(request, sourceEvidence(WORLD_SLUG)); + stubVersion(7L, VersionLifecycleState.PUBLISHED, 17L, null); + + assertFrozenRuntimeFlagsDenial(request); + } + @Test void exactRetryReturnsStoredResultWithoutReadingChangedTemplateDefaultsVersionOrRelease() { AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-retry", 9L); @@ -883,6 +956,26 @@ private AuthoredWorldLaunchDescriptorEvidence.Request request( CANONICAL_TENANT_ID); } + private AuthoredWorldLaunchDescriptorEvidence.Request request( + String controlPlaneRequestId, long gameTemplateId, String requestedRuntimeFlagsJson) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + controlPlaneRequestId, + CANONICAL_TENANT_ID, + WORLD_SLUG, + SOURCE_OPERATION_ID, + sourceEvidence(WORLD_SLUG).evidenceDigest(), + gameTemplateId, + false, + null, + false, + null, + false, + null, + true, + requestedRuntimeFlagsJson); + } + private AuthoredWorldLaunchDescriptorEvidence.Request request( String controlPlaneRequestId, long gameTemplateId, @@ -906,6 +999,25 @@ private AuthoredWorldLaunchDescriptorEvidence.Request request( null); } + private void assertFrozenRuntimeFlagsDenial( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + FrozenLaunchDescriptorDenialException thrown = + assertThrows( + FrozenLaunchDescriptorDenialException.class, + () -> service.resolveLaunchDescriptor(request)); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", thrown.failureCode()); + + org.mockito.ArgumentCaptor failure = + org.mockito.ArgumentCaptor.forClass(LaunchDescriptor.class); + verify(launchDescriptorRepository).insertImmutable(failure.capture()); + assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); + assertEquals("INVALID_TEMPLATE_CONFIGURATION", failure.getValue().getFailureCode()); + assertNull(failure.getValue().getLaunchDescriptorId()); + assertNull(failure.getValue().getVersionId()); + assertNull(failure.getValue().getRuntimeFlagsJson()); + assertNull(failure.getValue().getResultDigest()); + } + private AuthoredWorldLaunchDescriptorEvidence.Request request( String controlPlaneRequestId, long gameTemplateId, From cdf50867dd5e5f935dcd6eb5eb096b76d3ecccbf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:36:43 +1300 Subject: [PATCH 17/34] fix: align roster proof fixture and immutable-target analysis --- ...edWorldReleaseAttestationSelectorTest.java | 46 +------------------ .../client/CanonicalGameplayRosterClient.java | 3 ++ .../text/CanonicalGameplayActorSelection.java | 4 ++ ...nonicalGameplayRosterSelectionService.java | 4 -- 4 files changed, 9 insertions(+), 48 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java index f4fde9e072..e9cbc74b7e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -7,8 +7,7 @@ import java.util.Base64; import java.util.List; import java.util.UUID; -import net.firedevops.firemud.common.authoring.DraftCommitBinding; -import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadGrpcCodecTest; +import net.firedevops.firemud.common.testing.AuthoringFixtures; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; @@ -139,48 +138,7 @@ void selectorSubstitutionAtAnOtherwiseValidCheckpointChangesTheDigest() throws E } static WorldPublishedStartLocationEvidence selectorEvidence() throws Exception { - var terminal = - WorldDraftTerminalReadGrpcCodecTest.freshGraphRequestForStartLocationEvidenceTest(); - var applied = - WorldDraftTerminalReadGrpcCodecTest.committedFreshGraphReadbackForStartLocationEvidenceTest( - terminal); - var account = terminal.accountBinding(); - var draft = - DraftCommitBinding.fromStored( - new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); - var tuples = - draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) - .toList(); - var request = - new WorldPublishedStartLocationEvidence.Request( - "test", - account.tenantId(), - account.versionId(), - UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), - UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), - "publication-request", - "a".repeat(64), - 5L, - "publish-workflow", - account.commitId().toString(), - "b".repeat(64), - 3, - tuples); - var result = JSON.readTree(applied.result()); - return new WorldPublishedStartLocationEvidence( - request, - Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), - applied.fullBinding(), - applied.result()); + return AuthoringFixtures.startLocationEvidence(); } static AuthoredWorldLaunchDescriptorEvidence descriptor( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java index 52f43c5732..cd254a01da 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -615,6 +615,9 @@ public UUID selectedCharacterUuid() { return selectedCharacterUuid; } + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The target is an immutable generated protobuf message.") public CanonicalGameplayRosterTarget target() { return target; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java index 2d1007e4bd..f45067d224 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.command.text; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -243,6 +244,9 @@ public String rosterSnapshotDigest() { return rosterSnapshotDigest; } + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "CanonicalGameplayRosterTarget is an immutable generated protobuf message.") public CanonicalGameplayRosterTarget target() { return target; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java index c4e43044c3..6c90be7d0f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java @@ -77,10 +77,6 @@ public Result select( } catch (RuntimeException invalidOrUnavailable) { return new Denied(Denial.INVALID_ROSTER_PROOF); } - if (snapshot == null) { - return new Denied(Denial.INVALID_ROSTER_PROOF); - } - Denial listFreshnessFailure = requireExactCurrentRoute(current); if (listFreshnessFailure != null) { return new Denied(listFreshnessFailure); From 5bf00b2855516e965912aabb886803c545fc8828 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 14:52:18 +1300 Subject: [PATCH 18/34] test(game-design): target actual retained launch migration predecessor --- .../service/LaunchDescriptorServiceIntegrationTest.java | 2 +- .../gamedesign/repository/GameAssetRepositoryTest.java | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index cf4889581d..729e730ec0 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -471,7 +471,7 @@ void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfill() { String schema = "game_design_launch_history_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = isolatedDataSource(schema); - migrate(dataSource, schema, MigrationVersion.fromVersion("34")); + migrate(dataSource, schema, MigrationVersion.fromVersion("34.1")); DSLContext isolatedDsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); DataSourceTransactionManager isolatedTransactionManager = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java index 017a3fe5cf..4c53f6f243 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameAssetRepositoryTest.java @@ -16,7 +16,8 @@ class GameAssetRepositoryTest { @Test void findByTenantIdConvertsJdbcTimestampAndPreservesAssetBytesAndTenantScope() throws Exception { try (var connection = - DriverManager.getConnection("jdbc:h2:mem:game-asset-timestamp-read;DATABASE_TO_LOWER=TRUE")) { + DriverManager.getConnection( + "jdbc:h2:mem:game-asset-timestamp-read;DATABASE_TO_LOWER=TRUE")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createTable(dsl); LocalDateTime createdAt = LocalDateTime.of(2026, 10, 8, 21, 34, 56, 123_456_000); @@ -50,7 +51,8 @@ void findByTenantIdConvertsJdbcTimestampAndPreservesAssetBytesAndTenantScope() t @Test void saveReadsBackTimestampAndFindByTenantIdPreservesNullTimestamp() throws Exception { try (var connection = - DriverManager.getConnection("jdbc:h2:mem:game-asset-save-timestamp;DATABASE_TO_LOWER=TRUE")) { + DriverManager.getConnection( + "jdbc:h2:mem:game-asset-save-timestamp;DATABASE_TO_LOWER=TRUE")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createTable(dsl); GameAssetRepository repository = new GameAssetRepository(dsl); From 079a6704654e890c07f38235fa8a9047576ee5bc Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:10:07 +1300 Subject: [PATCH 19/34] test: honor explicit launch selections in preparation evidence --- .../GameSessionCanonicalLaunchPreparationServiceTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java index 2c2536f491..913ee37d2c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -733,9 +733,9 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptor( return AuthoredWorldLaunchDescriptorEvidence.create( request.descriptorRequest(catalog, source), "launch-descriptor-1", - 72, - false, - null, + request.targetVersionIdPresent() ? request.targetVersionId() : 72, + request.requestedScriptPatchVersionPresent(), + request.requestedScriptPatchVersion(), "{}", "generation-1", 3, From a063dc44534a6742ecdfc1f9eb9df1e01c91b5e8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:04:49 +1300 Subject: [PATCH 20/34] fix(game-session): align canonical source migration and retained fixtures --- .../V22__authored_world_source_intake.sql | 4 +- ...RealmCatalogRepositoryIntegrationTest.java | 49 ++++++++++++------- ...unchPreparationServiceIntegrationTest.java | 28 +++++------ 3 files changed, 48 insertions(+), 33 deletions(-) diff --git a/services/game-session-service/src/main/resources/db/migration/V22__authored_world_source_intake.sql b/services/game-session-service/src/main/resources/db/migration/V22__authored_world_source_intake.sql index d41a988f98..858a2d9765 100644 --- a/services/game-session-service/src/main/resources/db/migration/V22__authored_world_source_intake.sql +++ b/services/game-session-service/src/main/resources/db/migration/V22__authored_world_source_intake.sql @@ -38,7 +38,7 @@ CREATE TABLE game_session_authored_world_tenant_source_binding ( AND source_game_tenant_key !~ '^[[:space:]]*$' ), CONSTRAINT chk_gs_authored_world_tenant_source_provenance - CHECK (provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30')) + CHECK (provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) ); CREATE TABLE game_session_authored_world_source_intake ( @@ -129,7 +129,7 @@ CREATE TABLE game_session_authored_world_source_intake ( AND source_game_tenant_key !~ '^[[:space:]]*$' ), CONSTRAINT chk_gs_authored_world_source_intake_provenance - CHECK (source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V30')) + CHECK (source_provenance_kind IN ('NEW_GAME_ROW', 'RETAINED_GAME_V29')) ); -- [jooq ignore start] 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 0e107db1ce..51f3da0d6b 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 @@ -339,7 +339,7 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan .isEqualTo(1); IntakeReceipt retained = - fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V30"); + fixture.register(tenant(3), "retained-world", "Retained World", "RETAINED_GAME_V29"); assertThatThrownBy( () -> fixture.create( @@ -680,20 +680,32 @@ CanonicalRealmCatalogSnapshot create(CreateCanonicalRealmCatalogRequest request) void insertRetainedAssociation(IntakeReceipt source, UUID requestId) { AuthoredWorldSourceEvidence evidence = source.source(); String digest = "sha256:" + "a".repeat(64); - dsl.execute( - "INSERT INTO game_session_retained_tenant_association (" - + "operation_id, approval_schema_version, target_namespace, association_request_id, " - + "request_digest, approval_operation_id, signer_key_id, approved_by, " - + "approval_reference, signed_at, legacy_game_session_tenant_id, canonical_tenant_id, " - + "source_game_row_id, source_game_tenant_key, provenance_kind, " - + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " - + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " - + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + UUID operationId = UUID.nameUUIDFromBytes( ("retained-operation-" + requestId) - .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association (" + + "operation_id, target_namespace, association_request_id, " + + "legacy_game_session_tenant_id, canonical_tenant_id, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + operationId, NAMESPACE, requestId, + RETAINED_TENANT_ID, + evidence.canonicalTenantId(), + evidence.sourceGameRowId(), + evidence.sourceGameTenantKey(), + evidence.provenanceKind()); + dsl.execute( + "INSERT INTO game_session_retained_tenant_association_payload (" + + "operation_id, request_digest, approval_operation_id, approval_schema_version, " + + "signer_key_id, approved_by, approval_reference, signed_at, " + + "game_session_evidence_digest, approval_manifest_digest, approval_signature, " + + "snapshot_canonical_json, snapshot_evidence_digest, receipt_digest) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, digest, UUID.nameUUIDFromBytes( ("approval-operation-" + requestId) @@ -702,15 +714,18 @@ void insertRetainedAssociation(IntakeReceipt source, UUID requestId) { "fixture-operator", "fixture-reference", "2026-10-03T00:00:00Z", - RETAINED_TENANT_ID, - evidence.canonicalTenantId(), - evidence.sourceGameRowId(), - evidence.sourceGameTenantKey(), - evidence.provenanceKind(), evidence.evidenceDigest(), digest, "A".repeat(86) + "==", - "{}", + "{\"canonicalTenantId\":\"" + + evidence.canonicalTenantId() + + "\",\"sourceGameRowId\":" + + evidence.sourceGameRowId() + + ",\"sourceGameTenantKey\":\"" + + evidence.sourceGameTenantKey() + + "\",\"provenanceKind\":\"" + + evidence.provenanceKind() + + "\"}", digest, digest); } 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 74c72fac1a..d88f02bd52 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 @@ -79,8 +79,8 @@ class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { fixture.dsl.fetchCount( DSL.table(DSL.name("game_session_canonical_launch_preparation")))) .isZero(); - IntakeReceipt source = java.util.Objects.requireNonNull(fixture.preV14Source); - CanonicalRealmCatalogSnapshot catalog = java.util.Objects.requireNonNull(fixture.preV14Catalog); + IntakeReceipt source = java.util.Objects.requireNonNull(fixture.preV24Source); + CanonicalRealmCatalogSnapshot catalog = java.util.Objects.requireNonNull(fixture.preV24Catalog); assertThat( fixture.sourceRepository.read( source.operationId(), TENANT, source.source().worldSlug(), NAMESPACE)) @@ -363,7 +363,7 @@ private static CreateCanonicalLaunchPreparationRequest request( } private Fixture fixture( - boolean seedRetainedNumericRows, boolean seedCanonicalOwnerEvidenceBeforeV14) { + boolean seedRetainedNumericRows, boolean seedCanonicalOwnerEvidenceBeforeV24) { String schema = "gs_canonical_launch_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl(postgres.getJdbcUrl()); @@ -426,7 +426,7 @@ private Fixture fixture( .defaultSchema(schema) .table("flyway_schema_history") .locations(MIGRATION_LOCATION) - .target(MigrationVersion.fromVersion("13")) + .target(MigrationVersion.fromVersion("23")) .load() .migrate(); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); @@ -437,10 +437,10 @@ private Fixture fixture( new GameSessionAuthoredWorldSourceRepository(transactionalDsl); GameSessionCanonicalRealmCatalogRepository catalogRepository = new GameSessionCanonicalRealmCatalogRepository(transactionalDsl); - IntakeReceipt preV14Source = null; - CanonicalRealmCatalogSnapshot preV14Catalog = null; - if (seedCanonicalOwnerEvidenceBeforeV14) { - preV14Source = + IntakeReceipt preV24Source = null; + CanonicalRealmCatalogSnapshot preV24Catalog = null; + if (seedCanonicalOwnerEvidenceBeforeV24) { + preV24Source = java.util.Objects.requireNonNull( transactions.execute( status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); @@ -449,7 +449,7 @@ private Fixture fixture( CATALOG_REQUEST, NAMESPACE, TENANT, - preV14Source.operationId(), + preV24Source.operationId(), "violet-realm", "Violet Realm", true, @@ -459,7 +459,7 @@ private Fixture fixture( null, null); var preparedCatalog = catalogRepository.prepareInitialPublicProduction(catalogRequest); - preV14Catalog = + preV24Catalog = java.util.Objects.requireNonNull( transactions.execute( status -> catalogRepository.createInitialPublicProduction(preparedCatalog))); @@ -482,8 +482,8 @@ private Fixture fixture( preparationRepository, transactionManager, transactions, - preV14Source, - preV14Catalog); + preV24Source, + preV24Catalog); } private static AuthoredWorldSourceEvidence freshSource() { @@ -545,8 +545,8 @@ private record Fixture( GameSessionCanonicalLaunchPreparationRepository preparationRepository, DataSourceTransactionManager transactionManager, TransactionTemplate transactions, - IntakeReceipt preV14Source, - CanonicalRealmCatalogSnapshot preV14Catalog) { + IntakeReceipt preV24Source, + CanonicalRealmCatalogSnapshot preV24Catalog) { IntakeReceipt registerFreshSource() { IntakeReceipt receipt = transactions.execute(status -> sourceRepository.register(INTAKE_REQUEST, freshSource())); From 3858b273ba41084d9a72839b27dfbaca698dfcd3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:49:00 +1300 Subject: [PATCH 21/34] style: format reconciled launch descriptor integration proof --- .../service/LaunchDescriptorServiceIntegrationTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 07a923cdc0..fc0a1eddaa 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -48,10 +48,10 @@ import org.springframework.context.annotation.Import; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; -import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.util.ReflectionTestUtils; @@ -1113,6 +1113,7 @@ AuthoredWorldLaunchDescriptorEvidence.Request requestWithPatch(String patch) { null); } } + @Test void authoredSourceMigrationBindsFullSourceTupleAndRetainsLegacyRows() { String tenantId = "launch-schema-" + UUID.randomUUID().toString().substring(0, 8); From 6cd7e79cd1834bf4e83824e3c4e584594746c6a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:54:53 +1300 Subject: [PATCH 22/34] fix: persist complete authored source identity in launch outcomes --- .../gamedesign/entity/LaunchDescriptor.java | 4 + .../LaunchDescriptorRepository.java | 16 ++++ .../impl/LaunchDescriptorServiceImpl.java | 76 +++++++++++++------ ...aunchDescriptorServiceIntegrationTest.java | 25 ++++++ .../LaunchDescriptorRepositoryTest.java | 23 ++++-- .../impl/LaunchDescriptorServiceImplTest.java | 42 ++++++++++ 6 files changed, 159 insertions(+), 27 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java index 2626699e67..05f35f8a7e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/entity/LaunchDescriptor.java @@ -25,8 +25,12 @@ public class LaunchDescriptor { private Integer descriptorSchemaVersion; private String targetNamespace; private String canonicalTenantId; + private String authoredWorldSourceTenantSlug; private String worldSlug; private String authoredWorldSourceOperationId; + private Long authoredWorldSourceGameRowId; + private String authoredWorldSourceGameTenantKey; + private String authoredWorldSourceProvenanceKind; private String authoredWorldSourceEvidenceDigest; private String requestDigest; private String resultDigest; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java index 3f09f54f70..64be9fef5c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepository.java @@ -51,9 +51,17 @@ public class LaunchDescriptorRepository { DSL.field(DSL.name("target_namespace"), String.class); private static final Field CANONICAL_TENANT_ID = DSL.field(DSL.name("canonical_tenant_id"), UUID.class); + private static final Field SOURCE_TENANT_SLUG = + DSL.field(DSL.name("authored_world_source_tenant_slug"), String.class); private static final Field WORLD_SLUG = DSL.field(DSL.name("world_slug"), String.class); private static final Field SOURCE_OPERATION_ID = DSL.field(DSL.name("authored_world_source_operation_id"), UUID.class); + private static final Field SOURCE_GAME_ROW_ID = + DSL.field(DSL.name("authored_world_source_game_row_id"), Long.class); + private static final Field SOURCE_GAME_TENANT_KEY = + DSL.field(DSL.name("authored_world_source_game_tenant_key"), String.class); + private static final Field SOURCE_PROVENANCE_KIND = + DSL.field(DSL.name("authored_world_source_provenance_kind"), String.class); private static final Field SOURCE_EVIDENCE_DIGEST = DSL.field(DSL.name("authored_world_source_evidence_digest"), String.class); private static final Field REQUEST_DIGEST = @@ -143,10 +151,14 @@ public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { .set(DESCRIPTOR_SCHEMA_VERSION, descriptor.getDescriptorSchemaVersion()) .set(TARGET_NAMESPACE, descriptor.getTargetNamespace()) .set(CANONICAL_TENANT_ID, UUID.fromString(descriptor.getCanonicalTenantId())) + .set(SOURCE_TENANT_SLUG, descriptor.getAuthoredWorldSourceTenantSlug()) .set(WORLD_SLUG, descriptor.getWorldSlug()) .set( SOURCE_OPERATION_ID, UUID.fromString(descriptor.getAuthoredWorldSourceOperationId())) + .set(SOURCE_GAME_ROW_ID, descriptor.getAuthoredWorldSourceGameRowId()) + .set(SOURCE_GAME_TENANT_KEY, descriptor.getAuthoredWorldSourceGameTenantKey()) + .set(SOURCE_PROVENANCE_KIND, descriptor.getAuthoredWorldSourceProvenanceKind()) .set(SOURCE_EVIDENCE_DIGEST, descriptor.getAuthoredWorldSourceEvidenceDigest()) .set(REQUEST_DIGEST, descriptor.getRequestDigest()) .set(RESULT_DIGEST, descriptor.getResultDigest()) @@ -197,10 +209,14 @@ private LaunchDescriptor toEntity(Record record) { UUID canonicalTenantId = record.get(CANONICAL_TENANT_ID, UUID.class); descriptor.setCanonicalTenantId( canonicalTenantId == null ? null : canonicalTenantId.toString()); + descriptor.setAuthoredWorldSourceTenantSlug(record.get(SOURCE_TENANT_SLUG)); descriptor.setWorldSlug(record.get(WORLD_SLUG)); UUID sourceOperationId = record.get(SOURCE_OPERATION_ID, UUID.class); descriptor.setAuthoredWorldSourceOperationId( sourceOperationId == null ? null : sourceOperationId.toString()); + descriptor.setAuthoredWorldSourceGameRowId(record.get(SOURCE_GAME_ROW_ID)); + descriptor.setAuthoredWorldSourceGameTenantKey(record.get(SOURCE_GAME_TENANT_KEY)); + descriptor.setAuthoredWorldSourceProvenanceKind(record.get(SOURCE_PROVENANCE_KIND)); descriptor.setAuthoredWorldSourceEvidenceDigest(record.get(SOURCE_EVIDENCE_DIGEST)); descriptor.setRequestDigest(record.get(REQUEST_DIGEST)); descriptor.setResultDigest(record.get(RESULT_DIGEST)); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 83b4008895..00f48994af 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -69,13 +69,12 @@ public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( AuthoredWorldSourceEvidence source = readExactSource(request); String sourceJson = writeJson(source); if (LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus())) { - throwStoredFailure( - descriptor, request, requestJson, sourceJson, source.sourceGameTenantKey()); + throwStoredFailure(descriptor, request, source, requestJson, sourceJson); } if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { throw new IllegalArgumentException("LAUNCH_DESCRIPTOR_CONFLICT: stored outcome is unknown"); } - return readStored(descriptor, request, requestJson, sourceJson); + return readStored(descriptor, request, source, requestJson, sourceJson); } AuthoredWorldSourceEvidence source = readExactSource(request); String sourceJson = writeJson(source); @@ -91,7 +90,7 @@ public ResolvedLaunchDescriptorDto resolveLaunchDescriptor( } catch (FrozenLaunchDescriptorDenialException denial) { LaunchDescriptor failure = frozenFailure(request, source, requestJson, sourceJson, denial); LaunchDescriptor persisted = launchDescriptorRepository.insertImmutable(failure); - throwStoredFailure(persisted, request, requestJson, sourceJson, source.sourceGameTenantKey()); + throwStoredFailure(persisted, request, source, requestJson, sourceJson); throw new IllegalStateException("Persisted deterministic launch denial was not returned"); } } @@ -229,18 +228,25 @@ private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( descriptor.setPublishedReleaseBundleRef(evidence.publishedReleaseBundleRef()); descriptor.setRemapSetId(remapSetId); descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); - descriptor.setTargetNamespace(workloadNamespace); - descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); - descriptor.setWorldSlug(request.worldSlug()); - descriptor.setAuthoredWorldSourceOperationId( - request.authoredWorldSourceOperationId().toString()); - descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setTargetNamespace(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); descriptor.setRequestDigest(evidence.requestDigest()); descriptor.setResultDigest(evidence.resultDigest()); descriptor.setOriginalRequestJson(requestJson); descriptor.setSourceEvidenceJson(sourceJson); return readStored( - launchDescriptorRepository.insertImmutable(descriptor), request, requestJson, sourceJson); + launchDescriptorRepository.insertImmutable(descriptor), + request, + source, + requestJson, + sourceJson); } @Override @@ -272,6 +278,7 @@ public ResolvedLaunchDescriptorDto getLaunchDescriptor( return readStored( descriptor, storedRequest, + source, descriptor.getOriginalRequestJson(), descriptor.getSourceEvidenceJson()); } @@ -322,6 +329,7 @@ public ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( return readStored( descriptor, storedRequest, + source, descriptor.getOriginalRequestJson(), descriptor.getSourceEvidenceJson()); } @@ -416,9 +424,11 @@ private record DescriptorReadContext( private ResolvedLaunchDescriptorDto readStored( LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, String requestJson, String sourceJson) { - if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) + if (!matchesStoredSource(descriptor, source) + || !LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus()) || descriptor.getFailureCode() != null || descriptor.getFailureMessage() != null || descriptor.getDescriptorSchemaVersion() == null @@ -490,12 +500,15 @@ private LaunchDescriptor frozenFailure( descriptor.setControlPlaneRequestId(request.controlPlaneRequestId()); descriptor.setRequestHash(request.requestDigest()); descriptor.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); - descriptor.setTargetNamespace(workloadNamespace); - descriptor.setCanonicalTenantId(request.canonicalTenantId().toString()); - descriptor.setWorldSlug(request.worldSlug()); - descriptor.setAuthoredWorldSourceOperationId( - request.authoredWorldSourceOperationId().toString()); - descriptor.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); + descriptor.setTargetNamespace(source.targetNamespace()); + descriptor.setCanonicalTenantId(source.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); + descriptor.setWorldSlug(source.worldSlug()); + descriptor.setAuthoredWorldSourceOperationId(source.operationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); + descriptor.setAuthoredWorldSourceEvidenceDigest(source.evidenceDigest()); descriptor.setRequestDigest(request.requestDigest()); descriptor.setOriginalRequestJson(requestJson); descriptor.setSourceEvidenceJson(sourceJson); @@ -523,10 +536,11 @@ private void requireStoredRequestMatches( private void throwStoredFailure( LaunchDescriptor descriptor, AuthoredWorldLaunchDescriptorEvidence.Request request, + AuthoredWorldSourceEvidence source, String requestJson, - String sourceJson, - String sourceGameTenantKey) { - if (!LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) + String sourceJson) { + if (!matchesStoredSource(descriptor, source) + || !LaunchDescriptor.OUTCOME_FAILED.equals(descriptor.getOutcomeStatus()) || !Objects.equals( descriptor.getDescriptorSchemaVersion(), AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION) @@ -545,7 +559,7 @@ private void throwStoredFailure( || !request.requestDigest().equals(descriptor.getRequestHash()) || !requestJson.equals(descriptor.getOriginalRequestJson()) || !sourceJson.equals(descriptor.getSourceEvidenceJson()) - || !sourceGameTenantKey.equals(descriptor.getTenantId()) + || !source.sourceGameTenantKey().equals(descriptor.getTenantId()) || descriptor.getLaunchDescriptorId() != null || descriptor.getGameTemplateId() != null || descriptor.getVersionId() != null @@ -567,6 +581,24 @@ private void throwStoredFailure( descriptor.getFailureCode(), descriptor.getFailureMessage()); } + private boolean matchesStoredSource( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + return Objects.equals(descriptor.getTargetNamespace(), source.targetNamespace()) + && Objects.equals(descriptor.getCanonicalTenantId(), source.canonicalTenantId().toString()) + && Objects.equals(descriptor.getAuthoredWorldSourceTenantSlug(), source.tenantSlug()) + && Objects.equals(descriptor.getWorldSlug(), source.worldSlug()) + && Objects.equals( + descriptor.getAuthoredWorldSourceOperationId(), source.operationId().toString()) + && Objects.equals( + descriptor.getAuthoredWorldSourceGameRowId(), source.sourceGameRowId()) + && Objects.equals( + descriptor.getAuthoredWorldSourceGameTenantKey(), source.sourceGameTenantKey()) + && Objects.equals( + descriptor.getAuthoredWorldSourceProvenanceKind(), source.provenanceKind()) + && Objects.equals( + descriptor.getAuthoredWorldSourceEvidenceDigest(), source.evidenceDigest()); + } + private boolean isPersistableFailureCode(String failureCode) { return switch (failureCode == null ? "" : failureCode) { case "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index fc0a1eddaa..d2362b412a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -189,6 +189,7 @@ void resolvesPersistedSourceAndReplaysOriginalDescriptorAfterDefaultsAndVersionC assertThat(persisted.getPublishedReleaseBundleRef()) .isEqualTo(original.publishedReleaseBundleRef()); assertThat(persisted.getGenerationConfigRevision()).isEqualTo(generationConfigRevision); + assertDescriptorSourceTuple(persisted, fixture.source()); assertThat( dsl.fetchCount( LAUNCH_DESCRIPTOR, @@ -274,6 +275,7 @@ void deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries assertThat(failed.getRequestDigest()).isEqualTo(fixture.request().requestDigest()); assertThat(failed.getOriginalRequestJson()).isNotBlank(); assertThat(failed.getSourceEvidenceJson()).isNotBlank(); + assertDescriptorSourceTuple(failed, fixture.source()); assertThat(failed.getLaunchDescriptorId()).isNull(); assertThat(failed.getGameTemplateId()).isNull(); assertThat(failed.getVersionId()).isNull(); @@ -871,9 +873,13 @@ private LaunchDescriptor entity(AuthoredWorldLaunchDescriptorEvidence evidence, descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); descriptor.setTargetNamespace(evidence.targetNamespace()); descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(fixture.source().tenantSlug()); descriptor.setWorldSlug(evidence.worldSlug()); descriptor.setAuthoredWorldSourceOperationId( evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(fixture.source().sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(fixture.source().sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(fixture.source().provenanceKind()); descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); descriptor.setRequestDigest(evidence.requestDigest()); descriptor.setResultDigest(evidence.resultDigest()); @@ -1033,6 +1039,21 @@ private String privateTenantKey() { return "src-" + UUID.randomUUID().toString().replace("-", ""); } + private void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertThat(descriptor.getTargetNamespace()).isEqualTo(source.targetNamespace()); + assertThat(descriptor.getCanonicalTenantId()).isEqualTo(source.canonicalTenantId().toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo(source.tenantSlug()); + assertThat(descriptor.getWorldSlug()).isEqualTo(source.worldSlug()); + assertThat(descriptor.getAuthoredWorldSourceOperationId()) + .isEqualTo(source.operationId().toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(source.sourceGameRowId()); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()) + .isEqualTo(source.sourceGameTenantKey()); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()).isEqualTo(source.provenanceKind()); + assertThat(descriptor.getAuthoredWorldSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + } + private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescriptor actual) { assertThat(actual.getId()).isEqualTo(expected.getId()); assertThat(actual.getLaunchDescriptorId()).isEqualTo(expected.getLaunchDescriptorId()); @@ -1054,8 +1075,12 @@ private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescrip assertThat(actual.getDescriptorSchemaVersion()).isNull(); assertThat(actual.getTargetNamespace()).isNull(); assertThat(actual.getCanonicalTenantId()).isNull(); + assertThat(actual.getAuthoredWorldSourceTenantSlug()).isNull(); assertThat(actual.getWorldSlug()).isNull(); assertThat(actual.getAuthoredWorldSourceOperationId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameRowId()).isNull(); + assertThat(actual.getAuthoredWorldSourceGameTenantKey()).isNull(); + assertThat(actual.getAuthoredWorldSourceProvenanceKind()).isNull(); assertThat(actual.getAuthoredWorldSourceEvidenceDigest()).isNull(); assertThat(actual.getRequestDigest()).isNull(); assertThat(actual.getResultDigest()).isNull(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java index 750a243e20..2aed37a70b 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java @@ -30,8 +30,12 @@ void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws E + "version_state_epoch BIGINT, release_bundle_id BIGINT, " + "published_release_bundle_ref VARCHAR(128), remap_set_id VARCHAR(64), " + "descriptor_schema_version SMALLINT, target_namespace VARCHAR(63), " - + "canonical_tenant_id UUID, world_slug VARCHAR(120), " + + "canonical_tenant_id UUID, authored_world_source_tenant_slug VARCHAR(120), " + + "world_slug VARCHAR(120), " + "authored_world_source_operation_id UUID, " + + "authored_world_source_game_row_id BIGINT, " + + "authored_world_source_game_tenant_key VARCHAR(36), " + + "authored_world_source_provenance_kind VARCHAR(32), " + "authored_world_source_evidence_digest VARCHAR(72), request_digest VARCHAR(72), " + "result_digest VARCHAR(72), original_request_json VARCHAR(4000), " + "source_evidence_json VARCHAR(4000), outcome_status VARCHAR(16), " @@ -41,8 +45,11 @@ void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws E + "control_plane_request_id, request_hash, version_id, script_patch_version, " + "runtime_flags_json, generation_config_revision, version_state_epoch, " + "release_bundle_id, published_release_bundle_ref, remap_set_id, " - + "descriptor_schema_version, target_namespace, canonical_tenant_id, world_slug, " - + "authored_world_source_operation_id, authored_world_source_evidence_digest, " + + "descriptor_schema_version, target_namespace, canonical_tenant_id, " + + "authored_world_source_tenant_slug, world_slug, " + + "authored_world_source_operation_id, authored_world_source_game_row_id, " + + "authored_world_source_game_tenant_key, authored_world_source_provenance_kind, " + + "authored_world_source_evidence_digest, " + "request_digest, result_digest, original_request_json, source_evidence_json, " + "outcome_status, failure_code, failure_message, created_at) VALUES " + "(17, 'launch-17', 'private-tenant', 23, 'request-17', 'sha256:request', 29, " @@ -51,9 +58,10 @@ void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws E + "g".repeat(180) + "', 8, 31, 'release-31', NULL, 1, 'preview', '" + canonicalTenantId - + "', 'verdant-harbor', '" + + "', 'verdant-company', 'verdant-harbor', '" + sourceOperationId - + "', 'sha256:source', 'sha256:request', 'sha256:result', '{}', '{}', 'SUCCESS', " + + "', 93, 'private-game-key-9', 'NEW_GAME_ROW', 'sha256:source', " + + "'sha256:request', 'sha256:result', '{}', '{}', 'SUCCESS', " + "NULL, NULL, TIMESTAMP '2026-10-03 10:15:30.123')"); var descriptor = @@ -63,8 +71,13 @@ void findBoundByRequestConvertsMetadataBackedSmallintUuidAndTimestamp() throws E assertThat(descriptor.getDescriptorSchemaVersion()).isEqualTo(1); assertThat(descriptor.getCanonicalTenantId()).isEqualTo(canonicalTenantId.toString()); + assertThat(descriptor.getAuthoredWorldSourceTenantSlug()).isEqualTo("verdant-company"); + assertThat(descriptor.getWorldSlug()).isEqualTo("verdant-harbor"); assertThat(descriptor.getAuthoredWorldSourceOperationId()) .isEqualTo(sourceOperationId.toString()); + assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(93L); + assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()).isEqualTo("private-game-key-9"); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()).isEqualTo("NEW_GAME_ROW"); assertThat(descriptor.getGenerationConfigRevision()) .isEqualTo("generation-6:" + "g".repeat(180)); assertThat(descriptor.getCreatedAt()).isEqualTo(createdAt); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 0ffb9af54e..c5d3b9363e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -187,6 +187,7 @@ void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { inserted.get().getTenantId(), "The private source key remains owner-local and is not the canonical tenant UUID"); assertEquals(CANONICAL_TENANT_ID.toString(), inserted.get().getCanonicalTenantId()); + assertDescriptorSourceTuple(inserted.get(), sourceEvidence(WORLD_SLUG)); verify(authoredWorldSourceRepository) .read(SOURCE_OPERATION_ID, CANONICAL_TENANT_ID, WORLD_SLUG, NAMESPACE); verify(gameTemplateRepository).findLaunchConfigByTenantIdAndId(PRIVATE_SOURCE_TENANT_KEY, 9L); @@ -470,6 +471,7 @@ void selectedPatchWithoutExactPublicationAndReadinessEvidenceCannotResolve() { assertEquals(LaunchDescriptor.OUTCOME_FAILED, failure.getValue().getOutcomeStatus()); assertEquals("SCRIPT_PATCH_NOT_READY", failure.getValue().getFailureCode()); assertEquals(request.requestDigest(), failure.getValue().getRequestDigest()); + assertDescriptorSourceTuple(failure.getValue(), sourceEvidence(WORLD_SLUG)); assertEquals(null, failure.getValue().getLaunchDescriptorId()); assertEquals(null, failure.getValue().getVersionId()); } @@ -533,8 +535,12 @@ void exactRetryOfStoredFailureReturnsItsOriginalCodeAndMessageBeforeMutableReads failure.setDescriptorSchemaVersion(AuthoredWorldLaunchDescriptorEvidence.SCHEMA_VERSION); failure.setTargetNamespace(NAMESPACE); failure.setCanonicalTenantId(CANONICAL_TENANT_ID.toString()); + failure.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); failure.setWorldSlug(WORLD_SLUG); failure.setAuthoredWorldSourceOperationId(SOURCE_OPERATION_ID.toString()); + failure.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + failure.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + failure.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); failure.setAuthoredWorldSourceEvidenceDigest(request.authoredWorldSourceEvidenceDigest()); failure.setRequestDigest(request.requestDigest()); failure.setOriginalRequestJson(new ObjectMapper().writeValueAsString(request)); @@ -578,6 +584,25 @@ void tamperedStoredPatchCannotReplayOutsideItsCommittedResultDigest() { thrown.getMessage()); } + @Test + void storedDescriptorReplayRejectsChangedAuthoredSourceTuple() { + AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-tampered-source", 9L); + stubSuccessfulLaunch(request, 7L, 11L); + LaunchDescriptor stored = descriptorFor(request, 7L, 11L); + stored.setAuthoredWorldSourceGameRowId(902L); + when(launchDescriptorRepository.findBoundByRequest( + NAMESPACE, CANONICAL_TENANT_ID, request.controlPlaneRequestId())) + .thenReturn(Optional.of(stored)); + + IllegalArgumentException thrown = + assertThrows( + IllegalArgumentException.class, () -> service.resolveLaunchDescriptor(request)); + + assertEquals( + "LAUNCH_DESCRIPTOR_CONFLICT: stored descriptor is not the exact immutable request", + thrown.getMessage()); + } + @Test void resolveLaunchDescriptorPreservesTemplatePhaseGate() { AuthoredWorldLaunchDescriptorEvidence.Request request = request("cp-phase", 9L); @@ -897,9 +922,13 @@ private LaunchDescriptor descriptorFor( descriptor.setDescriptorSchemaVersion(evidence.schemaVersion()); descriptor.setTargetNamespace(evidence.targetNamespace()); descriptor.setCanonicalTenantId(evidence.canonicalTenantId().toString()); + descriptor.setAuthoredWorldSourceTenantSlug(source.tenantSlug()); descriptor.setWorldSlug(evidence.worldSlug()); descriptor.setAuthoredWorldSourceOperationId( evidence.authoredWorldSourceOperationId().toString()); + descriptor.setAuthoredWorldSourceGameRowId(source.sourceGameRowId()); + descriptor.setAuthoredWorldSourceGameTenantKey(source.sourceGameTenantKey()); + descriptor.setAuthoredWorldSourceProvenanceKind(source.provenanceKind()); descriptor.setAuthoredWorldSourceEvidenceDigest(evidence.authoredWorldSourceEvidenceDigest()); descriptor.setRequestDigest(evidence.requestDigest()); descriptor.setResultDigest(evidence.resultDigest()); @@ -946,6 +975,19 @@ private AuthoredWorldSourceEvidence sourceEvidence(String worldSlug) { "NEW_GAME_ROW")); } + private void assertDescriptorSourceTuple( + LaunchDescriptor descriptor, AuthoredWorldSourceEvidence source) { + assertEquals(source.targetNamespace(), descriptor.getTargetNamespace()); + assertEquals(source.canonicalTenantId().toString(), descriptor.getCanonicalTenantId()); + assertEquals(source.tenantSlug(), descriptor.getAuthoredWorldSourceTenantSlug()); + assertEquals(source.worldSlug(), descriptor.getWorldSlug()); + assertEquals(source.operationId().toString(), descriptor.getAuthoredWorldSourceOperationId()); + assertEquals(source.sourceGameRowId(), descriptor.getAuthoredWorldSourceGameRowId()); + assertEquals(source.sourceGameTenantKey(), descriptor.getAuthoredWorldSourceGameTenantKey()); + assertEquals(source.provenanceKind(), descriptor.getAuthoredWorldSourceProvenanceKind()); + assertEquals(source.evidenceDigest(), descriptor.getAuthoredWorldSourceEvidenceDigest()); + } + private AuthoredWorldLaunchDescriptorEvidence.Request request( String controlPlaneRequestId, long gameTemplateId) { return request( From 9b4a2b8b10755a19af3c00d718e39414e44e00d6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:01:47 +1300 Subject: [PATCH 23/34] style: format complete launch source identity proof --- .../service/impl/LaunchDescriptorServiceImpl.java | 3 +-- .../service/LaunchDescriptorServiceIntegrationTest.java | 6 ++++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index 00f48994af..1a2a346e21 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -589,8 +589,7 @@ private boolean matchesStoredSource( && Objects.equals(descriptor.getWorldSlug(), source.worldSlug()) && Objects.equals( descriptor.getAuthoredWorldSourceOperationId(), source.operationId().toString()) - && Objects.equals( - descriptor.getAuthoredWorldSourceGameRowId(), source.sourceGameRowId()) + && Objects.equals(descriptor.getAuthoredWorldSourceGameRowId(), source.sourceGameRowId()) && Objects.equals( descriptor.getAuthoredWorldSourceGameTenantKey(), source.sourceGameTenantKey()) && Objects.equals( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index d2362b412a..c1656a8406 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -1050,8 +1050,10 @@ private void assertDescriptorSourceTuple( assertThat(descriptor.getAuthoredWorldSourceGameRowId()).isEqualTo(source.sourceGameRowId()); assertThat(descriptor.getAuthoredWorldSourceGameTenantKey()) .isEqualTo(source.sourceGameTenantKey()); - assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()).isEqualTo(source.provenanceKind()); - assertThat(descriptor.getAuthoredWorldSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + assertThat(descriptor.getAuthoredWorldSourceProvenanceKind()) + .isEqualTo(source.provenanceKind()); + assertThat(descriptor.getAuthoredWorldSourceEvidenceDigest()) + .isEqualTo(source.evidenceDigest()); } private void assertRetainedRowUnchanged(LaunchDescriptor expected, LaunchDescriptor actual) { From e201e8ae69803c4185a172fedb25e1bb46d76ca0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:57:54 +1300 Subject: [PATCH 24/34] test: prove non-null canonical launch fixture version --- .../GameSessionCanonicalLaunchPreparationServiceTest.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java index 913ee37d2c..2dc09bf26c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -730,10 +730,14 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptor( CreateCanonicalLaunchPreparationRequest request, CanonicalRealmCatalogSnapshot catalog, AuthoredWorldSourceEvidence source) { + long targetVersionId = + request.targetVersionIdPresent() + ? java.util.Objects.requireNonNull(request.targetVersionId(), "targetVersionId") + : 72L; return AuthoredWorldLaunchDescriptorEvidence.create( request.descriptorRequest(catalog, source), "launch-descriptor-1", - request.targetVersionIdPresent() ? request.targetVersionId() : 72, + targetVersionId, request.requestedScriptPatchVersionPresent(), request.requestedScriptPatchVersion(), "{}", From 957dc5e60b9b94818507a3ccc02e33348d7473bb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 05:53:16 +1300 Subject: [PATCH 25/34] Restore canonical descriptor test helpers after roster reconciliation --- .../impl/GameDesignGrpcServiceTest.java | 67 ++++++++++++++++++- ...stanceServiceLifecycleIntegrationTest.java | 2 +- 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 3d9bc62783..3c97c290df 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -21,7 +21,6 @@ import net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto; import net.firedevops.firemud.gamedesign.dto.PublishedPluginVersionDto; import net.firedevops.firemud.gamedesign.dto.PublishedReleaseBundleDto; -import net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto; import net.firedevops.firemud.gamedesign.dto.RevisionDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapEntryDto; import net.firedevops.firemud.gamedesign.dto.TemplateRemapSetDto; @@ -1729,6 +1728,72 @@ private static StreamObserver observerFor(AtomicReference ref) { return new GenericObserver<>(ref); } + private AuthoredWorldLaunchDescriptorEvidence.Request launchRequest( + String controlPlaneRequestId) { + return new AuthoredWorldLaunchDescriptorEvidence.Request( + "test", + controlPlaneRequestId, + CANONICAL_TENANT_ID, + "silver-march", + AUTHORED_SOURCE_OPERATION_ID, + "sha256:" + "a".repeat(64), + 9L, + false, + null, + false, + null, + false, + null, + false, + null); + } + + private AuthoredWorldLaunchDescriptorEvidence launchEvidence( + AuthoredWorldLaunchDescriptorEvidence.Request request) { + return AuthoredWorldLaunchDescriptorEvidence.create( + request, + "ld-1", + 7L, + false, + null, + "{}", + "genrev-1", + 11L, + 11L, + "release-bundle:" + CANONICAL_TENANT_ID + ":7:11", + false, + null); + } + + private net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto launchDto( + AuthoredWorldLaunchDescriptorEvidence evidence) { + return new net.firedevops.firemud.gamedesign.dto.ResolvedLaunchDescriptorDto( + evidence.launchDescriptorId(), + evidence.canonicalTenantId().toString(), + evidence.gameTemplateId(), + evidence.controlPlaneRequestId(), + evidence.versionId(), + evidence.scriptPatchVersion(), + evidence.runtimeFlagsJson(), + evidence.generationConfigRevision(), + evidence.versionStateEpoch(), + evidence.releaseBundleId(), + evidence.publishedReleaseBundleRef(), + evidence.remapSetId(), + evidence); + } + + private ResolveLaunchDescriptorRequest resolveRequest(String controlPlaneRequestId) { + return ResolveLaunchDescriptorRequest.newBuilder() + .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) + .setGameTemplateId(9L) + .setControlPlaneRequestId(controlPlaneRequestId) + .setWorldSlug("silver-march") + .setAuthoredWorldSourceOperationId(AUTHORED_SOURCE_OPERATION_ID.toString()) + .setExpectedAuthoredWorldSourceEvidenceDigest("sha256:" + "a".repeat(64)) + .build(); + } + private TemplateRemapSetDto sampleRemapSetDto( TemplateRemapSetStatus status, String approvalReason, LocalDateTime approvedAt) { return new TemplateRemapSetDto( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index 398cf3103c..6fefadf114 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -18,7 +18,6 @@ import net.firedevops.firemud.common.conflict.ConflictTracker; import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.settings.SharedSettingsAuthorityReader; -import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.gamesession.GameSessionServiceApplication; import net.firedevops.firemud.gamesession.client.AccountClient; import net.firedevops.firemud.gamesession.client.EntityManagementClient; @@ -33,6 +32,7 @@ import net.firedevops.firemud.gamesession.service.CommandService; import net.firedevops.firemud.gamesession.service.SessionContextService; import net.firedevops.firemud.gamesession.service.SessionStateService; +import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; From 3ee73fb5393286af21ebf83e443aa103636032e7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:09:57 +1300 Subject: [PATCH 26/34] Align roster source fixtures with canonical evidence contracts --- ...ayRosterOwnerReadInterceptorChainTest.java | 24 +++++++++++++++---- ...signmentOwnerReadInterceptorChainTest.java | 24 +++++++++++++++---- .../impl/GameInstanceServiceImplTest.java | 13 +++++----- .../PublishedRealmPolicyEvidenceFixture.java | 2 +- 4 files changed, 47 insertions(+), 16 deletions(-) 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 ed1b644f1e..08f92fe291 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 @@ -92,9 +92,9 @@ void absentWrongServiceCrossNamespaceAndPlayerCallerContextAreDenied() { invokeThroughConfiguredChain(entityIdentity("other"), adapter, request(), otherNamespace); assertPermissionDenied(otherNamespace); - SessionContext.setContext(ACCOUNT.toString(), List.of("player"), java.util.Map.of()); var callerContext = new CapturingObserver(); - invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter, request(), callerContext); + invokeThroughConfiguredChain( + entityIdentity(NAMESPACE), adapter, request(), callerContext, true); assertPermissionDenied(callerContext); verifyNoInteractions(provider); @@ -119,7 +119,8 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { .containsExactly( "game_session.v1.GameSessionService/Ping", METHOD, - "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead") + "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead", + "game_session.v1.GameSessionService/AuthorizeStartSession") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( @@ -154,6 +155,15 @@ private static void invokeThroughConfiguredChain( CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, GetCanonicalGameplayRosterOwnerReadRequest request, CapturingObserver response) { + invokeThroughConfiguredChain(peerUri, adapter, request, response, false); + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetCanonicalGameplayRosterOwnerReadRequest request, + CapturingObserver response, + boolean authenticatedCallerContext) { ServerCall call = new TestServerCall(METHOD, sslSession(peerUri)); Metadata headers = new Metadata(); ServerInterceptor peer = new GrpcPeerIdentityInterceptor(); @@ -166,7 +176,13 @@ private static void invokeThroughConfiguredChain( .interceptCall( call, headers, - (authCall, authHeaders) -> peer.interceptCall(authCall, authHeaders, handler)); + (authCall, authHeaders) -> { + if (authenticatedCallerContext) { + SessionContext.setContext( + ACCOUNT.toString(), List.of("player"), java.util.Map.of()); + } + return peer.interceptCall(authCall, authHeaders, handler); + }); } private static GetCanonicalGameplayRosterOwnerReadRequest request() { 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 8ae7a022bc..9d5bd453e3 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 @@ -100,9 +100,9 @@ void absentWrongServiceCrossNamespaceAndCallerContextAreDeniedBeforeSourceRead() invokeThroughConfiguredChain(entityIdentity("other"), adapter, request(), otherNamespace); assertPermissionDenied(otherNamespace); - SessionContext.setContext(ACCOUNT.toString(), List.of("player"), java.util.Map.of()); var callerContext = new CapturingObserver(); - invokeThroughConfiguredChain(entityIdentity(NAMESPACE), adapter, request(), callerContext); + invokeThroughConfiguredChain( + entityIdentity(NAMESPACE), adapter, request(), callerContext, true); assertPermissionDenied(callerContext); verifyNoInteractions(provider); @@ -125,7 +125,8 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { .containsExactly( "game_session.v1.GameSessionService/Ping", "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", - METHOD) + METHOD, + "game_session.v1.GameSessionService/AuthorizeStartSession") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( @@ -160,6 +161,15 @@ private static void invokeThroughConfiguredChain( CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, GetPreseededActorAssignmentOwnerReadRequest request, CapturingObserver response) { + invokeThroughConfiguredChain(peerUri, adapter, request, response, false); + } + + private static void invokeThroughConfiguredChain( + String peerUri, + CanonicalGameplayRosterOwnerReadGrpcAdapter adapter, + GetPreseededActorAssignmentOwnerReadRequest request, + CapturingObserver response, + boolean authenticatedCallerContext) { ServerCall call = new TestServerCall(METHOD, sslSession(peerUri)); Metadata headers = new Metadata(); ServerInterceptor peer = new GrpcPeerIdentityInterceptor(); @@ -172,7 +182,13 @@ private static void invokeThroughConfiguredChain( .interceptCall( call, headers, - (authCall, authHeaders) -> peer.interceptCall(authCall, authHeaders, handler)); + (authCall, authHeaders) -> { + if (authenticatedCallerContext) { + SessionContext.setContext( + ACCOUNT.toString(), List.of("player"), java.util.Map.of()); + } + return peer.interceptCall(authCall, authHeaders, handler); + }); } private static GetPreseededActorAssignmentOwnerReadRequest request() { 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 25404ae4b4..b4242fba1a 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 @@ -191,9 +191,9 @@ void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority() { verify(gameDesignClient) .resolveLaunchDescriptor( request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); - verify(gameDesignClient).getPublishedReleaseBundle(request.tenantId(), 11L); - verify(gameDesignClient).getVersionAssetArtifactState(request.tenantId(), 11L); - verify(gameDesignClient).getVersionState(request.tenantId(), 11L); + verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); + verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); verifyNoMoreInteractions(gameDesignClient); verifyNoInteractions(repository, worldManagementClient, stateService); } @@ -671,7 +671,7 @@ void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-pinned") - .setCanonicalTenantId("1") + .setTenantId("1") .setGameTemplateId(3L) .setControlPlaneRequestId("cp-pinned") .setVersionId(11L) @@ -1709,8 +1709,7 @@ private void configureLaunchPreflight() { .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-" + invocation.getArgument(2, String.class)) - .setCanonicalTenantId( - Long.toString(invocation.getArgument(0, Long.class))) + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) .setGameTemplateId(invocation.getArgument(1, Long.class)) .setControlPlaneRequestId(invocation.getArgument(2, String.class)) .setVersionId(11L) @@ -1941,7 +1940,7 @@ void startSessionRejectsNonPositiveLaunchDescriptorTenantIdBeforeWorldPreparatio .setLaunchDescriptor( net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-cp-launch-tenant") - .setCanonicalTenantId("0") + .setTenantId("0") .setGameTemplateId(3L) .setControlPlaneRequestId("cp-launch-tenant") .setVersionId(11L) diff --git a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java index 94ae82b2ba..db4924d314 100644 --- a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java +++ b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java @@ -679,7 +679,7 @@ private static ReleaseContent release( request.appliedCommitId(), owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), owner.equals("GAME_LOGIC") ? DIGEST : null, null, null)) From bb612251744f8b28c0dd77ef7aaf94c139bb1baa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:23:08 +1300 Subject: [PATCH 27/34] Classify owner read failures and preserve roster and retained request identity proof --- .../system-architecture-transactions.md | 13 +- ...e-session-runtime-and-tick-coordination.md | 2 +- .../player-access-and-session.md | 4 +- .../CanonicalLaunchGrpcAuthWiringTest.java | 2 + .../impl/GameDesignGrpcServiceTest.java | 23 --- .../GameDesignPublishedRealmPolicyClient.java | 16 +- .../dto/CanonicalInitialAdmissionRequest.java | 4 +- ...nonicalGameplayRosterSelectionService.java | 57 ++++-- ...onicalPublishedPlayerRouteReadService.java | 21 ++- ...GameSessionApplicationIntegrationTest.java | 3 +- ...ialAdmissionRepositoryIntegrationTest.java | 29 +++ ...eDesignPublishedRealmPolicyClientTest.java | 8 +- .../CanonicalInitialAdmissionRequestTest.java | 26 ++- ...calGameplayRosterSelectionServiceTest.java | 176 +++++++++++++++++- ...alPublishedPlayerRouteReadServiceTest.java | 50 +++++ 15 files changed, 374 insertions(+), 60 deletions(-) diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index e91fecf781..f5425ead9e 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -396,7 +396,7 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): Entity.AutoProvisionCharacter(discoveredEntry, discoveredEntryDigest, autoProvisionRequestId, mutationDigest, canonicalCreationInput) PRESEEDED_ONLY: require creation input is absent - if retrying selection step: + if retrying after assignment reference was bound: selectionReadback = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, boundRosterSnapshot.reference, selectedCharacterId) require selectionReadback.request_uuid == boundRequest.request_uuid require selectionReadback.canonical_account_uuid == boundRequest.canonical_account_uuid @@ -409,7 +409,12 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): rosterSnapshot = boundRosterSnapshot else: rosterSnapshot = Entity.CanonicalGameplayRosterService.ListPreseededRoster(discoveredEntry, discoveredEntryDigest) - bind rosterSnapshot.identity and rosterSnapshot.digest to sagaStep + if retrying selection step: + require rosterSnapshot.identity == boundRosterSnapshot.identity + require rosterSnapshot.digest == boundRosterSnapshot.digest + rosterSnapshot = boundRosterSnapshot # preserve the original selection evidence + else: + bind rosterSnapshot.identity and rosterSnapshot.digest to sagaStep roster = rosterSnapshot.roster if roster is zero: return pre-seeded-only denial @@ -421,7 +426,7 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): resolvedSelectedCharacter = require actor matching selectedCharacterId in unchanged roster/snapshot bind resolvedSelectedCharacter.characterId to sagaStep select resolvedSelectedCharacter # lookup/selection only; no actor mutation - if not retrying selection step: + if assignment reference is not yet bound: selectionReadback = Entity.CanonicalGameplayRosterService.ReadSelectedPreseededAssignment(discoveredEntry, rosterSnapshot.reference, selectedCharacterId) require selectionReadback.request_uuid == boundRequest.request_uuid require selectionReadback.canonical_account_uuid == boundRequest.canonical_account_uuid @@ -429,7 +434,7 @@ explicitRealmEntry(discoveredEntry, discoveredEntryDigest): require selectionReadback.target == boundRequest.expected_target require selectionReadback.snapshot == rosterSnapshot.reference bind selectionReadback.assignment_uuid and selectionReadback.intent_digest to sagaStep - retries reuse the same discoveredEntry, discoveredEntryDigest, branch, applicable roster snapshot identity/digest, and resolved selectedCharacterId; an entered PLAYER_CREATED create step replays Entity before any fresh roster rejection, and each actor mutation reuses its operation request identity, mutationDigest, and canonicalCreationInput, while a changed input or roster snapshot fails closed + retries reuse the same discoveredEntry, discoveredEntryDigest, branch, applicable roster snapshot identity/digest, and resolved selectedCharacterId; a PRESEEDED_ONLY retry before assignment-reference binding rereads and validates the original roster snapshot, then resumes the original selected-assignment read without requiring an absent assignment UUID or intent digest, while an assignment-bound retry retains the exact original tuple assertions. An entered PLAYER_CREATED create step replays Entity before any fresh roster rejection, and each actor mutation reuses its operation request identity, mutationDigest, and canonicalCreationInput, while a changed input or roster snapshot fails closed ``` This is a target-state branch illustration, not current implementation or proof. Compensation applies only to the selected mutating branch; the `PRESEEDED_ONLY` lookup has no actor mutation to compensate. 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 8c13bc1a36..78d6c301e3 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 @@ -14,7 +14,7 @@ Focused unit tests cover immutable replay, descriptor comparison, certificate-pi This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -The Entity-only roster and preseeded-assignment owner reads are a separate default-off, read-only source boundary; they do not change tick execution, attach sessions, or activate `PLAY`/`LOOK`. Focused route/client/guard and isolated selection proof artifacts are present but unrun in this preparation. See [Player Access and Session](./player-access-and-session.md) for AA-2.1 status and [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) for the source boundary. +The Entity-only roster and preseeded-assignment owner reads are a separate default-off, read-only source boundary; they do not change tick execution, attach sessions, or activate `PLAY`/`LOOK`. The focused [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) proof executed in source Validation `38362401283` on published `65bf7294a906df9fc7fdd3150ddc94572c60dc09`: Game Session completed 2,209 unit and 264 integration cases, and Game Design completed 492 unit and 114 integration cases, with zero skips. Current-head CI is pending, so these results establish bounded source proof only. This selection source has no player-command caller and does not activate `PLAY`/`LOOK`; see [Player Access and Session](./player-access-and-session.md) for AA-2.1 status and [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) for the source boundary. Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple, and a separate source-only Account-facing current-attempt read. The latter returns the exact original pending attempt only while its owner lease and Account reference are live. Its composed Common/Game Session checks, generated SQL model, migration-version and documentation checks passed locally; PostgreSQL execution remains pending because the local database-dependent cases skipped. The RPC is not registered or deployed. The initial-admission owner-proof read returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. 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 Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither existing endpoint is deployed; those results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 27d3c3803f..fcc7f71969 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. @@ -147,7 +147,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. No focused executable proof: a genuine authenticated World terminal, failed-acquisition settlement, or composed runtime registration/admission. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. The initial private gameplay LOGIN source remains unregistered; runtime registration and caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java index 946b7b35de..c422c55ff0 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java @@ -133,9 +133,11 @@ void sameNamespaceGameSessionPeerReachesResolveAndDescriptorReadButBindingReadIs assertThat(resolve.dispatched()).isTrue(); assertThat(resolve.closedStatus()).isNull(); assertThat(resolve.response()).isNotNull(); + assertThat(resolve.response().getError().getCode()).isNotEqualTo("PERMISSION_DENIED"); assertThat(descriptorRead.dispatched()).isTrue(); assertThat(descriptorRead.closedStatus()).isNull(); assertThat(descriptorRead.response()).isNotNull(); + assertThat(descriptorRead.response().getError().getCode()).isNotEqualTo("PERMISSION_DENIED"); assertThat(completeRead.dispatched()).isTrue(); assertThat(completeRead.closedStatus()).isNull(); assertThat(completeRead.response()).isNotNull(); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java index 31ab94578b..2d81d48ebd 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcServiceTest.java @@ -1692,29 +1692,6 @@ void completeLaunchBindingDeniesCandidateBeforeRequestValidationOrOwnerRead() { Mockito.verifyNoInteractions(completeLaunchBindingService); } - @Test - void completeLaunchBindingDeniesCandidateBeforeTypedOwnerOutcome() { - UUID readRequestId = UUID.fromString("32345678-1234-4234-8234-123456789abc"); - String requestDigest = "sha256:" + "a".repeat(64); - String resultDigest = "sha256:" + "b".repeat(64); - var request = - GetLaunchDescriptorRequest.newBuilder() - .setRequestId(readRequestId.toString()) - .setCanonicalTenantId(CANONICAL_TENANT_ID.toString()) - .setWorldSlug("silver-march") - .setControlPlaneRequestId("cp-complete") - .setExpectedRequestDigest(requestDigest) - .setExpectedResultDigest(resultDigest) - .build(); - AtomicReference ref = - new AtomicReference<>(); - underLaunchPeer( - "game-session-service", () -> service.getCompleteLaunchBinding(request, observerFor(ref))); - - assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); - Mockito.verifyNoInteractions(completeLaunchBindingService); - } - @Test void compareAndSetVersionStateSameStateNoOpReturnsCurrentStateWithoutUpdatedFlag() { Mockito.when( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java index 79ac391b87..3faa05af4f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java @@ -72,7 +72,7 @@ public PublishedRealmEntryPolicySetEvidence listPublishedRealmEntryPolicies( requireNonNil(canonicalVersionId, "canonical version ID"); var currentStub = stub(); if (currentStub == null) { - throw new IllegalStateException( + throw new UninitializedClientException( "Game Design published realm policy client is not initialized"); } @@ -87,11 +87,23 @@ public PublishedRealmEntryPolicySetEvidence listPublishedRealmEntryPolicies( try { return PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(request, response); } catch (IllegalArgumentException invalid) { - throw new IllegalStateException( + throw new InvalidResponseException( "Game Design published realm policy response is invalid", invalid); } } + public static final class UninitializedClientException extends RuntimeException { + public UninitializedClientException(String message) { + super(message); + } + } + + public static final class InvalidResponseException extends RuntimeException { + public InvalidResponseException(String message, Throwable cause) { + super(message, cause); + } + } + private static void requireNonNil(UUID value, String label) { if (value == null || NIL_UUID.equals(value)) { throw new IllegalArgumentException("Canonical non-nil " + label + " is required"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java index 9cbe4afc27..afa6518c09 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequest.java @@ -67,8 +67,8 @@ public enum OriginKind { throw new IllegalArgumentException( "EXPECT_CLOSED requires a positive exact expectedPriorPointerVersion"); } - // The immutable compatibility audit's control_plane_request_id is varchar(120). - requireText(initialAdmissionRequestId, "initialAdmissionRequestId", 120); + // The retained owner attempt and compatibility audit both support 128 code points. + requireText(initialAdmissionRequestId, "initialAdmissionRequestId", 128); if (!REQUEST_DIGEST.matcher(Objects.requireNonNull(requestDigest, "requestDigest")).matches()) { throw new IllegalArgumentException( "requestDigest must be bare lowercase 64-character SHA-256 hex"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java index 6c90be7d0f..2b7427ce95 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service; +import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.util.List; import java.util.Objects; @@ -72,8 +73,8 @@ public Result select( CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot; try { snapshot = rosterClient.listPreseededRoster(current, authenticatedContext); - } catch (StatusRuntimeException unavailable) { - return new Denied(Denial.ROSTER_UNAVAILABLE); + } catch (StatusRuntimeException failure) { + return new Denied(rosterFailure(failure)); } catch (RuntimeException invalidOrUnavailable) { return new Denied(Denial.INVALID_ROSTER_PROOF); } @@ -88,6 +89,15 @@ public Result select( return new Denied(Denial.INVALID_ROSTER_PROOF); } + if (selector != null && !selector.isBlank()) { + if (expectedMenuIdentity == null) { + return new Denied(Denial.MISSING_MENU_IDENTITY); + } + if (!expectedMenuIdentity.matches(snapshot)) { + return new Denied(Denial.STALE_MENU_IDENTITY); + } + } + CanonicalGameplayActorSelection.SelectionResult selection = CanonicalGameplayActorSelection.select(validated.orElseThrow(), selector); if (selection instanceof CanonicalGameplayActorSelection.SelectionRequired required) { @@ -99,15 +109,6 @@ public Result select( return new Denied(mapSelectionDenial(denied.reason())); } - if (selector != null && !selector.isBlank()) { - if (expectedMenuIdentity == null) { - return new Denied(Denial.MISSING_MENU_IDENTITY); - } - if (!expectedMenuIdentity.matches(snapshot)) { - return new Denied(Denial.STALE_MENU_IDENTITY); - } - } - CanonicalGameplayActorSelection.Selected selected = (CanonicalGameplayActorSelection.Selected) selection; PlayerExecutionContext selectedContext = @@ -119,8 +120,8 @@ public Result select( CanonicalGameplayRosterClient.VerifiedPreseededAssignment ownerReference; try { ownerReference = rosterClient.readSelectedPreseededAssignment(snapshot, selectedContext); - } catch (StatusRuntimeException unavailable) { - return new Denied(Denial.ASSIGNMENT_UNAVAILABLE); + } catch (StatusRuntimeException failure) { + return new Denied(assignmentFailure(failure)); } catch (RuntimeException invalidOrUnavailable) { return new Denied(Denial.INVALID_ASSIGNMENT_PROOF); } @@ -152,12 +153,40 @@ private static Denial routeFailure(RuntimeException failure) { || failure instanceof CanonicalPublishedPlayerRouteReadService.StorageUnavailableException || failure instanceof CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException - || failure instanceof StatusRuntimeException) { + || failure instanceof StatusRuntimeException status && isTransient(status.getStatus())) { return Denial.ROUTE_UNAVAILABLE; } + if (failure instanceof StatusRuntimeException status + && status.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + return Denial.ROUTE_CHANGED; + } return Denial.INVALID_ROUTE_PROOF; } + private static Denial rosterFailure(StatusRuntimeException failure) { + Status status = failure.getStatus(); + if (isTransient(status)) { + return Denial.ROSTER_UNAVAILABLE; + } + if (status.getCode() == Status.Code.FAILED_PRECONDITION) { + return Denial.STALE_MENU_IDENTITY; + } + return Denial.INVALID_ROSTER_PROOF; + } + + private static Denial assignmentFailure(StatusRuntimeException failure) { + return isTransient(failure.getStatus()) + ? Denial.ASSIGNMENT_UNAVAILABLE + : Denial.INVALID_ASSIGNMENT_PROOF; + } + + private static boolean isTransient(Status status) { + return switch (status.getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, ABORTED -> true; + default -> false; + }; + } + private static Optional validateContext(PlayerExecutionContext context) { if (context == null || !context.getUnknownFields().asMap().isEmpty()) { return Optional.empty(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java index c1d266e897..1fd447c38f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service; +import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.util.Objects; import java.util.UUID; @@ -298,14 +299,32 @@ private PublishedRealmEntryPolicySetEvidence readPolicy( UUID canonicalTenantId, UUID canonicalVersionId) { try { return policyClient.listPublishedRealmEntryPolicies(canonicalTenantId, canonicalVersionId); - } catch (StatusRuntimeException | IllegalStateException unavailable) { + } catch (StatusRuntimeException failure) { + if (isTransient(failure.getStatus())) { + throw new GameDesignUnavailableException( + "Game Design policy transport is unavailable", failure); + } + if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { + throw new StaleAuthorityException("Game Design policy owner read is stale"); + } + throw new InvalidAuthorityException("Game Design policy owner read was rejected", failure); + } catch (GameDesignPublishedRealmPolicyClient.UninitializedClientException unavailable) { throw new GameDesignUnavailableException( "Game Design policy transport is unavailable", unavailable); + } catch (GameDesignPublishedRealmPolicyClient.InvalidResponseException invalid) { + throw new InvalidAuthorityException("Game Design policy response is invalid", invalid); } catch (IllegalArgumentException rejected) { throw new InvalidAuthorityException("Game Design policy owner read was rejected", rejected); } } + private static boolean isTransient(io.grpc.Status status) { + return switch (status.getCode()) { + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, ABORTED -> true; + default -> false; + }; + } + private PublishedRealmEntryPolicySetEvidence verifySet( PublishedRealmEntryPolicySetEvidence policySet) { if (policySet == null) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 323e6ab957..ce3c40a7fa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -131,7 +131,8 @@ void legacyNumericStartIsDeniedBeforePersistenceOrWorldPreparation() throws Exce .build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); - assertThat(response.statusCode()).isGreaterThanOrEqualTo(400); + assertThat(response.statusCode()).isEqualTo(400); + assertThat(response.body()).contains("FAILED_PRECONDITION"); assertThat(gameInstanceRepository.findAll()).hasSize(existingGameInstances); org.mockito.Mockito.verifyNoInteractions(worldManagementClient); } 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 74f802f4bb..bd8579d5d7 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 @@ -449,6 +449,35 @@ void reservesAndCommitsExactWorldHeldOpenWithPointerAuditAndOwnerReadback() { .isZero(); } + @Test + void retainsAndReadsBack128CharacterRequestIdentityFromOwnerAttempt() { + Fixture fixture = fixture(); + PreparedAdmission prepared = prepareAdmission(fixture); + String requestId = "r".repeat(128); + CanonicalInitialAdmissionRequest request = + initialAdmissionRequest( + prepared.catalog(), + prepared.binding(), + requestId, + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + uuid(115), + uuid(116)); + + fixture.transactions.execute( + status -> { + fixture.initialAdmissionRepository.reserve(request); + return null; + }); + + CanonicalInitialAdmissionOwnerProof retained = + fixture.initialAdmissionRepository.read(NAMESPACE, requestId).orElseThrow(); + assertThat(retained.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); + assertThat(retained.initialAdmissionRequestId()).isEqualTo(requestId); + assertThat(retained.holdId()).isEqualTo(request.holdId()); + assertThat(retained.holdFence()).isEqualTo(request.holdFence()); + } + @Test void newNoPriorPointerReservationRejectsAnAlreadyOpenRealmWithoutLeavingPendingAttempt() { Fixture fixture = fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java index cf2617292e..245fdb3afe 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -93,7 +93,7 @@ void rejectsUninitializedClientAndPropagatesUnavailableOwner() throws Exception var channelFactory = mock(GrpcChannelFactory.class); var uninitialized = newClientWithoutStub(channelFactory); assertThatThrownBy(() -> uninitialized.listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) - .isInstanceOf(IllegalStateException.class) + .isInstanceOf(GameDesignPublishedRealmPolicyClient.UninitializedClientException.class) .hasMessageContaining("not initialized"); verifyNoInteractions(channelFactory); @@ -122,7 +122,7 @@ void rejectsChangedRequestUnknownFieldsAndMalformedClosedEvidence() throws Excep .build(); }); assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) - .isInstanceOf(IllegalStateException.class) + .isInstanceOf(GameDesignPublishedRealmPolicyClient.InvalidResponseException.class) .hasMessageContaining("response is invalid"); doAnswer( @@ -136,7 +136,7 @@ void rejectsChangedRequestUnknownFieldsAndMalformedClosedEvidence() throws Excep .when(stub) .listPublishedRealmEntryPolicies(any()); assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(GameDesignPublishedRealmPolicyClient.InvalidResponseException.class); doAnswer( invocation -> { @@ -153,7 +153,7 @@ void rejectsChangedRequestUnknownFieldsAndMalformedClosedEvidence() throws Excep .when(stub) .listPublishedRealmEntryPolicies(any()); assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) - .isInstanceOf(IllegalStateException.class); + .isInstanceOf(GameDesignPublishedRealmPolicyClient.InvalidResponseException.class); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java index 529936b386..8ee230ea6a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java @@ -29,6 +29,27 @@ void gameSessionRequestDigestIsBareAndWorldBindingDigestRemainsDistinct() { assertThat(request.canonicalVersionId()).isEqualTo(CANONICAL_VERSION); } + @Test + void requestIdentityAccepts121And128CodePointsAndRejects129() { + assertThat(requestWithId("r".repeat(121)).initialAdmissionRequestId()).hasSize(121); + assertThat(requestWithId("r".repeat(128)).initialAdmissionRequestId()).hasSize(128); + + assertThatThrownBy(() -> requestWithId("r".repeat(129))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("1..128 characters"); + } + + @Test + void requestIdentityLimitCountsUnicodeCodePoints() { + String requestId = "😀".repeat(128); + + assertThat(requestId).hasSize(256); + assertThat(requestWithId(requestId).initialAdmissionRequestId()).isEqualTo(requestId); + assertThatThrownBy(() -> requestWithId("😀".repeat(129))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("1..128 characters"); + } + @Test void bothOriginsRequireTheirExactPriorPointerShape() { assertThatThrownBy( @@ -139,7 +160,10 @@ void unauthenticatedDefaultWorldVerifierNeverTreatsCallerTupleAsOwnerProof() { } private static CanonicalInitialAdmissionRequest noPriorRequest() { - String requestId = "gs-initial-admission-17"; + return requestWithId("gs-initial-admission-17"); + } + + private static CanonicalInitialAdmissionRequest requestWithId(String requestId) { String digest = CanonicalInitialAdmissionRequest.computeRequestDigest( "prod", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index e9d2b03278..8800a594ff 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -238,24 +238,27 @@ void rejectsAnEntitySnapshotWithAnotherAccountOrTargetBeforeSelectedRead() throw @Test void returnsExplicitSelectionAndSelectorDenialsWithoutAssignmentReads() throws Exception { var multiple = harness(twoActors()); - assertThat( + var menu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) multiple .service() .select( - context(multiple.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null)) - .isInstanceOf(CanonicalGameplayRosterSelectionService.SelectionRequired.class); + context(multiple.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); assertDenied( multiple .service() .select( context(multiple.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), "Pilot Two", - null), + menu.menuIdentity()), CanonicalGameplayRosterSelectionService.Denial.INVALID_SELECTOR); assertDenied( multiple .service() - .select(context(multiple.route(), "abababab-abab-4bab-8bab-abababababab"), "3", null), + .select( + context(multiple.route(), "abababab-abab-4bab-8bab-abababababab"), + "3", + menu.menuIdentity()), CanonicalGameplayRosterSelectionService.Denial.SELECTOR_OUT_OF_RANGE); verify(multiple.stub(), never()).readSelectedPreseededAssignment(any()); @@ -363,6 +366,44 @@ void rejectsChangedMenuSnapshotUuidAndReorderedRosterBeforeAssignmentRead() thro verify(reorderedRoster.stub(), never()).readSelectedPreseededAssignment(any()); } + @Test + void staleMenuIdentityPrecedesOrdinalResolutionAgainstARefreshedSmallerRoster() throws Exception { + var harness = harness(twoActors()); + AtomicInteger reads = new AtomicInteger(); + doAnswer( + invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + boolean firstRead = reads.getAndIncrement() == 0; + return rosterResponse( + request, + ACCOUNT, + request.getExpectedTarget(), + firstRead + ? twoActors() + : List.of( + new CanonicalGameplayRosterClient.RosterActor(FIRST_ACTOR, "Pilot One")), + firstRead ? SNAPSHOT : CHANGED_SNAPSHOT); + }) + .when(harness.stub()) + .listPreseededRoster(any()); + + var menu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + harness + .service() + .select( + context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null); + assertDenied( + harness + .service() + .select( + context(harness.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "2", + menu.menuIdentity()), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + verify(harness.stub(), never()).readSelectedPreseededAssignment(any()); + } + @Test void rejectsMovedRouteAfterRosterAndAfterAssignmentNetworkEvidence() throws Exception { var changedAfterList = harness(oneActor()); @@ -422,6 +463,131 @@ void rejectsChangedAssignmentSnapshotAndUnavailableEntityBackend() throws Except verify(unavailable.stub(), never()).readSelectedPreseededAssignment(any()); } + @Test + void mapsEntityGrpcFailuresByStatusAndReadBoundary() throws Exception { + for (Status.Code code : + List.of( + Status.Code.UNAVAILABLE, + Status.Code.DEADLINE_EXCEEDED, + Status.Code.RESOURCE_EXHAUSTED, + Status.Code.ABORTED)) { + var rosterUnavailable = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("Entity read failed").asRuntimeException()) + .when(rosterUnavailable.stub()) + .listPreseededRoster(any()); + assertDenied( + rosterUnavailable + .service() + .select( + context(rosterUnavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); + + var assignmentUnavailable = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("Entity read failed").asRuntimeException()) + .when(assignmentUnavailable.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + assignmentUnavailable + .service() + .select( + context(assignmentUnavailable.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ASSIGNMENT_UNAVAILABLE); + } + + var staleRoster = harness(oneActor()); + doThrow(Status.FAILED_PRECONDITION.withDescription("menu changed").asRuntimeException()) + .when(staleRoster.stub()) + .listPreseededRoster(any()); + assertDenied( + staleRoster + .service() + .select( + context(staleRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + + var changedAssignment = harness(oneActor()); + doThrow(Status.FAILED_PRECONDITION.withDescription("assignment changed").asRuntimeException()) + .when(changedAssignment.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + changedAssignment + .service() + .select( + context(changedAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); + + var rejectedRoster = harness(oneActor()); + doThrow(Status.PERMISSION_DENIED.withDescription("caller rejected").asRuntimeException()) + .when(rejectedRoster.stub()) + .listPreseededRoster(any()); + assertDenied( + rejectedRoster + .service() + .select( + context(rejectedRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + + for (Status.Code code : List.of(Status.Code.PERMISSION_DENIED, Status.Code.INVALID_ARGUMENT)) { + var invalidRoster = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("roster rejected").asRuntimeException()) + .when(invalidRoster.stub()) + .listPreseededRoster(any()); + assertDenied( + invalidRoster + .service() + .select( + context(invalidRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + + var invalidAssignment = harness(oneActor()); + doThrow(Status.fromCode(code).withDescription("assignment rejected").asRuntimeException()) + .when(invalidAssignment.stub()) + .readSelectedPreseededAssignment(any()); + assertDenied( + invalidAssignment + .service() + .select( + context(invalidAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); + } + + var staleRoute = harness(oneActor()); + doThrow(Status.FAILED_PRECONDITION.withDescription("route changed").asRuntimeException()) + .when(staleRoute.policyClient()) + .listPublishedRealmEntryPolicies( + staleRoute.route().canonicalTenantId(), staleRoute.route().canonicalVersionId()); + assertDenied( + staleRoute + .service() + .select( + context(staleRoute.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + + var invalidRoute = harness(oneActor()); + doThrow(Status.PERMISSION_DENIED.withDescription("route rejected").asRuntimeException()) + .when(invalidRoute.policyClient()) + .listPublishedRealmEntryPolicies( + invalidRoute.route().canonicalTenantId(), invalidRoute.route().canonicalVersionId()); + assertDenied( + invalidRoute + .service() + .select( + context(invalidRoute.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROUTE_PROOF); + } + @Test void deniesAmbientTransactionBeforeAnyRouteOrOwnerRead() throws Exception { var harness = harness(oneActor()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java index d8caec3dc5..6bc4db9477 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java @@ -119,6 +119,56 @@ void storageAndGameDesignTransportFailuresRemainDistinctAndReturnNoRoute() { CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException.class); } + @Test + void classifiesGameDesignPolicyFailuresWithoutTreatingRejectedEvidenceAsUnavailable() { + for (io.grpc.Status.Code code : + java.util.List.of( + io.grpc.Status.Code.UNAVAILABLE, + io.grpc.Status.Code.DEADLINE_EXCEEDED, + io.grpc.Status.Code.RESOURCE_EXHAUSTED, + io.grpc.Status.Code.ABORTED)) { + var f = fixture(); + when(f.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow(io.grpc.Status.fromCode(code).asRuntimeException()); + assertThatThrownBy(() -> f.service().readCurrent(f.route())) + .isInstanceOf( + CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException.class); + } + + var stale = fixture(); + when(stale.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow(io.grpc.Status.FAILED_PRECONDITION.asRuntimeException()); + assertThatThrownBy(() -> stale.service().readCurrent(stale.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + + for (io.grpc.Status.Code code : + java.util.List.of( + io.grpc.Status.Code.PERMISSION_DENIED, io.grpc.Status.Code.INVALID_ARGUMENT)) { + var rejected = fixture(); + when(rejected.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow(io.grpc.Status.fromCode(code).asRuntimeException()); + assertThatThrownBy(() -> rejected.service().readCurrent(rejected.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + } + + var uninitialized = fixture(); + when(uninitialized.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow( + new GameDesignPublishedRealmPolicyClient.UninitializedClientException( + "not initialized")); + assertThatThrownBy(() -> uninitialized.service().readCurrent(uninitialized.route())) + .isInstanceOf( + CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException.class); + + var invalidResponse = fixture(); + when(invalidResponse.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenThrow( + new GameDesignPublishedRealmPolicyClient.InvalidResponseException( + "malformed response", new IllegalArgumentException("invalid evidence"))); + assertThatThrownBy(() -> invalidResponse.service().readCurrent(invalidResponse.route())) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class); + } + @Test void missingCompleteGameDesignPolicySetFailsClosed() { var f = fixture(); From 82cc9ecc1ab4d242e03c09294592dc53297eba32 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:23:33 +1300 Subject: [PATCH 28/34] Fix roster denial mappings and review proof alignment --- .../game-design-service/README.md | 2 +- .../game-design-service/api-contracts.md | 6 +- .../game-design-service/game-templates.md | 4 +- .../game-session-service/api-contracts.md | 15 ++- .../game-session-service/runtime-and-data.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 +- .../player-access-and-session.md | 2 +- ...nonicalGameplayRosterSelectionService.java | 13 ++- ...eDesignPublishedRealmPolicyClientTest.java | 2 +- ...calGameplayRosterSelectionServiceTest.java | 37 +++---- .../CanonicalPlayerRouteReadServiceTest.java | 51 +++++++-- ...alPublishedPlayerRouteReadServiceTest.java | 100 ++++++++++++++++-- .../PublishedRealmPolicyEvidenceFixture.java | 2 +- 13 files changed, 185 insertions(+), 53 deletions(-) diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 338f352b8f..2b3ac67581 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -18,7 +18,7 @@ Current capability and proof gaps remain: Game Session's exact pin/epoch persist ### Authored-World Launch Boundary -The canonical authored-world launch slice includes source-qualified ResolveLaunchDescriptor, exact independent GetLaunchDescriptor, and GetCompleteLaunchBinding returning descriptor and release-attestation evidence separately. Game Session's evidence-only preparation and focused proof sources are present, but validation is deferred until published A/B/C dependencies are integrated. Numeric launch selectors are non-authorizing. +The canonical authored-world launch slice includes source-qualified ResolveLaunchDescriptor, exact independent GetLaunchDescriptor, and GetCompleteLaunchBinding returning descriptor and release-attestation evidence separately. Game Session's evidence-only preparation and focused proof sources are present; capability and proof gaps are recorded in the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#launch-activation-cutover-and-termination). Numeric launch selectors are non-authorizing. ## Responsibilities diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index ba2ef2f4d4..35906be9c3 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -12,7 +12,7 @@ Launch resolution is authorized by an exact canonical authored-world source, not GetLaunchDescriptor is a separate exact read using a fresh non-nil read-request UUID, canonical tenant UUID, world slug, control-plane request ID, and expected request/result digests. A caller compares this committed readback with the original resolve response; a successful resolve response alone is not committed-evidence proof. GetCompleteLaunchBinding reads the same exact descriptor together with its matching immutable full-version release attestation, including participant digests and manifest/artifact evidence. Descriptor evidence and release attestation remain separate digested objects and must not be substituted for one another. These reads are read-only and do not authorize Game Session instance creation, World activation, admission, or PLAY. -The target caller matrix is: launch resolution accepts only the exact same-namespace Game Session workload identity; descriptor readback accepts same-namespace Game Session or World Management; complete-binding readback accepts same-namespace Game Session, World Management, or Entity Management. All reject absent/malformed peer identity, noncanonical or nil UUIDs, and unknown request fields before owner reads. Legacy numeric Game Session launch selectors fail closed and are not translated into this contract. +The target caller matrix is: launch resolution accepts only the exact same-namespace Game Session workload identity; descriptor readback accepts same-namespace Game Session or World Management; complete-binding readback accepts same-namespace Game Session, World Management, or Entity Management. Target behavior rejects absent/malformed peer identity, noncanonical or nil UUIDs, and unknown request fields before owner reads. Legacy numeric Game Session launch selectors fail closed and are not translated into this contract. Current limitation: `GetCompleteLaunchBinding` authenticates those exact same-namespace candidate peers and then returns `PERMISSION_DENIED` before request validation or owner reads. No production owner-read permission or activation authority is enabled; see the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#launch-activation-cutover-and-termination). @@ -144,7 +144,7 @@ The published realm-policy owner read is present behind the default-off `firemud - `GetPublishedReleaseBundle` – authoritative read surface for immutable release attestation used by activation, cutover preflight, and repair workflows. It also carries the canonical publish workflow identity and workflow-runtime status for operators. `NOT_FOUND` means the target version is not publish-complete; `SCHEMA_VERSION_UNSUPPORTED` means callers must fail closed until they understand the attestation schema. - `ResolveLaunchDescriptor` – resolves an exact canonical authored-world source, tenant/world selector, template, and closed optional override tuple into one immutable source-qualified descriptor. The descriptor contains request/result digests and source operation/evidence identity; exact retries replay the stored outcome, and changed reuse fails closed. - `GetLaunchDescriptor` – independently reads the exact committed descriptor by read-request UUID, canonical tenant, world slug, control-plane request ID, and expected request/result digests. -- `GetCompleteLaunchBinding` – returns that exact descriptor together with its matching full-version release attestation and artifact/manifest evidence; it does not infer or authorize runtime admission. +- `GetCompleteLaunchBinding` – **Target behavior:** returns that exact descriptor together with its matching full-version release attestation and artifact/manifest evidence; it does not infer or authorize runtime admission. **Current behavior:** authenticates the exact same-namespace candidate peer, then returns `PERMISSION_DENIED` before request validation or owner reads. - `CreateTemplateRemapSet` / `ApproveTemplateRemapSet` / `GetTemplateRemapSet` – authoritative control-plane APIs for persisted version-to-version remap identities and their audit history. Game Design owns the `remapSetId` namespace consumed by replacement launch resolution and later cutover preflight. - `CanDeleteVersionAssets` – deletion-eligibility oracle for version-scoped asset prefixes. - `BeginPurgeVersionAssets` – **Target state:** CAS-guarded purge start that atomically re-checks deletion eligibility and transitions `version_asset_artifact` into purge-in-progress state. The current implementation has no database CAS or shared idempotency ledger. @@ -224,7 +224,7 @@ Detailed request and response schemas are defined in the [OpenAPI specification] - `GetPublishedReleaseBundle(GetPublishedReleaseBundleRequest) returns (GetPublishedReleaseBundleResponse)` – **Target response:** returns the immutable `(tenantId, versionId)` release attestation including participant digests, the dedicated Game Logic-owned `abilitySchemaDigest` for the same target commit (using Game Logic's existing participant `digestSchemaVersion` and canonicalization evidence), any required `artifactDigests[]` and `requiredManifestAssetKeys[]` for exported derived assets, `manifestHash`, `generationConfigRevision`, and the canonical publish workflow runtime metadata (`publishWorkflowId`, `workflowRunId`, `workflowStatus`). **Current live response/compatibility path:** the implementation still uses the attested `AUTOMATION_SCRIPTING` aggregate participant digest in place of the dedicated ability-schema field; that aggregate is not ability-schema proof, so consumers must fail closed until the target field and evidence converge. Missing, unsupported, or mismatched ability-schema evidence fails closed. Missing attestation must surface as `NOT_FOUND`, and unreadable attestation schema must surface as `SCHEMA_VERSION_UNSUPPORTED`. - `ResolveLaunchDescriptor(ResolveLaunchDescriptorRequest) returns (ResolveLaunchDescriptorResponse)` – resolves a source-qualified canonical authored-world request and returns a descriptor carrying the complete request/result evidence. - `GetLaunchDescriptor(GetLaunchDescriptorRequest) returns (GetLaunchDescriptorResponse)` – performs an independent committed read using exact tenant, world, request, and expected-digest selectors. -- `GetCompleteLaunchBinding(GetLaunchDescriptorRequest) returns (GetCompleteLaunchBindingResponse)` – returns the exact descriptor plus a matching immutable release attestation; callers must compare both complete evidence objects. +- `GetCompleteLaunchBinding(GetLaunchDescriptorRequest) returns (GetCompleteLaunchBindingResponse)` – **Target behavior:** returns the exact descriptor plus a matching immutable release attestation; callers must compare both complete evidence objects. **Current behavior:** authenticates the exact same-namespace candidate peer, then returns `PERMISSION_DENIED` before request validation or owner reads. - `CreateTemplateRemapSet(CreateTemplateRemapSetRequest) returns (CreateTemplateRemapSetResponse)` – persists a draft remap set for a concrete `(tenantId, sourceVersionId, targetVersionId)` pair. - `ApproveTemplateRemapSet(ApproveTemplateRemapSetRequest) returns (ApproveTemplateRemapSetResponse)` – marks a persisted remap set approved for launch/cutover consumers and records approval reason. - `GetTemplateRemapSet(GetTemplateRemapSetRequest) returns (GetTemplateRemapSetResponse)` – returns the canonical remap-set payload and approval state for an existing `remapSetId`. diff --git a/design/architecture/microservices/game-design-service/game-templates.md b/design/architecture/microservices/game-design-service/game-templates.md index 0580f27d9c..d02b292f3e 100644 --- a/design/architecture/microservices/game-design-service/game-templates.md +++ b/design/architecture/microservices/game-design-service/game-templates.md @@ -245,9 +245,9 @@ These target-only fields do not replace or relax the current authored-world sour Before computing the request idempotency digest, normalization rejects `EMPTY` with a non-empty list, `EXPLICIT` with an empty list, and `REUSE_ROLLBACK_TARGET` without a named rollback target or with any entries; accepted presence forms must first derive the modes and effective selections defined above consistently. -Normative examples: +Target-only conceptual extension illustrations (not the current wire contract or executable RPC examples): -The examples below intentionally use numeric `versionId` values because the current Game Design launch and published-bundle protobuf contracts expose `int64 version_id`. UUID-shaped version identifiers elsewhere in the target architecture must not be substituted into these current-contract examples until those transport fields are migrated together. +The current authored-world binding wire contract is defined by the [Game Design API contract](./api-contracts.md#authored-world-launch-binding) and [Game Design proto](../../../../protos/game-design/v1/game_design_service.proto). The current launch and published-bundle protobuf contracts expose numeric `int64 version_id`, so these illustrations retain numeric `versionId` values. The plugin-selection and rollback fields shown below are conceptual target extensions and are not current transport fields or executable requests. - Fresh launch from a template with no script patch pinned: diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 62c5a298bb..7552344320 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -36,7 +36,7 @@ For script transitions, the live boundary includes the exact `scriptPinEpoch` an Game Session communicates with other platform services exclusively via gRPC for gameplay-domain work. Player-delegated calls carry the typed unsigned `PlayerExecutionContext` defined in the authentication architecture, including the required gameplay scope for admission. Downstream services authenticate the concrete mTLS caller, enforce an exact RPC caller allowlist, validate context/request equality and domain scope, and reject client-supplied identity metadata. Routine gameplay calls do not use signed per-action attestations or a generic replay cache; mutations retain their owning command/effect/request idempotency. -The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality; context `playable_state_scope` is the exact text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. Its response echoes discovery bindings and returns the original assignment operation UUID and immutable intent digest from Entity's unique matching committed receipt. Game Session binds and reuses that original reference for later owner revalidation; it does not mint an assignment identity or treat the reference as admission proof or current Account eligibility. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This wire currently has no handler or activation, and its policy does not authorize other roster branches or actor admission. +The Entity `CanonicalGameplayRosterService` calls for `PRESEEDED_ONLY` are pre-admission discovery reads, not already-admitted player actions. Game Session supplies a server-derived `PlayerExecutionContext` containing authenticated account, session, request, and the prospective tenant/realm/namespace/scope/instance target, and calls under the exact same-namespace Game Session mTLS identity allowlisted for each method. Entity requires exact context/request/target equality; context `playable_state_scope` is the exact text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster request has no selected actor or admitted-character/current-binding requirement; for `ReadSelectedPreseededAssignment`, `context.character_id` equals `selected_character_uuid`. Its response echoes discovery bindings and returns the original assignment operation UUID and immutable intent digest from Entity's unique matching committed receipt. Game Session binds and reuses that original reference for later owner revalidation; it does not mint an assignment identity or treat the reference as admission proof or current Account eligibility. The unsigned context is scope data, not a credential, and these reads add no Account lookup solely for authorization. This Game Session source slice introduces no Entity handler or activation; [Entity API contracts](../entity-management-service/api-contracts.md#grpc) record the owning implementation status. The wire policy does not authorize other roster branches or actor admission. For target gameplay forwarding, `PlayerExecutionContext` carries the server-resolved `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId}` binding and, for region-scoped work, its `{regionId, regionEpoch}` fence as one context. Game Session forwards the namespace and scope unchanged and validates exact context/request equality on every downstream response or mutation result; it never accepts a caller-selected namespace or substitutes a current one after admission. The current context/forwarding wire is narrower in places and does not yet carry or prove this complete namespace-plus-fence tuple, so that path remains an implementation/proof gap and must fail closed on missing authority. @@ -63,21 +63,26 @@ Lost responses reconcile through the exact hold identity and authoritative World The first admission-pointer bind for a realm is a separate owner transaction from replacement cutover. Game Session owns a durable attempt ledger with one stable request identity and canonical digest, plus the terminal outcome `COMMITTED` or `ABORTED`. Its initial pointer transaction must prove that no pointer exists for the exact `{tenantId, realmId}` and atomically bind the World-issued initial-bind hold identity/fence, the same request identity/digest, `{tenantId, realmId, playableStateNamespaceId, playableStateScope}`, target `gameInstanceId`/`versionId` and exact `ACTIVE` lifecycle epoch, and `catalogRevision` with the new pointer and matching append-only audit event. The durable `COMMITTED` attempt outcome commits in that same transaction. This owner-side no-prior-pointer check is not replaced by a bootstrap snapshot, startup configuration, public raw-pointer RPC, or external operator write bypass. 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). + +### Canonical gameplay roster owner reads + +#### Canonical gameplay roster owner read + The internal `CanonicalGameplayRosterOwnerReadService.GetCanonicalGameplayRosterOwnerRead` method is an Entity-only point-in-time source read. It requires the exact same-namespace Entity Management mTLS workload and no authenticated caller context; the request retains its exact caller-observed pointer-version and World-epoch preconditions. The route-reader composition is disabled unless `firemud.canonical-gameplay-roster-owner-read.enabled=true`; the bearer-check allowlist does not enable its source beans. The read returns source evidence only and does not create actors, bind sessions, or activate `PLAY` or `LOOK`. For the Entity-only canonical roster-owner read, Game Session returns `admissionPointerSnapshotDigest` from [`CanonicalInitialAdmissionRepository.readCurrentOpenSnapshotForRealm`](../../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java) only after validating one current V3 `OPEN` pointer, matching its exact durable `COMMITTED` attempt and append-only audit readback, and confirming the entire pointer row is unchanged across the before/after read. Its raw lowercase 64-hex SHA-256 preimage has domain `gs-canonical-current-open-pointer-snapshot/v1` and, in fixed order, binds: representation version; target namespace; canonical tenant UUID; world slug/display name; realm UUID/slug/display name; playable-state namespace UUID and scope; positive catalog revision and pointer version; admission state; visible and public-production flags; the required-null character-selection flag; character-creation policy; canonical game-instance and version UUIDs; initial-admission request ID/digest; origin kind and nullable expected prior-pointer version; positive active World epoch; hold UUID/fence/binding digest; last-updated actor/reason; the required-null prepared-version-upgrade ID; committed outcome; owner proof digest; positive audit event ID; and terminal timestamp. `pointer.updated_at` and audit occurrence time are validated against that terminal timestamp before hashing. Pointer surrogate ID, retained numeric tenant/game-instance/runtime-version IDs, and row creation time are not canonical identity inputs; canonical UUIDs remain the identity. Encoding is closed and unambiguous: strings use strict UTF-8 with a signed 32-bit byte length (`-1` only for null), without Unicode normalization; UUIDs are lowercase canonical strings; representation version is fixed-width big-endian int32; every long counter uses the unique base-10 `Long.toString()` representation in the same length-prefixed UTF-8 form; booleans use one byte; nullable booleans use `0=null`, `1=false`, `2=true`; nullable prior-pointer versions use a presence boolean followed by the canonical decimal counter string when present; and the terminal instant uses canonical UTC `Instant.toString()` after database-microsecond validation. The [Common evidence carrier](../../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java) and [roster-read response proto](../../../../protos/game-session/v1/canonical_gameplay_roster_owner_read.proto) transport this exact digest; they do not recompute it or treat it as a second authority. It is a point-in-time current-pointer commitment, not a permission spanning a later mutation, a fresh lifecycle check, membership proof, actor ownership, or `PLAY` admission. The opaque committed owner-proof digest is included as evidence; it is not a mapping from a retained numeric row key to canonical identity. -### Entity preseeded-actor assignment source read +#### Entity preseeded-actor assignment source read `CanonicalGameplayRosterOwnerReadService.GetPreseededActorAssignmentOwnerRead` is an internal, Entity-only source read for non-admitting PRESEEDED actor assignment. It requires Entity Management's exact same-namespace workload identity over mTLS and no authenticated caller context. Its request selects the canonical Account and tenant plus the exact immutable realm, namespace/scope, current instance/version, catalog, policy-digest, and release selectors. It does not accept `pointerVersion` or `activeWorldEpoch`: Game Session derives both from its current OPEN pointer and terminal COMMITTED World-hold proof, then checks the complete current catalog, launch binding, and sealed Game Design policy set and rereads them before returning the request-bound evidence. The response carries the complete source proof and policy-set evidence plus the current pointer projection digest. Entity consumer code remains outside this Game Session source slice. The read itself is not permission to mutate actor data; Account remains the identity and membership authority, and this source method is not `JOIN` or `PLAY` admission. -Game Session also exposes a default-off `CanonicalGameplayRosterSelectionService` composition for its existing typed Entity roster reads. It accepts a `PlayerExecutionContext` already constructed from authenticated Game Session state, binds its tenant, realm, namespace, scope, and instance to the current published route, and accepts only a one-based ordinal from the validated Entity snapshot. It rereads the exact published route after each Entity read and returns only a selection menu, denial, or Entity's original assignment reference. This source-only composition consumes the existing Entity methods but does not establish membership or admission, persist a selection, bind a session, or activate `PLAY` or `LOOK`; Entity remains the assignment-evidence owner, including later revalidation. - -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). +Game Session exposes a default-off `CanonicalGameplayRosterSelectionService` composition whose intended Entity reads use the typed roster wire contract defined in [Entity API contracts](../entity-management-service/api-contracts.md#grpc). No Entity handler or activation is introduced by this Game Session source slice; the Entity contract records its owning implementation and proof status. The composition accepts a `PlayerExecutionContext` already constructed from authenticated Game Session state, binds its tenant, realm, namespace, scope, and instance to the current published route, and accepts only a one-based ordinal from the validated Entity snapshot. It rereads the exact published route after each Entity read and returns only a selection menu, denial, or Entity's original assignment reference. This source-only composition does not establish membership or admission, persist a selection, bind a session, change gameplay state, or activate `PLAY` or `LOOK`; Entity remains the assignment-evidence owner, including later revalidation. ## Session Front-End and Lease-Owner Routing diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 4e25e75275..53663768a1 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -59,7 +59,7 @@ The sections below define the target-state runtime contract. Current implementat Game Session does not persist or allocate the primary actor. It resolves the realm target, asks Entity Management for the valid roster/policy result, and keeps `CHARS` as discovery before `PLAY`. A normal binding requires one persisted `characterId`; controller uniqueness is `{tenantId, playableStateNamespaceId, characterId}`, with `accountId` owner evidence and `playableStateScope`, `gameInstanceId`, and region/epoch as routing/fence evidence. See [Entity Runtime and Data](../entity-management-service/runtime-and-data.md) for allocation, policy, descriptor/template, and fork-copy rules. -The current Game Session route and published-policy readers, plus the Entity-only roster and preseeded-assignment source reads, remain behind default-off composition. They return bounded source evidence; they do not persist actor assignments, attach a gameplay session, or activate `PLAY`/`LOOK`. See [API Contracts](./api-contracts.md#initial-admission-bind) for the local read boundary. +The current Game Session route and published-policy readers, plus the Entity-only roster and preseeded-assignment source reads, remain behind default-off composition. They return bounded source evidence; they do not persist actor assignments, attach a gameplay session, or activate `PLAY`/`LOOK`. See [API Contracts](./api-contracts.md#canonical-gameplay-roster-owner-reads) for the local read boundary. The local runtime stores only active attachment, protocol state, presence, and controller-fence data. A playtest copy is selected by its new fork-local `characterId`; `sourceCharacterId` is not used as authority. Current per-instance lookup, unresolved-character fallback, and complete cross-service proof remain gaps. 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 78d6c301e3..2ba7c21cb0 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 @@ -14,7 +14,7 @@ Focused unit tests cover immutable replay, descriptor comparison, certificate-pi This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -The Entity-only roster and preseeded-assignment owner reads are a separate default-off, read-only source boundary; they do not change tick execution, attach sessions, or activate `PLAY`/`LOOK`. The focused [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) proof executed in source Validation `38362401283` on published `65bf7294a906df9fc7fdd3150ddc94572c60dc09`: Game Session completed 2,209 unit and 264 integration cases, and Game Design completed 492 unit and 114 integration cases, with zero skips. Current-head CI is pending, so these results establish bounded source proof only. This selection source has no player-command caller and does not activate `PLAY`/`LOOK`; see [Player Access and Session](./player-access-and-session.md) for AA-2.1 status and [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) for the source boundary. +The Entity-only roster and preseeded-assignment owner reads are a separate default-off, read-only source boundary; they do not change tick execution, attach sessions, or activate `PLAY`/`LOOK`. The focused [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) proof executed in source Validation `38362401283` on published `65bf7294a906df9fc7fdd3150ddc94572c60dc09`: Game Session completed 2,209 unit and 264 integration cases, and Game Design completed 492 unit and 114 integration cases, with zero skips. Current-head CI is pending, so these results establish bounded source proof only. This selection source has no player-command caller and does not activate `PLAY`/`LOOK`; see [Player Access and Session](./player-access-and-session.md) for AA-2.1 status and [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) for the source boundary. Local Game Session producer code includes an unregistered historical original-StartSession evidence read for exact same-namespace World or Account workloads, an unregistered World-only initial-admission owner-proof read bound to the configured namespace and full hold tuple, and a separate source-only Account-facing current-attempt read. The latter returns the exact original pending attempt only while its owner lease and Account reference are live. Its composed Common/Game Session checks, generated SQL model, migration-version and documentation checks passed locally; PostgreSQL execution remains pending because the local database-dependent cases skipped. The RPC is not registered or deployed. The initial-admission owner-proof read returns a point-in-time `PENDING` snapshot or a terminal result backed by a positive `COMMITTED` pointer with matching audit or a durable `ABORTED` outcome. 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 Game Session cases; all 2,327 cases passed with zero skips, failures, or errors. Its JUnit artifact includes the owner-proof and original-owner tests plus the PostgreSQL-backed owner-attempt, association, descriptor, and initial-admission fixtures. Neither existing endpoint is deployed; those results do not establish continuous hold protection through cross-owner commit, terminal composition, restart recovery, production activation, or playable-state closure. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index fcc7f71969..1973b6f4de 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). +Game Session now carries a default-off source path for current route and published-policy evidence and a non-admitting composition over its typed Entity roster reads. The composition binds the authenticated canonical `PlayerExecutionContext` to the exact published route, validates the Entity roster, accepts only an ordinal, reads Entity's original selected-assignment reference, and rereads the route after each Entity call. Focused local proof passed using real route readers, roster-client validation, actor selection, controlled repository doubles, and a controlled gRPC transport; it covers success, multi-actor menu and ordinal selection, account/namespace/realm/instance mismatches, changed route and assignment snapshot evidence, non-OK Entity responses, no selected read after invalid roster evidence, and ambient-transaction denial. This does not establish live database or owner-RPC execution. The [CanonicalGameplayRosterSelectionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java) and [CanonicalGameplayRosterSelectionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java) provide the bounded executed proof anchors. Existing Entity-side owner handling and proof remain unchanged; this slice adds no player-command caller or `PLAY`/`LOOK` activation. `AA-2.1` remains partial. See the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#canonical-gameplay-roster-owner-reads) and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). The Account source-currentness/first-JOIN persistence stage builds on the tested V30–V39 storage and retention-safety prerequisite. It preserves V40 fresh source-baseline hooks, canonical source/event proof, and the complete owner-local first-JOIN coordinator rather than dropping them to reduce scope. Earlier source-stage checkpoints have reported unit and integration-source proof; physical PostgreSQL proof for the current reconciled cut remains unavailable. The parent's 493 unit tests and 13 targeted physical PostgreSQL cases across separate runs cover only storage/currentness. These primitives do not supply authenticated public JOIN, the cross-service target-through-commit gate, Game Session text JOIN, or playable proof. Existing #2898/#2848 gaps and capability statuses remain unchanged. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java index 2b7427ce95..fec66c6ef4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java @@ -169,15 +169,20 @@ private static Denial rosterFailure(StatusRuntimeException failure) { return Denial.ROSTER_UNAVAILABLE; } if (status.getCode() == Status.Code.FAILED_PRECONDITION) { - return Denial.STALE_MENU_IDENTITY; + return Denial.ROUTE_CHANGED; } return Denial.INVALID_ROSTER_PROOF; } private static Denial assignmentFailure(StatusRuntimeException failure) { - return isTransient(failure.getStatus()) - ? Denial.ASSIGNMENT_UNAVAILABLE - : Denial.INVALID_ASSIGNMENT_PROOF; + Status status = failure.getStatus(); + if (isTransient(status)) { + return Denial.ASSIGNMENT_UNAVAILABLE; + } + if (status.getCode() == Status.Code.FAILED_PRECONDITION) { + return Denial.STALE_MENU_IDENTITY; + } + return Denial.INVALID_ASSIGNMENT_PROOF; } private static boolean isTransient(Status status) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java index 245fdb3afe..9df3bf5565 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -39,7 +39,7 @@ class GameDesignPublishedRealmPolicyClientTest { private static final String NAMESPACE = "test"; private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); - private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID VERSION_ID = UUID.fromString("55555555-5555-4555-8555-555555555551"); @Test void returnsCompleteTypedEvidenceAndSendsExactRequestWithDeadline() throws Exception { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index 8800a594ff..f54cd05cf1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -498,19 +498,27 @@ void mapsEntityGrpcFailuresByStatusAndReadBoundary() throws Exception { CanonicalGameplayRosterSelectionService.Denial.ASSIGNMENT_UNAVAILABLE); } - var staleRoster = harness(oneActor()); - doThrow(Status.FAILED_PRECONDITION.withDescription("menu changed").asRuntimeException()) - .when(staleRoster.stub()) + var staleRouteOrPolicy = harness(oneActor()); + doThrow( + Status.FAILED_PRECONDITION + .withDescription("route changed or policy is no longer PRESEEDED_ONLY") + .asRuntimeException()) + .when(staleRouteOrPolicy.stub()) .listPreseededRoster(any()); assertDenied( - staleRoster + staleRouteOrPolicy .service() .select( - context(staleRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), - CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + context(staleRouteOrPolicy.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); var changedAssignment = harness(oneActor()); - doThrow(Status.FAILED_PRECONDITION.withDescription("assignment changed").asRuntimeException()) + doThrow( + Status.FAILED_PRECONDITION + .withDescription("snapshot changed or selected actor is absent") + .asRuntimeException()) .when(changedAssignment.stub()) .readSelectedPreseededAssignment(any()); assertDenied( @@ -520,20 +528,7 @@ void mapsEntityGrpcFailuresByStatusAndReadBoundary() throws Exception { context(changedAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), - CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); - - var rejectedRoster = harness(oneActor()); - doThrow(Status.PERMISSION_DENIED.withDescription("caller rejected").asRuntimeException()) - .when(rejectedRoster.stub()) - .listPreseededRoster(any()); - assertDenied( - rejectedRoster - .service() - .select( - context(rejectedRoster.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - null, - null), - CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); for (Status.Code code : List.of(Status.Code.PERMISSION_DENIED, Status.Code.INVALID_ARGUMENT)) { var invalidRoster = harness(oneActor()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java index af71e0cfaf..233be28ee5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java @@ -196,10 +196,16 @@ void abortedCurrentOwnerProofFailsWithoutReadingLaunchAssociation() { var catalogRepository = mock(GameSessionCanonicalRealmCatalogRepository.class); var admissionRepository = mock(CanonicalInitialAdmissionRepository.class); var launchRepository = mock(CanonicalGameInstanceLaunchAssociationRepository.class); + CanonicalInitialAdmissionOwnerProof proof = abortedProof(); + assertThat(proof.provesAbort()).isTrue(); + assertThat(proof.committedPointerVersion()).isNull(); + assertThat(proof.auditEventId()).isNull(); when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) .thenReturn(List.of(catalogSnapshot())); when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) - .thenThrow(new IllegalStateException("Current OPEN pointer has no committed proof")); + .thenAnswer( + invocation -> + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, "d".repeat(64))); var service = routeReadService(catalogRepository, admissionRepository, launchRepository); assertThatThrownBy(service::readVisiblePublicProductionTargets) @@ -377,6 +383,33 @@ private static CanonicalInitialAdmissionOwnerProof committedProof( Instant.parse("2026-10-07T00:00:00Z")); } + private static CanonicalInitialAdmissionOwnerProof abortedProof() { + return new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.ABORTED, + REQUEST_ID, + "a".repeat(64), + NAMESPACE, + TENANT, + "demo-world", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 82L, + 1L, + OriginKind.NO_PRIOR_POINTER, + null, + uuid("77777777-7777-4777-8777-777777777777"), + uuid("88888888-8888-4888-8888-888888888888"), + "sha256:" + "c".repeat(64), + null, + null, + "sha256:" + "f".repeat(64), + true, + Instant.parse("2026-10-07T00:00:00Z")); + } + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentOpenSnapshot( CanonicalInitialAdmissionOwnerProof proof) { return currentOpenSnapshot(proof, "d".repeat(64)); @@ -425,21 +458,27 @@ private static CanonicalInitialAdmissionLaunchTarget launchTarget( } private static IntakeReceipt sourceReceipt(String targetNamespace) { - UUID intakeOperationId = uuid("99999999-9999-4999-8999-999999999999"); + UUID intakeOperationId = uuid("cccccccc-cccc-4ccc-8ccc-cccccccccccc"); UUID intakeRequestId = uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - UUID sourceOperationId = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + UUID sourceRegistrationRequestId = uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + UUID sourceOperationId = uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); String tenantSlug = "demo-tenant"; String worldSlug = "demo-world"; String worldDisplayName = "Demo World"; String sourceTenantKey = "game-design-tenant-42"; String sourceRequestDigest = AuthoredWorldSourceDigest.requestDigest( - targetNamespace, sourceOperationId, TENANT, tenantSlug, worldSlug, worldDisplayName); + targetNamespace, + sourceRegistrationRequestId, + TENANT, + tenantSlug, + worldSlug, + worldDisplayName); String sourceEvidenceDigest = AuthoredWorldSourceDigest.evidenceDigest( targetNamespace, + sourceRegistrationRequestId, sourceOperationId, - intakeOperationId, sourceRequestDigest, TENANT, tenantSlug, @@ -452,8 +491,8 @@ private static IntakeReceipt sourceReceipt(String targetNamespace) { new AuthoredWorldSourceEvidence( 1, targetNamespace, + sourceRegistrationRequestId, sourceOperationId, - intakeOperationId, sourceRequestDigest, TENANT, tenantSlug, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java index 6bc4db9477..eb1954d68b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadServiceTest.java @@ -1,9 +1,11 @@ package unit.net.firedevops.firemud.gamesession.service; +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.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -16,6 +18,7 @@ import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.PreseededActorAssignmentOwnerReadEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; @@ -27,9 +30,10 @@ import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; import org.junit.jupiter.api.Test; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; class CanonicalPublishedPlayerRouteReadServiceTest { - private static final String NAMESPACE = "gameplay"; + private static final String NAMESPACE = "test"; private static final UUID TENANT = uuid("11111111-1111-4111-8111-111111111111"); private static final UUID REALM = uuid("22222222-2222-4222-8222-222222222222"); private static final UUID PLAYABLE_NAMESPACE = uuid("33333333-3333-4333-8333-333333333333"); @@ -39,16 +43,50 @@ class CanonicalPublishedPlayerRouteReadServiceTest { private static final String SOURCE_DIGEST = "sha256:" + "a".repeat(64); @Test - void tenantSelectorOwnerReadRejectsChangedCanonicalSelectorOrCounterBeforeGameDesign() { + void tenantSelectorOwnerReadRejectsEachChangedCanonicalCounterBeforeGameDesign() { var f = fixture(); when(f.routeReader().readCurrentTarget(TENANT)).thenReturn(f.route()); - var request = exactRequest(999L, 0L, 0L); - - assertThatThrownBy(() -> f.service().readCurrent(request)) - .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + for (var deltas : + java.util.List.of( + new long[] {1L, 0L, 0L}, new long[] {0L, 1L, 0L}, new long[] {0L, 0L, 1L})) { + assertThatThrownBy( + () -> f.service().readCurrent(exactRequest(deltas[0], deltas[1], deltas[2]))) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + } verify(f.policyClient(), never()).listPublishedRealmEntryPolicies(TENANT, VERSION); } + @Test + void matchingCurrentRouteReadsAndReturnsCompleteOwnerPolicyEvidence() { + var f = fixture(); + when(f.routeReader().readCurrentTarget(TENANT)).thenReturn(f.route()); + var policies = + PublishedRealmPolicyEvidenceFixture.fixture( + TENANT, + VERSION, + 19L, + 42L, + "game-design-tenant-42", + "NEW_GAME_ROW", + 3, + new PublishedRealmPolicyEvidenceFixture.PolicySpec( + "earth", "Earth", "main", "Main", true, true, "SHARED")); + when(f.release().commitId()).thenReturn(policies.set().sourceCommitId().toString()); + when(f.release().publishWorkflowId()).thenReturn(policies.set().publishWorkflowId()); + when(f.release().manifestHash()).thenReturn(policies.set().manifestHash()); + when(f.release().versionStateEpoch()).thenReturn(policies.set().publicationVersionStateEpoch()); + when(f.descriptor().versionStateEpoch()) + .thenReturn(policies.set().publicationVersionStateEpoch()); + when(f.policyClient().listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenReturn(policies.set()); + + CanonicalGameplayRosterOwnerReadEvidence result = + f.service().readCurrent(exactRequest(0L, 0L, 0L)); + + assertThat(result.publishedPolicySetEvidence()).isEqualTo(policies.set()); + verify(f.policyClient(), times(2)).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + @Test void tenantSelectorOwnerReadRejectsChangedTargetNamespaceBeforeOwnerRead() { var f = fixture(); @@ -224,6 +262,28 @@ private static Fixture fixture() { when(route.gameInstanceId()).thenReturn(202L); when(route.runtimeVersionId()).thenReturn(303L); when(route.canonicalVersionId()).thenReturn(VERSION); + when(route.catalogRevision()).thenReturn(1L); + when(route.pointerVersion()).thenReturn(1L); + when(route.admissionPointerSnapshotDigest()).thenReturn("d".repeat(64)); + when(route.activeWorldEpoch()).thenReturn(1L); + when(route.initialAdmissionRequestId()).thenReturn("first-open-operation-17"); + when(route.initialAdmissionRequestDigest()).thenReturn("a".repeat(64)); + when(route.initialAdmissionOriginKind()) + .thenReturn( + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind + .NO_PRIOR_POINTER); + when(route.expectedPriorPointerVersion()).thenReturn(null); + when(route.holdId()).thenReturn(uuid("99999999-9999-4999-8999-999999999999")); + when(route.holdFence()).thenReturn(uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + when(route.holdBindingDigest()).thenReturn(currentHoldRequest().holdBindingDigest()); + when(route.auditEventId()).thenReturn(27L); + when(route.ownerProofDigest()).thenReturn("sha256:" + "f".repeat(64)); + when(route.ownerProofOutcome()) + .thenReturn( + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome + .COMMITTED); + when(route.positiveDurableAbort()).thenReturn(false); + when(route.ownerProofTerminalAt()).thenReturn(java.time.Instant.parse("2026-10-07T00:00:00Z")); when(catalog.targetNamespace()).thenReturn(NAMESPACE); when(catalog.tenantId()).thenReturn(TENANT); @@ -250,6 +310,9 @@ private static Fixture fixture() { when(launch.runtimeVersionId()).thenReturn(303L); when(launch.canonicalVersionId()).thenReturn(VERSION); when(association.targetNamespace()).thenReturn(NAMESPACE); + when(association.gameSessionTenantId()).thenReturn(101L); + when(association.tenantAssociationOperationId()) + .thenReturn(uuid("aeaeaeae-aeae-4eae-8eae-aeaeaeaeaeae")); when(association.canonicalTenantId()).thenReturn(TENANT); when(association.gameInstanceUuid()).thenReturn(INSTANCE); when(association.worldSlug()).thenReturn("earth"); @@ -260,6 +323,8 @@ private static Fixture fixture() { .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); when(association.controlPlaneRequestId()).thenReturn("launch-request"); when(association.launchDescriptorId()).thenReturn("launch-descriptor"); + when(association.capturedStartingRowVersion()).thenReturn(1L); + when(association.currentRowVersion()).thenReturn(2L); when(association.launchBindingEvidence()).thenReturn(completeBinding); when(completeBinding.descriptor()).thenReturn(descriptor); when(completeBinding.releaseAttestation()).thenReturn(release); @@ -279,6 +344,9 @@ private static Fixture fixture() { when(release.worldSlug()).thenReturn("earth"); when(release.authoredWorldSourceOperationId()).thenReturn(SOURCE_OPERATION); when(release.authoredWorldSourceEvidenceDigest()).thenReturn(SOURCE_DIGEST); + when(release.commitId()).thenReturn("commit-id"); + when(release.publishWorkflowId()).thenReturn("publish-workflow"); + when(release.manifestHash()).thenReturn("sha256:" + "b".repeat(64)); when(release.versionStateEpoch()).thenReturn(7L); when(release.publishedReleaseBundleRef()).thenReturn("bundle:exact"); @@ -298,6 +366,7 @@ private static Fixture fixture() { route, source, launch, + descriptor, release, service); } @@ -321,6 +390,24 @@ private static CanonicalGameplayRosterOwnerReadEvidence.Request exactRequest( 1L + epochDelta); } + private static WorldCanonicalInitialAdmissionHold.Request currentHoldRequest() { + return new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + TENANT, + "earth", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + INSTANCE, + VERSION, + 1L, + "first-open-operation-17", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + 1L, + null); + } + private static PreseededActorAssignmentOwnerReadEvidence.Request assignmentRequest( UUID realmUuid) { return new PreseededActorAssignmentOwnerReadEvidence.Request( @@ -352,6 +439,7 @@ private record Fixture( CanonicalPlayableTarget route, AuthoredWorldSourceEvidence source, CanonicalInitialAdmissionLaunchTarget launch, + AuthoredWorldLaunchDescriptorEvidence descriptor, AuthoredWorldReleaseAttestationEvidence release, CanonicalPublishedPlayerRouteReadService service) {} } diff --git a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java index db4924d314..0e887b49f4 100644 --- a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java +++ b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java @@ -74,7 +74,7 @@ private PublishedRealmPolicyEvidenceFixture() {} public static Fixture fixture(PolicySpec... requestedPolicies) { return fixture( uuid("11111111-1111-4111-8111-111111111111"), - uuid("22222222-2222-4222-8222-222222222222"), + uuid("55555555-5555-4555-8555-555555555551"), 19L, 42L, "tenant-key", From 56ed78456be3ac27de3d7d3a384a32c633c1f578 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:43:27 +1300 Subject: [PATCH 29/34] Share canonical roster target validation and clarify source contracts --- .../api-contracts.md | 2 +- .../system-architecture-transactions.md | 2 +- ...ame-authoring-publishing-and-activation.md | 2 +- .../client/CanonicalGameplayRosterClient.java | 8 ++- .../text/CanonicalGameplayActorSelection.java | 54 ++----------------- 5 files changed, 13 insertions(+), 55 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 7f7b6072c0..534c7bd943 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -8,7 +8,7 @@ The authoritative REST schema source lives in [../../../../services/entity-manag The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -The `ReadSelectedPreseededAssignment` `intent_digest` is the lowercase hexadecimal SHA-256 of Entity's immutable assignment-intent preimage. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. UUIDs use canonical `UUID.toString()` form, counters use base-10 decimal text, and scope/policy values use their canonical enum names. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest is the original persisted operation-intent digest, not a digest of current owner evidence or current Account state. +The `ReadSelectedPreseededAssignment` `intent_digest` is the lowercase hexadecimal SHA-256 of Entity's immutable assignment-intent preimage. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUIDs use canonical `UUID.toString()` form, counters use base-10 decimal text, and scope/policy values use their canonical enum names. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest is the original persisted operation-intent digest, not a digest of current owner evidence or current Account state. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index f5425ead9e..ed39acbaca 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -250,7 +250,7 @@ These workflows: - Modify **persistent storage (PostgreSQL)** across multiple services - Require compensation and persisted step status, but not durable workflow execution -For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses its later-owned policy-aware Entity roster contract against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. The separate `CanonicalGameplayRosterService.ListPreseededRoster` wire implements only the pre-admission `PRESEEDED_ONLY` lookup; `PLAYER_CREATED` remains a later-owned target branch, and neither it nor `AUTO_PROVISIONED` may fall back to the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. +For `explicitRealmEntry`, the accepted policy outcomes are exactly `PLAYER_CREATED`, `AUTO_PROVISIONED`, and `PRESEEDED_ONLY`; the immutable discovered-entry request may carry an optional `selectedCharacterId`, and its digest covers that selection without duplicating policy semantics. For any branch that reads a roster, the durable saga step binds the selected policy branch, Entity-returned roster snapshot identity/digest, and resolved selected character when one exists; retries reuse those applicable values rather than silently following a changed roster. The saga branches on that unchanged bound outcome: `PLAYER_CREATED` first uses its later-owned policy-aware Entity roster contract against the unchanged bound target, then evaluates any supplied creation input against that roster. An exactly-one roster auto-selects its actor; if the request supplies `selectedCharacterId`, it must equal that one actor. A multiple-actor roster requires an explicit `selectedCharacterId` that belongs to the unchanged roster/snapshot; missing or invalid selection fails before binding. Any supplied creation input is valid only for a zero-roster `PLAYER_CREATED` branch; after the roster lookup, a nonempty `PLAYER_CREATED` roster rejects its presence before selection, binding, or mutation, while `AUTO_PROVISIONED` and `PRESEEDED_ONLY` reject it before their branch-specific lookup or mutation. A zero roster with no creation input offers/requires creation without mutation, and zero-roster creation never accepts a caller-selected character ID. A submitted creation input with absent required fields, malformed data, or failure to validate against the exact realm-published descriptor and version bound in the discovered-entry object fails closed; and only valid submitted input calls `CreateCharacter` with the unchanged discovered-entry object/digest plus that input. The preliminary roster read is discovery and selection evidence, not concurrency authority; the Entity-owned `CreateCharacter` contract serializes and rereads the zero-roster boundary before allocation. If a durable saga step has already entered `CreateCharacter`, a retry calls Entity with the stored request identity, digest, and canonical input before any fresh roster rejection so a committed operation with a lost response replays its original result. Each mutating branch carries a caller-stable operation request identity derived from its durable forward saga-step identity (`createCharacterRequestId` for `PLAYER_CREATED`, `autoProvisionRequestId` for `AUTO_PROVISIONED`) and a `mutationDigest` over the trusted target, exact descriptor or template identity/version, and canonical `creationInput`; the auto-provision branch uses the explicit absent-input marker defined by [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md). Entity recomputes and binds the digest and operation identity, while `discoveredEntryDigest` remains admission/discovery evidence rather than actor-write identity. A retry reuses the same operation identity, digest, and canonical input and replays the original result; changed target, descriptor/template/version, or input fails closed as an idempotency conflict. The separate `CanonicalGameplayRosterService.ListPreseededRoster` wire specifies only the pre-admission `PRESEEDED_ONLY` lookup; `PLAYER_CREATED` remains a later-owned target branch, and neither it nor `AUTO_PROVISIONED` may fall back to the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. `AUTO_PROVISIONED` requires `selectedCharacterId` to be absent; any supplied selection fails closed before the provisioning call. It calls `AutoProvisionCharacter` with the same immutable discovered-entry inputs plus its stable `autoProvisionRequestId`, `mutationDigest`, and canonical absent-input marker after explicit entry, allowing its owner-defined idempotent existing-actor result. `PRESEEDED_ONLY` calls `CanonicalGameplayRosterService.ListPreseededRoster` as a lookup: zero actors returns the pre-seeded-only denial, while a nonzero roster applies the same exact-one-versus-many selection rule without actor mutation. Its durable selection step binds the returned roster snapshot identity/digest and selected character; `ReadSelectedPreseededAssignment` requires that exact snapshot and selection and fails closed if the roster changed rather than silently selecting another actor. The response echoes request/account/selected-character/target/snapshot bindings and returns Entity's original assignment operation UUID and immutable intent digest from the unique matching committed receipt. The saga binds and retries with that unchanged reference so the later placement owner can revalidate the original assignment; the reference is neither minted by this read nor evidence of admission or current Account eligibility. The separate wire accepts only `PRESEEDED_ONLY`; other policy values fail with `FAILED_PRECONDITION`. `PLAYER_CREATED` remains a later-owned policy-aware roster branch, and `AUTO_PROVISIONED` remains its owner-defined idempotent existing-actor operation; neither branch may use the legacy numeric `ListCharactersByAccount` RPC as canonical gameplay authority. No branch re-resolves policy or substitutes a different descriptor/template, namespace, scope, roster, or digest. Catalog and admission-pointer identity/semantics remain in [Multi-Tenancy](./system-architecture-multi-tenancy.md), while Game Session owns realm/pointer resolution, selection, and serving orchestration and Entity Management owns descriptor/template consumption and actor allocation/persistence. [ADR 0140](./decisions/adr-0140-realm-authored-controllable-actor-entry.md) remains decision rationale for this boundary; its canonical presence encoding is retained by the auto-provision request above. The Entity API contract names these target surfaces, but the current proto, implementation, and focused proof do not establish this saga. 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 6a4bc35f79..d3cfd76254 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 @@ -89,7 +89,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.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); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.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); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java); [CanonicalLaunchGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. Production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads; the RPC is registered in the gRPC public-method list to bypass bearer validation, while its mTLS peer checks remain active. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java index cd254a01da..d6ca7f8f42 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -111,7 +111,7 @@ protected CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlock public PreseededRosterSnapshot listPreseededRoster( CanonicalPublishedPlayerRoute publishedRoute, PlayerExecutionContext playerExecutionContext) { Objects.requireNonNull(publishedRoute, "publishedRoute"); - CanonicalGameplayRosterTarget expectedTarget = toExpectedTarget(publishedRoute); + CanonicalGameplayRosterTarget expectedTarget = expectedTarget(publishedRoute); UUID canonicalAccountUuid = validatePlayerExecutionContext(playerExecutionContext, expectedTarget, false); UUID requestUuid = parseContextUuid(playerExecutionContext.getRequestId(), "request_id"); @@ -423,7 +423,11 @@ private static PreseededRosterSnapshot validateResponse( expectedAccountUuid, snapshotUuid, snapshotDigest, expectedTarget, actors); } - private static CanonicalGameplayRosterTarget toExpectedTarget( + /** + * Builds the exact Entity source target for a validated current SHARED PRESEEDED_ONLY route. + * Policy and digest evidence are validated before the target is returned. + */ + public static CanonicalGameplayRosterTarget expectedTarget( CanonicalPublishedPlayerRoute publishedRoute) { CanonicalPlayableTarget route = publishedRoute.route(); RealmEntryPolicy policy = publishedRoute.entryPolicy(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java index f45067d224..dbad545e5a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java @@ -7,10 +7,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; -import net.firedevops.firemud.common.publication.RealmEntryPolicy; -import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; @@ -38,7 +35,10 @@ public static Optional validate( || !isNonNil(snapshot.snapshotUuid()) || !isCanonicalDigest(snapshot.snapshotDigest()) || expectedRoute == null - || !matchesExactPublishedTarget(snapshot.target(), expectedRoute)) { + || snapshot.target() == null + || !snapshot.target().getUnknownFields().asMap().isEmpty() + || !CanonicalGameplayRosterClient.expectedTarget(expectedRoute) + .equals(snapshot.target())) { return Optional.empty(); } List actors = snapshot.actors(); @@ -109,52 +109,6 @@ private static Selected selected( ordinal); } - private static boolean matchesExactPublishedTarget( - CanonicalGameplayRosterTarget target, CanonicalPublishedPlayerRoute publishedRoute) { - if (target == null || !target.getUnknownFields().asMap().isEmpty()) { - return false; - } - var route = publishedRoute.route(); - RealmEntryPolicy policy = publishedRoute.entryPolicy(); - if (policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PRESEEDED_ONLY - || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED - || !"SHARED".equals(route.playableStateScope())) { - return false; - } - publishedRoute.policySetEvidence().requireValidDigest(); - publishedRoute.selectedPolicyEvidence().requireValidDigest(publishedRoute.policySetEvidence()); - return target.getTenantUuid().equals(route.canonicalTenantId().toString()) - && target.getRealmUuid().equals(route.realmId().toString()) - && target.getWorldSlug().equals(route.worldSlug()) - && target.getRealmSlug().equals(route.realmSlug()) - && target.getGameInstanceUuid().equals(route.canonicalGameInstanceId().toString()) - && target.getCatalogRevision() == route.catalogRevision() - && target - .getPublishedPolicyDigest() - .equals(rawDigest(publishedRoute.selectedPolicyEvidence().policyDigest())) - && target - .getPublishedReleaseBundleRef() - .equals(publishedRoute.policySetEvidence().publishedReleaseBundleRef()) - && target.getAdmissionPointerSnapshotDigest().equals(route.admissionPointerSnapshotDigest()) - && target.getPublishedOwnerProofDigest().equals(rawDigest(route.ownerProofDigest())) - && target - .getPlayableStateNamespaceUuid() - .equals(route.playableStateNamespaceId().toString()) - && target.getPlayableStateScope() == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED - && target.getEntryPolicy() - == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY - && target.getCanonicalVersionUuid().equals(route.canonicalVersionId().toString()) - && target.getPointerVersion() == route.pointerVersion() - && target.getActiveWorldEpoch() == route.activeWorldEpoch(); - } - - private static String rawDigest(String prefixedDigest) { - if (prefixedDigest == null || !prefixedDigest.matches("sha256:[0-9a-f]{64}")) { - throw new IllegalArgumentException("Published route digest is malformed"); - } - return prefixedDigest.substring("sha256:".length()); - } - private static boolean isCanonicalDisplayName(String value) { return value != null && !value.isBlank() From ff8b9024b0dc4cf76fe8073520851f8985385619 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:14:33 +1300 Subject: [PATCH 30/34] Unify typed roster validation and prove tenant mismatch denial --- .../api-contracts.md | 2 +- .../game-design-service/README.md | 2 +- .../client/CanonicalGameplayRosterClient.java | 73 ++++++++++--------- .../text/CanonicalGameplayActorSelection.java | 24 +----- ...calGameplayRosterSelectionServiceTest.java | 17 +++++ 5 files changed, 59 insertions(+), 59 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 534c7bd943..1d5b64b660 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -8,7 +8,7 @@ The authoritative REST schema source lives in [../../../../services/entity-manag The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -The `ReadSelectedPreseededAssignment` `intent_digest` is the lowercase hexadecimal SHA-256 of Entity's immutable assignment-intent preimage. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUIDs use canonical `UUID.toString()` form, counters use base-10 decimal text, and scope/policy values use their canonical enum names. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest is the original persisted operation-intent digest, not a digest of current owner evidence or current Account state. +The `ReadSelectedPreseededAssignment` `intent_digest` is the lowercase hexadecimal SHA-256 of Entity's immutable assignment-intent preimage. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUIDs use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest is the original persisted operation-intent digest, not a digest of current owner evidence or current Account state. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. diff --git a/design/architecture/microservices/game-design-service/README.md b/design/architecture/microservices/game-design-service/README.md index 2b3ac67581..ca02a38ca7 100644 --- a/design/architecture/microservices/game-design-service/README.md +++ b/design/architecture/microservices/game-design-service/README.md @@ -18,7 +18,7 @@ Current capability and proof gaps remain: Game Session's exact pin/epoch persist ### Authored-World Launch Boundary -The canonical authored-world launch slice includes source-qualified ResolveLaunchDescriptor, exact independent GetLaunchDescriptor, and GetCompleteLaunchBinding returning descriptor and release-attestation evidence separately. Game Session's evidence-only preparation and focused proof sources are present; capability and proof gaps are recorded in the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#launch-activation-cutover-and-termination). Numeric launch selectors are non-authorizing. +The canonical authored-world launch slice includes source-qualified ResolveLaunchDescriptor and exact independent GetLaunchDescriptor. Target `GetCompleteLaunchBinding` returns the exact descriptor and release-attestation evidence separately; current production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads. Game Session's evidence-only preparation and focused proof sources are present; capability and proof gaps are recorded in the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#launch-activation-cutover-and-termination). Numeric launch selectors are non-authorizing. ## Responsibilities diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java index d6ca7f8f42..c6da9e621d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClient.java @@ -56,7 +56,7 @@ public final class CanonicalGameplayRosterClient CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; // Matches Entity's bounded CanonicalGameplayRosterSnapshotDigest contract. - private static final int MAX_ROSTER_SIZE = 100; + public static final int MAX_ROSTER_SIZE = 100; private static final UUID NIL_UUID = new UUID(0L, 0L); private static final String SNAPSHOT_DIGEST_DOMAIN = "firemud.entity.canonical-gameplay-roster.v3"; @@ -277,28 +277,7 @@ private static void requireValidSelectedRosterSnapshot(PreseededRosterSnapshot r throw new IllegalArgumentException( "Selected assignment reads require an exact SHARED PRESEEDED_ONLY roster target"); } - if (roster.actors().size() > MAX_ROSTER_SIZE) { - throw new IllegalArgumentException("Validated Entity roster exceeds its maximum size"); - } - Set characterUuids = new HashSet<>(); - for (RosterActor actor : roster.actors()) { - if (actor == null) { - throw new IllegalArgumentException("Validated Entity roster contains an absent actor"); - } - UUID characterUuid = actor.characterUuid(); - requireNonNil(characterUuid, "roster character UUID"); - if (!characterUuids.add(characterUuid)) { - throw new IllegalArgumentException("Validated Entity roster contains a duplicate actor"); - } - String displayName = actor.displayName(); - if (displayName == null - || displayName.isBlank() - || !displayName.equals(displayName.trim()) - || displayName.length() > 100 - || displayName.codePoints().anyMatch(Character::isISOControl)) { - throw new IllegalArgumentException("Validated Entity roster contains a malformed actor"); - } - } + requireValidActors(roster.actors()); if (!roster .snapshotDigest() .equals(calculateSnapshotDigest(roster.canonicalAccountUuid(), target, roster.actors()))) { @@ -391,30 +370,24 @@ private static PreseededRosterSnapshot validateResponse( throw invalidResponse("actor roster exceeds its maximum size"); } - Set characterUuids = new HashSet<>(); List actors = new ArrayList<>(response.getActorsCount()); for (CanonicalGameplayRosterActor actor : response.getActorsList()) { if (!actor.getUnknownFields().asMap().isEmpty()) { throw invalidResponse("actor contains unknown fields"); } UUID characterUuid = parseCanonicalUuid(actor.getCharacterUuid(), "character_uuid"); - if (!characterUuids.add(characterUuid)) { - throw invalidResponse("actor roster contains a duplicate character UUID"); - } if (actor.getActorKind() != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) { throw invalidResponse("actor roster contains an unsupported actor kind"); } String displayName = actor.getDisplayName(); - if (displayName == null - || displayName.isBlank() - || !displayName.equals(displayName.trim()) - || displayName.length() > 100 - || displayName.codePoints().anyMatch(Character::isISOControl)) { - throw invalidResponse("actor display name is malformed"); - } actors.add(new RosterActor(characterUuid, displayName)); } + try { + requireValidActors(actors); + } catch (IllegalArgumentException malformedActors) { + throw invalidResponse(malformedActors.getMessage()); + } if (!snapshotDigest.equals( calculateSnapshotDigest(expectedAccountUuid, expectedTarget, actors))) { throw invalidResponse("snapshot_digest does not bind the returned target and roster"); @@ -462,6 +435,38 @@ public static CanonicalGameplayRosterTarget expectedTarget( .build(); } + /** Requires a typed Entity roster to satisfy the shared actor-list contract. */ + public static void requireValidActors(List actors) { + if (actors == null) { + throw new IllegalArgumentException("Validated Entity roster is absent"); + } + if (actors.size() > MAX_ROSTER_SIZE) { + throw new IllegalArgumentException("Validated Entity roster exceeds its maximum size"); + } + Set characterUuids = new HashSet<>(); + for (RosterActor actor : actors) { + if (actor == null) { + throw new IllegalArgumentException("Validated Entity roster contains an absent actor"); + } + UUID characterUuid = actor.characterUuid(); + requireNonNil(characterUuid, "roster character UUID"); + if (!characterUuids.add(characterUuid)) { + throw new IllegalArgumentException("duplicate actor: duplicate character UUID"); + } + if (!isCanonicalDisplayName(actor.displayName())) { + throw new IllegalArgumentException("display name is malformed"); + } + } + } + + private static boolean isCanonicalDisplayName(String value) { + return value != null + && !value.isBlank() + && value.equals(value.trim()) + && value.length() <= 100 + && value.codePoints().noneMatch(Character::isISOControl); + } + private static String rawOwnerProofDigest(String prefixedDigest) { if (prefixedDigest == null || !prefixedDigest.matches("sha256:[0-9a-f]{64}")) { throw new IllegalArgumentException("Canonical route owner-proof digest is malformed"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java index dbad545e5a..a62581684b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java @@ -1,11 +1,9 @@ package net.firedevops.firemud.gamesession.command.text; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -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.entitymanagement.v1.CanonicalGameplayRosterTarget; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; @@ -16,7 +14,6 @@ */ public final class CanonicalGameplayActorSelection { private static final UUID NIL_UUID = new UUID(0L, 0L); - private static final int MAX_ROSTER_SIZE = 100; private CanonicalGameplayActorSelection() {} @@ -42,18 +39,7 @@ public static Optional validate( return Optional.empty(); } List actors = snapshot.actors(); - if (actors == null || actors.size() > MAX_ROSTER_SIZE) { - return Optional.empty(); - } - Set actorIds = new HashSet<>(); - for (CanonicalGameplayRosterClient.RosterActor actor : actors) { - if (actor == null - || !isNonNil(actor.characterUuid()) - || !actorIds.add(actor.characterUuid()) - || !isCanonicalDisplayName(actor.displayName())) { - return Optional.empty(); - } - } + CanonicalGameplayRosterClient.requireValidActors(actors); return Optional.of(new ValidatedRoster(snapshot, expectedAccountUuid, expectedRoute)); } catch (RuntimeException malformed) { return Optional.empty(); @@ -109,14 +95,6 @@ private static Selected selected( ordinal); } - private static boolean isCanonicalDisplayName(String value) { - return value != null - && !value.isBlank() - && value.equals(value.trim()) - && value.length() <= 100 - && value.codePoints().noneMatch(Character::isISOControl); - } - private static boolean isCanonicalDigest(String value) { return value != null && value.matches("[0-9a-f]{64}"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index f54cd05cf1..499c791fe8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -152,6 +152,23 @@ void returnsMenuForMultipleActorsThenReadsOnlyTheSelectedOrdinalOwnerReference() void deniesTenantNamespaceRealmAndInstanceContextMismatchesBeforeEntityRead() throws Exception { var harness = harness(oneActor()); PlayerExecutionContext valid = context(harness.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"); + UUID foreignTenant = uuid("13131313-1313-4313-8313-131313131313"); + var mainTenantCatalog = + harness + .catalogRepository() + .readUniqueVisiblePublicProduction( + harness.route().targetNamespace(), harness.route().canonicalTenantId()); + // Deliberately return the valid main-tenant owner row for a foreign-tenant query. + when(harness + .catalogRepository() + .readUniqueVisiblePublicProduction(harness.route().targetNamespace(), foreignTenant)) + .thenReturn(mainTenantCatalog); + + assertDenied( + harness + .service() + .select(valid.toBuilder().setTenantId(foreignTenant.toString()).build(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); assertDenied( harness From 55c6ecb533a66ec520db258820cb1a5fe3ef9e27 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:28:28 +1300 Subject: [PATCH 31/34] Bind World stub tests directly to ephemeral ports --- .../test/stubs/WorldManagementStubServerTest.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java index b14fe5c6d6..be0d8f8d68 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java @@ -12,14 +12,13 @@ import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotResponse; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.junit.jupiter.api.Test; -import org.springframework.test.util.TestSocketUtils; class WorldManagementStubServerTest { @Test void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { + int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); try { @@ -60,8 +59,8 @@ void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { @Test void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { + int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); try { @@ -92,8 +91,8 @@ void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { @Test void unknownRoomInstanceIdReturnsNotFound() throws Exception { - int port = TestSocketUtils.findAvailableTcpPort(); - try (WorldManagementStubServer server = new WorldManagementStubServer(port)) { + try (WorldManagementStubServer server = new WorldManagementStubServer(0)) { + int port = server.port(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", port).usePlaintext().build(); try { From 3451072b4246386f592f22693bb93eb5a954075f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:40:09 +1300 Subject: [PATCH 32/34] Clarify launch method authentication and explicit owner-read test stubbing --- .../microservices/game-design-service/api-contracts.md | 2 +- .../game-authoring-publishing-and-activation.md | 2 +- .../CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java | 8 +++++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/design/architecture/microservices/game-design-service/api-contracts.md b/design/architecture/microservices/game-design-service/api-contracts.md index 35906be9c3..7e66da5da1 100644 --- a/design/architecture/microservices/game-design-service/api-contracts.md +++ b/design/architecture/microservices/game-design-service/api-contracts.md @@ -12,7 +12,7 @@ Launch resolution is authorized by an exact canonical authored-world source, not GetLaunchDescriptor is a separate exact read using a fresh non-nil read-request UUID, canonical tenant UUID, world slug, control-plane request ID, and expected request/result digests. A caller compares this committed readback with the original resolve response; a successful resolve response alone is not committed-evidence proof. GetCompleteLaunchBinding reads the same exact descriptor together with its matching immutable full-version release attestation, including participant digests and manifest/artifact evidence. Descriptor evidence and release attestation remain separate digested objects and must not be substituted for one another. These reads are read-only and do not authorize Game Session instance creation, World activation, admission, or PLAY. -The target caller matrix is: launch resolution accepts only the exact same-namespace Game Session workload identity; descriptor readback accepts same-namespace Game Session or World Management; complete-binding readback accepts same-namespace Game Session, World Management, or Entity Management. Target behavior rejects absent/malformed peer identity, noncanonical or nil UUIDs, and unknown request fields before owner reads. Legacy numeric Game Session launch selectors fail closed and are not translated into this contract. +The target caller matrix is: launch resolution accepts only the exact same-namespace Game Session workload identity; descriptor readback accepts same-namespace Game Session or World Management; complete-binding readback accepts same-namespace Game Session, World Management, or Entity Management. Target behavior rejects absent/malformed peer identity, noncanonical or nil UUIDs, and unknown request fields before owner reads. Legacy numeric Game Session launch selectors fail closed and are not translated into this contract. The base and production gRPC public-method lists include `ResolveLaunchDescriptor`, `GetLaunchDescriptor`, and `GetCompleteLaunchBinding` to bypass bearer validation; each method retains its method-specific same-namespace mTLS peer check. Current limitation: `GetCompleteLaunchBinding` authenticates those exact same-namespace candidate peers and then returns `PERMISSION_DENIED` before request validation or owner reads. No production owner-read permission or activation authority is enabled; see the [implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#launch-activation-cutover-and-termination). 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 d3cfd76254..0f619ebb15 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 @@ -89,7 +89,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.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); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java); [CanonicalLaunchGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. Production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads; the RPC is registered in the gRPC public-method list to bypass bearer validation, while its mTLS peer checks remain active. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `unverified`: Game Session lifecycle and World activation, failure, and termination seams remain proven. Legacy numeric-only tenant/template/version resolution remains fail-closed and does not authorize launch; authenticated source-bound v1 descriptor resolution and exact readback are implemented, while candidate-specific source/receipt proof and current PostgreSQL, packaged Compose/restart, and later protected-activation proof remain unproved. Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.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); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql); [V34.1 authored source operations](../../../services/game-design-service/src/main/resources/db/migration/V34.1__authored_world_source_operations.sql); [V35 descriptor source binding](../../../services/game-design-service/src/main/resources/db/migration/V35__authored_source_launch_descriptor_binding.sql); [V41 source delivery](../../../services/game-design-service/src/main/resources/db/migration/V41__world_authored_source_delivery.sql); [GameAuthoredWorldSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepository.java); [GameAuthoredWorldSourceDeliveryRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java); [CompleteLaunchBindingService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingService.java); [CompleteLaunchBindingServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java); [CompleteLaunchBindingDto.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/dto/CompleteLaunchBindingDto.java) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [GameAuthoredWorldSourceRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java); [GameAuthoredWorldSourceDeliveryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java); [CompleteLaunchBindingServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java); [CompleteLaunchBindingServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java); [CanonicalLaunchGrpcAuthWiringTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/CanonicalLaunchGrpcAuthWiringTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: authenticated source-bound v1 resolution and exact descriptor readback are live; numeric-only tenant/template/version fields do not authorize launch. Candidate-specific source/receipt proof and physical Compose/Docker/PostgreSQL/mTLS smoke remain unvalidated. Automation `READY`, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover and owner cleanup acknowledgement remain unproved. `ResolveLaunchDescriptor`, `GetLaunchDescriptor`, and `GetCompleteLaunchBinding` are registered in the base and production gRPC public-method lists to bypass bearer validation, and each retains its method-specific same-namespace mTLS peer check. Production `GetCompleteLaunchBinding` authenticates exact same-namespace candidate peers, then returns `PERMISSION_DENIED` before request validation or owner reads. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java index 5eb294e5bc..d43281401e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterOwnerReadGrpcAdapterTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -205,10 +206,11 @@ void staleOrInvalidCurrentSelectorsFailClosed() { () -> adapter.getCanonicalGameplayRosterOwnerRead(request(), staleObserver)); assertStatus(staleObserver, Status.Code.FAILED_PRECONDITION); - when(source.readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class))) - .thenThrow( + doThrow( new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( - "changed policy or source")); + "changed policy or source")) + .when(source) + .readCurrent(any(CanonicalGameplayRosterOwnerReadEvidence.Request.class)); var invalidObserver = responseObserver(); runAsPeer( ENTITY_SERVICE, From 7d8effc4e44c0958dd74a2e515c7ef994ec502ff Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:59:57 +1300 Subject: [PATCH 33/34] Map assignment precondition denials by selection context and clarify digest sources --- .../api-contracts.md | 2 +- ...nonicalGameplayRosterSelectionService.java | 7 ++--- ...calGameplayRosterSelectionServiceTest.java | 27 +++++++++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 1d5b64b660..bf12d23d73 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -8,7 +8,7 @@ The authoritative REST schema source lives in [../../../../services/entity-manag The separate `CanonicalGameplayRosterService` proto is a wire contract only; it has no handler or activation in the current stage. Its two methods define pre-admission, non-admitting reads restricted to `PRESEEDED_ONLY`; any other policy value is non-authorizing and returns `FAILED_PRECONDITION`. `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. -The `ReadSelectedPreseededAssignment` `intent_digest` is the lowercase hexadecimal SHA-256 of Entity's immutable assignment-intent preimage. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUIDs use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest is the original persisted operation-intent digest, not a digest of current owner evidence or current Account state. +The `ReadSelectedPreseededAssignment` `intent_digest` is the bare lowercase 64-hex SHA-256 of Entity's immutable assignment-intent preimage, with no `sha256:` prefix. Entity serializes these UTF-8 string values in this exact order: domain `firemud.entity.preseeded-actor-assignment.v4`; original `assignmentUuid`; `canonicalAccountUuid`; core `actorKind`; core `displayName`; target `canonicalTenantUuid`; `realmUuid`; `worldSlug`; `realmSlug`; `gameInstanceId`; base-10 `catalogRevision`; `canonicalVersionUuid`; `frozenPolicyDigest`; `playableStateNamespaceId`; `publishedReleaseBundleRef`; `playableStateScope`; and `entryPolicy`. The operation and account values come from `PreseededActorAssignmentRequest.assignmentUuid` and `.canonicalAccountUuid`, corresponding to `assignment_uuid` in the selected-assignment response and `canonical_account_uuid` on its request and response. `actorKind` and `displayName` come from the original `request.corePayload`, not the currently selected roster actor's `actor_kind` or `display_name`. Target values come from the independently resolved `PreseededActorAssignmentOwnerEvidence` used to create the persisted assignment receipt; their corresponding `CanonicalGameplayRosterTarget` wire fields are `tenant_uuid`, `realm_uuid`, `world_slug`, `realm_slug`, `game_instance_uuid`, `catalog_revision`, `canonical_version_uuid`, `published_policy_digest`, `playable_state_namespace_uuid`, `published_release_bundle_ref`, `playable_state_scope`, and `entry_policy`. In particular, internal `gameInstanceId` is a bounded opaque string; the `game_instance_uuid` wire field name does not add UUID parsing or normalization to its digest value. The internal `frozenPolicyDigest` is the same persisted value represented by `CanonicalGameplayRosterTarget.published_policy_digest`; it is bare lowercase 64-hex without a `sha256:` prefix and is not separately derived. For this assignment, the enum values are the internal short strings `PLAYER`, `SHARED` or `ISOLATED`, and `PRESEEDED_ONLY`, respectively, not full protobuf enum identifiers. UUID values use canonical `UUID.toString()` form, counters use base-10 decimal text, and `actorKind`, `playableStateScope`, and `entryPolicy` use only the short strings listed above. Each value is encoded as UTF-8 and prefixed by its byte length as a four-byte big-endian integer; SHA-256 covers the concatenated length-prefixed values. The digest returned by the selected-assignment read is the original persisted receipt digest, not recomputed from that read's request, the current roster, or current owner/Account observations. See the [Entity proto](../../../../protos/entity-management/v1/entity_management_service.proto) for the wire field names. The live crafting REST surface is runtime-reachable but is not a tenant-authorized gameplay or design-time boundary: `POST /crafting/recipes` accepts a caller-supplied `tenantId` in `CraftingRecipeDto`, and `GET /crafting/recipes/{id}` accepts only a globally-shaped recipe id. The ping-only authoritative OpenAPI document declares root `security: []`; the crafting handlers and schemas are omitted from that contract. The deployed Entity HTTP interceptor currently requires only an `AUTHENTICATED` bearer (crafting is not in the public-route list), while the controllers do not apply `SessionContext` tenant authorization and the service/repository do not bind either operation to the authenticated caller. The create path can therefore persist a caller-selected tenant (and an existing DTO id can update by id), while the read path performs an ID-only recipe lookup. `CraftingControllerTest` and `CraftingServiceImplTest` cover request/recipe validation and happy-path persistence only; they do not prove unauthenticated denial, tenant-qualified lookup/update, or cross-tenant item ownership. The handlers must remain unsupported/fenced or gain the target caller-bound authorization before they can be treated as a supported route. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java index fec66c6ef4..d5ca70d8d8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java @@ -121,7 +121,7 @@ public Result select( try { ownerReference = rosterClient.readSelectedPreseededAssignment(snapshot, selectedContext); } catch (StatusRuntimeException failure) { - return new Denied(assignmentFailure(failure)); + return new Denied(assignmentFailure(failure, expectedMenuIdentity != null)); } catch (RuntimeException invalidOrUnavailable) { return new Denied(Denial.INVALID_ASSIGNMENT_PROOF); } @@ -174,13 +174,14 @@ private static Denial rosterFailure(StatusRuntimeException failure) { return Denial.INVALID_ROSTER_PROOF; } - private static Denial assignmentFailure(StatusRuntimeException failure) { + private static Denial assignmentFailure( + StatusRuntimeException failure, boolean menuIdentitySupplied) { Status status = failure.getStatus(); if (isTransient(status)) { return Denial.ASSIGNMENT_UNAVAILABLE; } if (status.getCode() == Status.Code.FAILED_PRECONDITION) { - return Denial.STALE_MENU_IDENTITY; + return menuIdentitySupplied ? Denial.STALE_MENU_IDENTITY : Denial.ROUTE_CHANGED; } return Denial.INVALID_ASSIGNMENT_PROOF; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index 499c791fe8..f3205c1ed1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -545,6 +545,33 @@ void mapsEntityGrpcFailuresByStatusAndReadBoundary() throws Exception { context(changedAssignment.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + + var changedAssignmentWithMenu = harness(twoActors()); + doThrow( + Status.FAILED_PRECONDITION + .withDescription("snapshot changed or selected actor is absent") + .asRuntimeException()) + .when(changedAssignmentWithMenu.stub()) + .readSelectedPreseededAssignment(any()); + var menuResult = + changedAssignmentWithMenu + .service() + .select( + context(changedAssignmentWithMenu.route(), "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + null, + null); + assertThat(menuResult) + .isInstanceOf(CanonicalGameplayRosterSelectionService.SelectionRequired.class); + var menuIdentity = + ((CanonicalGameplayRosterSelectionService.SelectionRequired) menuResult).menuIdentity(); + assertDenied( + changedAssignmentWithMenu + .service() + .select( + context(changedAssignmentWithMenu.route(), "ffffffff-ffff-4fff-8fff-ffffffffffff"), + "1", + menuIdentity), CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); for (Status.Code code : List.of(Status.Code.PERMISSION_DENIED, Status.Code.INVALID_ARGUMENT)) { From 749eaddce84d67241848871ea6c793d6a6f18b1e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:14:51 +1300 Subject: [PATCH 34/34] Prove UUID legacy tenant denial alongside blank tenant rejection --- .../service/impl/GameInstanceServiceImplTest.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) 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 991fbda17e..81fc275ae3 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 @@ -182,8 +182,9 @@ void legacyNumericLaunchFailsClosedBeforeMutation() { assertNumericLaunchDeniedWithoutMutation(request); } - @Test - void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority() { + @ParameterizedTest + @ValueSource(strings = {"", "123e4567-e89b-12d3-a456-426614174000"}) + void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority(String legacyTenantId) { StartSessionRequest request = new StartSessionRequest(1L, 3L, "cp-canonical-tenant", 42L); doReturn( ResolveLaunchDescriptorResponse.newBuilder() @@ -191,6 +192,7 @@ void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority() { net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() .setLaunchDescriptorId("ld-cp-canonical-tenant") .setCanonicalTenantId("123e4567-e89b-12d3-a456-426614174000") + .setTenantId(legacyTenantId) .setGameTemplateId(request.gameTemplateId()) .setControlPlaneRequestId(request.controlPlaneRequestId()) .setVersionId(11L) @@ -216,9 +218,6 @@ void canonicalTenantUuidCannotBeCoercedIntoLegacyNumericLaunchAuthority() { verify(gameDesignClient) .resolveLaunchDescriptor( request.tenantId(), request.gameTemplateId(), request.controlPlaneRequestId()); - verify(gameDesignClient, never()).getPublishedReleaseBundle(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionAssetArtifactState(anyLong(), anyLong()); - verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); verifyNoMoreInteractions(gameDesignClient); verifyNoInteractions(repository, worldManagementClient, stateService); }