From 81b52678917b8d2a81dbcf84760b8f249380fbd5 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:16:39 +1300 Subject: [PATCH 01/22] Prepare created actor owner and immediate roster consumer --- .../api-contracts.md | 17 +- .../runtime-and-data.md | 7 + .../game-session-service/api-contracts.md | 8 + .../game-session-service/runtime-and-data.md | 6 + .../gameplay-rules-entities-and-effects.md | 6 + .../player-access-and-session.md | 4 + .../canonical_gameplay_roster_recovery.proto | 2 + .../v1/entity_management_service.proto | 65 +- ...canonical_gameplay_roster_owner_read.proto | 7 + .../v1/character_create_target_service.proto | 58 ++ .../character_create_lifecycle_service.proto | 36 + .../charactercreate/public-action.json | 1 + .../common-platform-core/build.gradle.kts | 2 + ...nonicalGameplayRosterRecoveryEvidence.java | 46 +- ...onicalGameplayRosterReferenceEvidence.java | 268 ++++- ...nicalGameplayRosterRetirementEvidence.java | 37 +- .../CanonicalPlayerCreatedRosterEvidence.java | 552 ++++++++++ ...calGameplayRosterRecoveryEvidenceTest.java | 173 ++++ ...alGameplayRosterReferenceEvidenceTest.java | 357 +++++++ ...lGameplayRosterRetirementEvidenceTest.java | 138 +++ ...onicalPlayerCreatedRosterEvidenceTest.java | 856 +++++++++++++++ ...edPlayerCreatedRosterTerminalFixtures.java | 391 +++++++ .../build.gradle.kts | 9 + .../EntityCharacterCreateGrpcService.java | 65 ++ .../EntityCharacterCreatePeerInterceptor.java | 74 ++ .../EntityCharacterCreateProofs.java | 95 ++ .../EntityCharacterCreateRepository.java | 561 ++++++++++ .../EntityCharacterCreateService.java | 129 +++ .../EntityCharacterCreateSource.java | 54 + .../EntityPlayerCreatedRosterReadService.java | 192 ++++ .../EntityPlayerCreatedRosterService.java | 144 +++ ...PlayerCreatedRosterSnapshotRepository.java | 587 +++++++++++ ...essionCharacterCreateProtectionReader.java | 62 ++ .../AccountCharacterCreateSourceClient.java | 107 ++ ...anonicalGameplayRosterOwnerReadClient.java | 15 +- ...ameSessionCharacterCreateTargetClient.java | 159 +++ .../WorldCharacterCreateLifecycleClient.java | 89 ++ ...icalGameplayRosterRetentionRepository.java | 269 ++++- ...anonicalGameplayRosterPeerInterceptor.java | 6 + .../CanonicalGameplayRosterGrpcAdapter.java | 103 +- ...1015__entity_character_create_terminal.sql | 214 ++++ ...layer_created_roster_snapshot_receipts.sql | 157 +++ ...eseededActorAssignmentIntegrationTest.java | 7 +- .../RetainedActorIdentityIntegrationTest.java | 16 +- ...haracterCreatePostgresIntegrationTest.java | 978 ++++++++++++++++++ ...RosterSnapshotPostgresIntegrationTest.java | 765 ++++++++++++++ ...osterRetentionPostgresIntegrationTest.java | 492 +++++++++ ...ntakeMigrationPostgresIntegrationTest.java | 28 +- ...tySelectedSourceIntakePostgresFixture.java | 17 +- .../EntityCharacterCreateBindingsTest.java | 158 +++ .../EntityCharacterCreateMtlsTest.java | 169 +++ ...ityPlayerCreatedRosterReadServiceTest.java | 118 +++ .../EntityPlayerCreatedRosterServiceTest.java | 145 +++ ...ayerCreatedRosterSourceClientMtlsTest.java | 516 ++------- ...GameplayRosterOwnerReadClientMtlsTest.java | 99 +- ...icalGameplayRosterOwnerReadClientTest.java | 75 ++ ...icalGameplayRosterPeerInterceptorTest.java | 48 + ...anonicalGameplayRosterGrpcAdapterTest.java | 124 +++ .../charactercreate/entity-public-action.json | 1 + ...olledPlayerCreatedRosterSourceFixture.java | 798 ++++++++++++++ ...ionCharacterCreatePublicSourceService.java | 143 ++- .../CanonicalPlayerCreatedRosterClient.java | 386 +++++++ .../text/CanonicalGameplayActorSelection.java | 66 +- ...icalGameplayRosterReferenceRepository.java | 187 +++- ...CanonicalGameplayRosterReferenceOwner.java | 140 ++- ...nonicalGameplayRosterSelectionService.java | 278 ++++- ...V1020__player_created_roster_reference.sql | 266 +++++ ...osterReferencePostgresIntegrationTest.java | 676 +++++++++++- ...ialAdmissionRepositoryIntegrationTest.java | 4 +- ...haracterCreatePublicSourceServiceTest.java | 96 +- ...anonicalPlayerCreatedRosterClientTest.java | 751 ++++++++++++++ .../CanonicalGameplayActorSelectionTest.java | 70 ++ ...nicalGameplayRosterReferenceOwnerTest.java | 505 +++++++++ ...calGameplayRosterSelectionServiceTest.java | 712 +++++++++++++ ...alGameplayRosterReferenceGrpcMtlsTest.java | 67 +- 75 files changed, 14391 insertions(+), 638 deletions(-) create mode 100644 protos/game-session/v1/character_create_target_service.proto create mode 100644 protos/world-management/v1/character_create_lifecycle_service.proto create mode 100644 services/account-service/src/testFixtures/resources/charactercreate/public-action.json create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidence.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidenceTest.java create mode 100644 services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePeerInterceptor.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProofs.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/GameSessionCharacterCreateProtectionReader.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountCharacterCreateSourceClient.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCharacterCreateTargetClient.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/WorldCharacterCreateLifecycleClient.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java create mode 100644 services/entity-management-service/src/test/resources/charactercreate/entity-public-action.json create mode 100644 services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index a48544f514..9ec23dc680 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,12 +6,14 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status -The standalone, unregistered `EntityPlayerCreatedRosterSourceClient` reads Game Session’s [public character-creation source](../game-session-service/api-contracts.md#public-character-creation-source-read) through exact same-namespace workload mTLS. It checks the complete sealed policy set, original authored source, World lifecycle and current target together, retaining the owner-issued policy identity and digest separately from authored projection identities. Its private authenticated result supplies source input only. It has no current roster consumer and does not widen the existing `PRESEEDED_ONLY` roster or selected-assignment services, allocate a character, acquire protection or establish admission. +The standalone, unregistered `EntityPlayerCreatedRosterSourceClient` reads Game Session’s [public character-creation source](../game-session-service/api-contracts.md#public-character-creation-source-read) through exact same-namespace workload mTLS. It checks the complete sealed policy set, original authored source, World lifecycle and current target together, retaining the owner-issued policy identity and digest separately from authored projection identities. Its private authenticated result supplies source input only. The created-roster consumer remains a separate manually composed and unregistered path; neither path widens the existing `PRESEEDED_ONLY` roster or selected-assignment services, allocates a character, acquires protection or establishes admission. The prepared selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1011 adds the empty selected source catalogue over the current combined Entity/Saga parent, retaining explicit family and equipment evidence; this does not enable arbitrary authored templates, placement or gameplay admission. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-entity-and-automation-intake-prerequisite). Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has manually composed certificate-guarded client, peer-interceptor, and read-adapter source definitions, but no automatic runtime handler, client, or service-bean registration. Default component scanning and legacy activation flags leave this family unregistered; [Runtime and Data](./runtime-and-data.md#implementation-status) owns its registration prerequisites. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. +Forward V1016 adds the created snapshot branch to the existing sealed-roster family. The created-roster API and storage changes in this isolated candidate remain unvalidated and do not register the service, handler, or caller; no new owner-custody, gameplay-admission, or activation proof is claimed. + The manually composed Account/Game Session evidence bridge currently supports `SHARED` only; the assignment bridge requires already canonical, non-nil UUID game-instance text under the existing bridge contract. Those bounded adapters supply no owner proof outside their declared scope. They do not narrow the passive assignment core, which supports `SHARED` and `ISOLATED` and hashes exact bounded opaque game-instance text without parsing or normalization. The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `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. @@ -59,6 +61,7 @@ curl http://localhost:8080/ping - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. - `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – target `PRESEEDED_ONLY` pre-admission wire contract described in [Implementation Status](#implementation-status). Source models and manually composed certificate-guarded handler, peer-interceptor, client, and read-adapter source definitions are present; none of these or callers is registered. The result is discovery evidence, not actor admission or a session-binding shortcut. +- `CanonicalGameplayRosterService.ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter` – distinct non-admitting `PLAYER_CREATED` reads with the target contract described in [Player-created roster and selected character](#player-created-roster-and-selected-character). They do not change either preseeded method; this candidate's created-roster path remains unvalidated and unregistered. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains 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. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `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). @@ -79,6 +82,18 @@ For `DROP` and `PICKUP`, Entity is the holder-mutation participant in the canoni grpcurl -plaintext localhost:6565 entity_management.v1.EntityManagementService/Ping ``` +## Player-created roster and selected character + +`CanonicalGameplayRosterService.ListPlayerCreatedRoster(CanonicalPlayerCreatedRosterRequest)` and `ReadSelectedPlayerCreatedCharacter(CanonicalSelectedPlayerCreatedCharacterRequest)` are distinct non-admitting Entity owner reads. They require the exact authenticated same-namespace Game Session workload over mTLS and a closed `PlayerExecutionContext` whose operation, account, session, tenant, realm, playable namespace/scope and runtime instance agree with the request and full target. Listing has no selected actor; selected readback requires `context.character_id` to equal the requested actor. Entity independently obtains and compares the complete current published `PLAYER_CREATED` source, descriptor, policy, canonical version and `SHARED` target before local work. Missing, changed or unsupported source evidence fails closed. `ListPreseededRoster` and `ReadSelectedPreseededAssignment` remain strictly `PRESEEDED_ONLY`; `AUTO_PROVISIONED` is unsupported by these roster methods. + +The request carries the exact expected source identity: schema version 1, canonical non-nil descriptor UUID and revision UUID, descriptor digest, authored-binding UUID and authored-binding digest. Both digests use `sha256:` followed by 64 lowercase hexadecimal characters. The response retains that source identity and an ordered projection of persisted eligible actors with an immutable Entity snapshot UUID and digest. Zero actors is a valid empty snapshot and allocates none. The created digest uses domain `firemud.entity.player-created-roster.v1` and binds the canonical account, complete canonical target, exact source identity and ordered actor UUID/display-name pairs; it does not replace or recompute retained preseeded digests. The owner-issued policy digest remains distinct from authored projection content digests. Source identity and parsed wire values are comparison evidence, not peer authentication or an Account, membership, creation or admission capability. + +Selected readback names the same original Game Session operation UUID and retained menu/selection, account, session, complete target, source identity, frozen chosen actor UUID and snapshot UUID/digest. Entity requires that actor to occur exactly once in the original immutable roster and revalidates its actual persisted creation provenance. It returns the original `COMMITTED` `CHARACTER_CREATE` operation UUID, unchanged mutation digest and complete original terminal in `CanonicalSelectedPlayerCreatedCharacterResponse`; it never returns an assignment UUID or invents a replacement operation. Original creation runtime-instance/pointer/catalog counters are not durable actor identity and are not rewritten to the current route. Selected readback allocates no actor and requires the existing local admission nonce and original receipt. + +Source and original-owner RPCs run outside Entity SQL transactions. Capture and readback join the existing admission/original-operation and shared roster fences; exact retained operation replay returns the original full created receipt, and a changed binding or unknown outcome remains protected. The local transaction and storage consequences belong to [Runtime and Data](./runtime-and-data.md#player-created-snapshot-storage). Recovery preserves the distinct created roster receipt without converting it into a preseeded response or dropping its source identity; closure and retirement retain the existing reference/hold protections. + +The created request bound is 16 KiB, source identity 4 KiB and complete roster receipt 66 KiB. The full creation terminal remains bounded to 192 MiB and selected-character response to 193 MiB. These are purpose-specific bounds; they do not widen the old preseeded messages or grant transport custody. Complete selected evidence must survive the original-reference and retirement paths within their declared purpose limits, without truncation or removal of opaque owner protection bytes. Common validation checks exact value bindings only; authenticating the source and consumer remains the owning service's responsibility. + ## Character creation owner protection The approved passive common-platform-core `CHARACTER_CREATE/1` model, codec, and bounded authored-source projection are present. The standalone parent check completed 233 tasks and 372 common-platform-core tests with zero failures, errors, or skips; this does not establish an authenticated producer, owner protections, or Entity terminal composition. The fixed ordered family and raw/normalized limits are owned by the [CHARACTER_CREATE/1 action schema](./character-create-action-schema.md), using ADR 0047's unchanged byte grammar. diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index b799b54a79..3b8f900aaa 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -23,6 +23,7 @@ This document defines Entity Management’s runtime model, persistence ownership - Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude actors carrying canonical `tenant_uuid` provenance even when their status becomes `QUARANTINED`, including updates and condition expiry. Legitimate legacy/quarantined rows with null canonical tenant provenance retain legacy behavior. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The services and certificate-guarded client/read-adapter source definitions are manually composed and unregistered; neither default scanning nor an optional flag registers them. No authenticated production transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). +- Forward V1016 adds the immutable `PLAYER_CREATED` source identity and created-receipt branch to the shared snapshot family while preserving the `PRESEEDED_ONLY` guards and budgets. This isolated candidate's created-roster changes remain unvalidated and unregistered; the source/selected owner chain does not establish production custody, actor admission or `PLAY`. - Sealed canonical roster snapshots and their actor references are immutable Entity-owned records: append a new snapshot/reference set when the canonical target or roster changes, preserving the existing deletion guards. The [family retention declaration](#sealed-canonical-roster-retention) defines its ADR 0163 obligations. Before any handler, service, or alternative snapshot writer is registered, owner-local disposal must be proved with authoritative terminal/reference/hold carriers and compatible configured horizons. Local carrier and disposal source is prepared with focused qualification; genuine producer composition and registration remain unavailable. See the [implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). This does not set a numeric horizon, authorize deletion, or establish indefinite retention. The current passive writer has no registered production call chain; its pending implementation obligation is tracked under #2967 and is not completion or merge proof. - Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. @@ -333,6 +334,12 @@ An unbound `OPEN` admission with no local original selection is a distinct local The configured cadence and batch bound limit each owner-local sweep. Its bounded health metrics must report oldest blocking retirement, cleanup lag and per-sweep disposed/blocked/failure counts with fixed outcome labels; snapshot, actor, account, tenant and namespace identifiers must not become metric labels. These are family-specific cleanup obligations, not a global garbage-collection registration. +#### Player-created snapshot storage + +Forward `V1016__player_created_roster_snapshot_receipts.sql` extends the existing sealed-roster family after Entity creation V1015. A `PLAYER_CREATED` snapshot requires `SHARED` scope and immutable canonical `canonical_player_created_source_identity` bytes; preseeded snapshots keep that column null. Immutable entry-policy metadata selects the applicable admission, original receipt, lifecycle-proof and outbox branch. The created original receipt is distinct and mutually exclusive with the preseeded receipt. Prior preseeded digest/history, provenance, immutability, reference/hold, epoch, conditional-disposal and late-nonce guards remain effective. Created receipt/proof/ACK storage uses its explicit purpose budgets, including the complete selected terminal in retirement evidence, while existing preseeded caps remain unchanged. The [Entity API owner](./api-contracts.md#player-created-roster-and-selected-character) defines the wire identities and bounds. + +Capture uses one short writable owner transaction in the established order: admission nonce, original operation, namespace enrollment, tenant association and account roster guard, then the applicable snapshot/reference rows. Under those fences it checks actual retained creation-operation and actor provenance, captures the ordered roster, persists or reuses its exact source-bound snapshot, seals it and binds admission plus original receipt atomically. Any failed validation or bind rolls the capture back. Exact operation replay reads the retained receipt; selected readback requires the existing nonce and immutable original snapshot, checks the persisted original creation terminal and performs no actor allocation. Source and owner RPCs precede SQL, and the shared retention/recovery/outbox family preserves full created receipt bytes while using a validated generic projection only for snapshot comparisons. Unknown outcomes and outstanding references or holds retain their existing protection. + ### Persisted actor and realm-entry identity Under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md), Entity Management is the persistence authority for the generic primary controllable actor. It allocates canonical `characterId` values and stores the namespace/association tuple `{accountId, tenantId, playableStateNamespaceId, characterId}`. The durable actor storage key is `{tenantId, playableStateNamespaceId, characterId}`; `playableStateScope` is separately validated server-derived policy/routing evidence and `gameInstanceId` is only the replaceable active-runtime fence for namespace-backed writes. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index f1ec218201..58b8f38573 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -36,6 +36,8 @@ This document mixes live and target-state control-plane surfaces. Current live b Read the pause/status/recovery APIs below as the target-state contract unless the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) explicitly records them as live. +The isolated created-owner consumer candidate contains Game Session migrations V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage. V1020's created-receipt branch does not supply either missing prerequisite. The created consumer and transfer semantics below remain unvalidated in this candidate, unregistered, and are not evidence of production custody or admission; the independently qualified public character-creation source-read contract above remains a separate boundary. + For script transitions, the live boundary includes the exact `scriptPinEpoch` and an atomic current-pin/request-result ledger commit; bounded authoritative history readback and append-only rollout history remain target-state gaps. Target pin and rollback requests require the explicit tagged `expectedCurrentPin` precondition defined in the [Scripting Control Plane API](../../system-architecture-scripting-control-plane-api.md): exactly `UNCONDITIONAL`, `EXPECT_UNPINNED`, or `EXPECT_EPOCH(scriptPinEpoch)`, with the complete tag/value included in the normalized digest. Missing/unknown tags fail validation; a both-absent tuple for a never-pinned instance is valid semantic `UNPINNED` and matches only `EXPECT_UNPINNED`; a partial tuple is invalid owner state, cannot satisfy `EXPECT_UNPINNED` or `EXPECT_EPOCH`, and is rejected/fails closed even for an `UNCONDITIONAL` request. Missing or unreadable authority is not `UNPINNED` and remains unavailable. `UNCONDITIONAL` is only the explicit `platformAdmin` break-glass repair branch with the matrix's `privileged_control` authorization; it skips only current-pin comparison and does not bypass coherent owner state, readiness, or other validation. See [Rollout and Rollback](../../system-architecture-scripting-rollout-and-rollback.md#pin-compare-and-set-preconditions) for the owner semantics. A valid precondition mismatch is deterministic and non-mutating and follows the existing idempotency/history semantics. ## Service Interactions @@ -102,6 +104,12 @@ Entity reserves a local admission nonce before its owner RPC, binds its snapshot Entity durably records that authenticated response before confirming delivery. Confirmation is bound to the same request and receipt. A confirmation repeated after qualified compact-receipt cleanup is only a no-op and cannot create acknowledgement or release authority. Required inventory, finite receipt retention, pending-transfer protection and owner-local cleanup belong to [Game Session runtime/data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership); Entity's local atomic observation and outbox rules belong to [sealed roster retention](../entity-management-service/runtime-and-data.md#sealed-canonical-roster-retention). Both transfer handlers retain the existing unregistered original-reference owner dependency and do not enable admission or production activation. +#### Player-created original roster consequences + +Game Session consumes Entity's distinct [player-created roster and selected-character contract](../entity-management-service/api-contracts.md#player-created-roster-and-selected-character) only after independently resolving the current published `PLAYER_CREATED` source and matching the complete route, policy, descriptor and source identity. It retains the exact typed created-roster and selected-character receipts on the original operation, preserves the original menu and ordinal/frozen actor choice, and revalidates the current route around owner reads. These receipts provide no membership, session-binding or gameplay-admission authority. The existing preseeded route remains a separate strict branch; a Common parser validates values without establishing authenticated custody. + +The created reference response retains the complete selected payload within its 194 MiB purpose envelope, and retirement-observation requests retain it within the 195 MiB created-ACK envelope with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within its existing recovery purpose bound. These purpose-specific limits preserve complete owner bytes and the existing preseeded limits; they do not raise a global gRPC limit. The corresponding local storage consequences belong to [Runtime and Data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership). + #### 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`. 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 bfca1bf909..f61d8c237b 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -42,6 +42,8 @@ The sections below define the target-state runtime contract. Current implementat - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). + +- The isolated created-owner consumer candidate includes Game Session migration V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage. V1020's created-receipt fields do not supply either missing prerequisite. The created consumer and receipt transfer path remain unvalidated and unregistered in this candidate; no UUID-runtime, protection, authenticated-custody, or gameplay-admission proof is claimed. - The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. ## Runtime Details @@ -81,6 +83,10 @@ Each acknowledgement binds the original operation, full account/target and same- Compact transfer receipts survive original removal and remain protected until Entity confirms it durably received the first acknowledgement response. Their finite cleanup horizon covers both owners' declared retry/restore windows and starts after both confirmation and original removal. A lost request or reply retries the same immutable transfer. Once a confirmed receipt has itself been lawfully disposed, repeating its delivery confirmation is a harmless no-op: it creates no acknowledgement, release, retirement proof or target authority. Missing first-acknowledgement evidence remains unavailable. Unconfirmed transfer lineage remains protected rather than discarding the only retry evidence. +#### Player-created original roster storage + +The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. The original-reference response preserves the complete selected payload within its 194 MiB purpose bound; retirement observation preserves it within the 195 MiB created-ACK bound with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within the existing recovery bound. These purpose-specific byte limits preserve owner bytes and preseeded limits; they do not widen global gRPC defaults. V1020 supplies the distinct receipt branch, not the absent V1018 canonical UUID or V1019 creation-protection storage. + The unregistered bounded retention service uses the configured cadence and batch bound, pages past protected candidates, and reports oldest blocking age, cleanup lag, pending-transfer age and fixed cleanup outcomes without identity-bearing metric labels. Unfinished or unavailable authority remains protected. Production registration and real gameplay admission stay closed pending the [owning proof gate](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). ## Owner-Local Gameplay Restrictions diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 1d74dda028..accdfafc8b 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ## Current Status +### Player-created owner and roster candidate + +The local, unregistered candidate adds Entity's `CHARACTER_CREATE` terminal writer and source-bound created-roster capture/readback, together with Common evidence and the immediate Game Session receipt consumer. Entity V1015 and V1016 retain the creation terminal and created snapshot branch; Game Session V1020 retains the distinct created receipt without changing the preseeded branch. Canonical behavior belongs to the [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) and [sealed roster storage](../../architecture/microservices/entity-management-service/runtime-and-data.md#player-created-snapshot-storage). + +This candidate has not yet passed its own consolidated qualification. Earlier source and mixed-worktree results retain their original attribution and do not qualify this isolated composition. Game Session UUID runtime and creation-protection storage remain separate receiving work; actual original Game Session creation-owner → Entity capture → Game Session receipt composition, genuine source custody, runtime registration, Account protection and settlement, region/execution handoffs, public admission and activation remain open. Controlled upstream facts and component or socket fixtures cannot close those gaps. + ### Canonical sealed roster retention prerequisite The unregistered passive composition implements Entity V1012 admission, sealed snapshot/reference/recovery and bounded disposal paths, Entity V1014 durable retirement-transfer retries, and Game Session V1015 selection/reference ownership plus V1017 acknowledgement inventory. Its supported consumers are PRESEEDED_ONLY roster/menu and selected-assignment readback. Required finite-horizon configuration, exact nonce/fence binding, reference/hold protection and fixed-label sweep metrics are implemented. Canonical contracts remain in [Entity sealed roster retention](../../architecture/microservices/entity-management-service/runtime-and-data.md#sealed-canonical-roster-retention), [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#canonical-roster-selection-and-reference-ownership) and the [original-reference API](../../architecture/microservices/game-session-service/api-contracts.md#original-canonical-roster-selection-reference). 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 9226bb136d..abd1e0e6c3 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,10 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Player-created roster consumer candidate + +The local, unregistered candidate consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. Consolidated proof of this isolated candidate is pending. Its V1020 receipt storage does not include the separate V1018 UUID runtime or V1019 creation-protection owners, and supplies no Account protection, admission, activation or genuine playable-journey proof. Qualified public source-read results below retain their original source attribution. + ### Public character-creation and created-roster source preparation The review correction at `e6682785db8c4aa678ce730b1361f02525fff639` preserves the source boundary and distinguishes downstream transport unavailability, owner-evidence rejection and malformed caller input. R80 freshly passes all 2,528 Game Session unit cases, affected static analysis and formatting, links and Markdown. R81 rebuilds fresh service images from that correction and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms its containers, networks and volumes absent. This qualifies the correction within those controlled boundaries, without genuine production custody, created-roster consumption, registration, successful public admission or activation. The independently attributed source qualification follows. diff --git a/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto b/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto index 2013af10ad..811c09313e 100644 --- a/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto +++ b/protos/entity-management/v1/canonical_gameplay_roster_recovery.proto @@ -29,5 +29,7 @@ message CanonicalGameplayRosterRecoveryResponse { string target_fence_uuid = 5; // Exact locally retained original receipt, if capture won before nonce closure. Absence is // positive fenced no-capture evidence only in this authenticated closed-admission response. + // PRESEEDED_ONLY; mutually exclusive with the distinct PLAYER_CREATED receipt. bytes canonical_roster_receipt = 6; + bytes canonical_player_created_roster_receipt = 7; } diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index eda2eb2236..d84b267aa7 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -5,6 +5,7 @@ package entity_management.v1; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; import "shared/v1/player_execution_context.proto"; +import "entity-management/v1/entity_character_create_service.proto"; option java_package = "net.firedevops.firemud.entitymanagement.v1"; option java_multiple_files = true; @@ -37,11 +38,12 @@ service EntityManagementService { returns (ValidateEntityUpgradeMappingsResponse); } -// 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 +// Canonical gameplay roster discovery is a pre-admission, non-admitting boundary. The two +// preseeded methods below remain restricted to PRESEEDED_ONLY; other policy values are +// non-authorizing and fail with FAILED_PRECONDITION. The PLAYER_CREATED methods are a separate +// source-bound read contract and do not authenticate their unsigned context or 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 @@ -67,6 +69,59 @@ service CanonicalGameplayRosterService { // selected_character_uuid. The target policy must be PRESEEDED_ONLY. rpc ReadSelectedPreseededAssignment(CanonicalGameplayRosterSelectedAssignmentRequest) returns (CanonicalGameplayRosterSelectedAssignmentResponse); + + // Reads the source-bound persisted PLAYER_CREATED roster. The unsigned execution context is + // equality evidence only; peer authentication remains a server responsibility. + rpc ListPlayerCreatedRoster(CanonicalPlayerCreatedRosterRequest) + returns (CanonicalPlayerCreatedRosterResponse); + // Reads the exact selected actor from the original source-bound snapshot and returns the + // persisted creation terminal. This carrier does not authenticate that terminal. + rpc ReadSelectedPlayerCreatedCharacter(CanonicalSelectedPlayerCreatedCharacterRequest) + returns (CanonicalSelectedPlayerCreatedCharacterResponse); +} + +message CanonicalPlayerCreatedRosterSourceIdentity { + uint32 schema_version = 1; + string descriptor_uuid = 2; + string descriptor_revision_uuid = 3; + string descriptor_digest = 4; + string authored_binding_uuid = 5; + string authored_binding_digest = 6; +} + +message CanonicalPlayerCreatedRosterRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + CanonicalGameplayRosterTarget expected_target = 3; + shared.v1.PlayerExecutionContext player_execution_context = 4; + CanonicalPlayerCreatedRosterSourceIdentity expected_source = 5; +} + +message CanonicalPlayerCreatedRosterResponse { + CanonicalGameplayRosterResponse roster = 1; + CanonicalPlayerCreatedRosterSourceIdentity source_identity = 2; +} + +message CanonicalSelectedPlayerCreatedCharacterRequest { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget expected_target = 4; + CanonicalGameplayRosterSnapshotReference expected_snapshot = 5; + shared.v1.PlayerExecutionContext player_execution_context = 6; + CanonicalPlayerCreatedRosterSourceIdentity expected_source = 7; +} + +message CanonicalSelectedPlayerCreatedCharacterResponse { + string request_uuid = 1; + string canonical_account_uuid = 2; + string selected_character_uuid = 3; + CanonicalGameplayRosterTarget target = 4; + CanonicalGameplayRosterSnapshotReference snapshot = 5; + CanonicalPlayerCreatedRosterSourceIdentity source_identity = 6; + string creation_operation_uuid = 7; + string mutation_digest = 8; + EntityCharacterCreateTerminal terminal = 9; } message CanonicalGameplayRosterRequest { diff --git a/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto index 3c3e6726c1..3c2ead5848 100644 --- a/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto +++ b/protos/game-session/v1/canonical_gameplay_roster_owner_read.proto @@ -100,6 +100,8 @@ message GetCanonicalGameplayRosterReferenceRequest { string session_uuid = 4; string target_namespace = 5; bytes canonical_target = 6; + // Canonical CanonicalPlayerCreatedRosterSourceIdentity bytes, required only for PLAYER_CREATED. + bytes canonical_player_created_source_identity = 7; } enum CanonicalGameplayRosterReferenceState { @@ -116,6 +118,7 @@ message GetCanonicalGameplayRosterReferenceResponse { CanonicalGameplayRosterReferenceState state = 3; // Canonical Entity snapshot response bytes, present only after receipt binding. Recording a // receipt does not release its retained selection/session/recovery/restore dependencies. + // PRESEEDED_ONLY receipt; mutually exclusive with the PLAYER_CREATED carrier below. bytes canonical_roster_receipt = 4; CanonicalGameplayRosterSelectionInput selection_input = 5; string selected_character_uuid = 6; @@ -130,6 +133,10 @@ message GetCanonicalGameplayRosterReferenceResponse { string retirement_proof_digest = 15; // Owner-local recovery fence: normal reads/writes cannot restart this original operation. string recovery_uuid = 16; + // Canonical typed PLAYER_CREATED roster and selected original creation terminal receipts. + // PRESEEDED_ONLY roster/assignment fields must be absent for this distinct policy branch. + bytes canonical_player_created_roster_receipt = 17; + bytes canonical_selected_player_created_character_receipt = 18; } // Original selection input is frozen before any Entity roster read. A later ordinal choice is a diff --git a/protos/game-session/v1/character_create_target_service.proto b/protos/game-session/v1/character_create_target_service.proto new file mode 100644 index 0000000000..e17cfdb456 --- /dev/null +++ b/protos/game-session/v1/character_create_target_service.proto @@ -0,0 +1,58 @@ +syntax = "proto3"; + +package game_session.v1; + +import "account/v1/character_create_source_service.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; + +// Unregistered exact-purpose owner boundary. Account acquires; Entity independently reads +// the retained original. Neither response supplies World lifecycle or Account authority. +service CharacterCreateTargetService { + rpc AcquireCharacterCreateTargetProtection(AcquireCharacterCreateTargetProtectionRequest) + returns (CharacterCreateTargetProtection); + rpc ReadOriginalCharacterCreateTargetProtection(ReadOriginalCharacterCreateTargetProtectionRequest) + returns (CharacterCreateTargetProtection); +} + +message AcquireCharacterCreateTargetProtectionRequest { + account.v1.ReadOriginalCharacterCreateProtectionRequest account_protection = 1; +} + +message ReadOriginalCharacterCreateTargetProtectionRequest { + account.v1.ReadOriginalCharacterCreateProtectionRequest account_protection = 1; + string game_session_protection_id = 2; + int64 game_session_protection_fence = 3; +} + +message CharacterCreateTargetProtection { + account.v1.ReadOriginalCharacterCreateProtectionResponse account_protection = 1; + string game_session_protection_id = 2; + int64 game_session_protection_fence = 3; + string acquired_at = 4; + bytes original_target_evidence = 5; +} + +// Exact GS-owned snapshot retained when the target protection commits. The action is the +// unchanged CHARACTER_CREATE/1 preimage; these owner fields identify its independently read +// catalog, current pointer and launch binding. This is not World lifecycle protection. +message CharacterCreateTargetSnapshot { + uint32 schema_version = 1; + bytes original_action = 2; + string target_namespace = 3; + string operation_id = 4; + string mutation_digest = 5; + string canonical_tenant_id = 6; + string realm_id = 7; + string canonical_game_instance_id = 8; + string canonical_version_id = 9; + string playable_state_namespace_id = 10; + int64 catalog_revision = 11; + int64 pointer_version = 12; + int64 active_world_epoch = 13; + string catalog_receipt_digest = 14; + string initial_admission_request_id = 15; + string initial_admission_owner_proof_digest = 16; + string admission_pointer_snapshot_digest = 17; +} diff --git a/protos/world-management/v1/character_create_lifecycle_service.proto b/protos/world-management/v1/character_create_lifecycle_service.proto new file mode 100644 index 0000000000..af649ce1c8 --- /dev/null +++ b/protos/world-management/v1/character_create_lifecycle_service.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package world_management.v1; + +import "account/v1/character_create_source_service.proto"; + +option java_package = "net.firedevops.firemud.worldmanagement.v1"; +option java_multiple_files = true; + +// Unregistered CHARACTER_CREATE owner protection. No activation, admission or terminal authority. +service CharacterCreateLifecycleService { + // Exact same-namespace Account workload only; World independently reads Account's original rows. + rpc AcquireCharacterCreateLifecycleProtection(AcquireCharacterCreateLifecycleProtectionRequest) + returns (WorldCharacterCreateLifecycleProtection); + // Exact same-namespace Entity workload only; immutable original acquisition, never a refresh. + rpc ReadOriginalCharacterCreateLifecycleProtection(ReadOriginalCharacterCreateLifecycleProtectionRequest) + returns (WorldCharacterCreateLifecycleProtection); +} + +message AcquireCharacterCreateLifecycleProtectionRequest { + account.v1.ReadOriginalCharacterCreateProtectionRequest account_protection = 1; +} + +message ReadOriginalCharacterCreateLifecycleProtectionRequest { + account.v1.ReadOriginalCharacterCreateProtectionRequest account_protection = 1; + string world_protection_id = 2; + int64 world_protection_fence = 3; +} + +message WorldCharacterCreateLifecycleProtection { + account.v1.ReadOriginalCharacterCreateProtectionResponse account_protection = 1; + string world_protection_id = 2; + int64 world_protection_fence = 3; + string acquired_at = 4; + bytes original_lifecycle_evidence = 5; +} diff --git a/services/account-service/src/testFixtures/resources/charactercreate/public-action.json b/services/account-service/src/testFixtures/resources/charactercreate/public-action.json new file mode 100644 index 0000000000..a63aa694c7 --- /dev/null +++ b/services/account-service/src/testFixtures/resources/charactercreate/public-action.json @@ -0,0 +1 @@ +{"actionFamilySchemaId":"firemud.entity.create-character","actionFamilySchemaVersion":"1","scope":{"targetNamespace":"firemud","tenantId":"a1000000-0000-4000-8000-000000000001","playableStateNamespaceId":"a3000000-0000-4000-8000-000000000001","playableStateScope":"PLAYABLE_STATE_SCOPE_SHARED"},"target":{"accountId":"a4000000-0000-4000-8000-000000000001","realmId":"a2000000-0000-4000-8000-000000000001","worldSlug":"ember-vale","realmSlug":"salt-harbor","gameInstanceId":"a5000000-0000-4000-8000-000000000001","versionId":"a6000000-0000-4000-8000-000000000001"},"expectedVersion":{"catalogRevision":"17","pointerVersion":"23","activeLifecycleEpoch":"31","evaluatedAt":"2026-10-11T12:34:56.123456789Z","connectScopeExpiresAt":"2026-10-11T12:39:56.987654321Z"},"mutation":{"purpose":"CHARACTER_CREATE","entryPolicy":"PLAYER_CREATED","catalog":{"tenantId":"a1000000-0000-4000-8000-000000000001","tenantSlug":"tideward","worldSlug":"ember-vale","worldDisplayName":{"encoding":"utf8-base64url-unpadded","bytes":"RW1iZXIgUmVhY2g"},"realmId":"a2000000-0000-4000-8000-000000000001","realmSlug":"salt-harbor","realmDisplayName":{"encoding":"utf8-base64url-unpadded","bytes":"U2FsdCBIYXJib3I"},"visible":true,"publicProduction":true,"stateScope":"SHARED","playableStateNamespaceId":"a3000000-0000-4000-8000-000000000001","characterCreationPolicy":"PLAYER_CREATED","catalogRevision":"17"},"pointer":{"tenantId":"a1000000-0000-4000-8000-000000000001","realmId":"a2000000-0000-4000-8000-000000000001","worldSlug":"ember-vale","realmSlug":"salt-harbor","admissionState":"OPEN","admissibleGameInstanceId":"a5000000-0000-4000-8000-000000000001","pointerVersion":"23","catalogRevision":"17","updatedAt":"2026-10-11T12:30:01.012345678Z"},"authoredSource":{"schema":"game-design-authored-initial-actor-core-projection/v1","bindingId":"a7000000-0000-4000-8000-000000000001","bindingDigest":"sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a","canonicalTenantId":"a1000000-0000-4000-8000-000000000001","canonicalVersionId":"a6000000-0000-4000-8000-000000000001","worldSourceOperationId":"a8000000-0000-4000-8000-000000000001","worldSourceEvidenceDigest":"sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263","worldSlug":"ember-vale","publicationWorkflowId":{"encoding":"utf8-base64url-unpadded","bytes":"cHVibGlzaGVkLWVtYmVyLXdvcmtmbG93LTIwMjYtMTAtMTE"},"selectedCommitId":"a9000000-0000-4000-8000-000000000001","selectedCommitDigest":"sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a","policy":{"commitId":"aa000000-0000-4000-8000-000000000001","revisionId":"ab000000-0000-4000-8000-000000000001","logicalRevisionId":{"encoding":"utf8-base64url-unpadded","bytes":"cG9saWN5LWxvZ2ljYWwtZW1iZXItcjQ"},"canonicalPolicyJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJjcmVhdGlvbkRlc2NyaXB0b3IiOnsiZGVwZW5kZW5jaWVzIjpbXSwiZGVzY3JpcHRvcklkIjoiYWMwMDAwMDAtMDAwMC00MDAwLTgwMDAtMDAwMDAwMDAwMDAxIiwiZGVzY3JpcHRvclJldmlzaW9uSWQiOiJhZDAwMDAwMC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDEiLCJpbnB1dEtpbmQiOiJFTVBUWV9PQkpFQ1QiLCJzY2hlbWFWZXJzaW9uIjoxfSwiZW50cnlQb2xpY3kiOiJQTEFZRVJfQ1JFQVRFRCIsImluaXRpYWxBY3RvckNvcmUiOnsiZGlzcGxheU5hbWUiOiJXYXlmYXJlciIsImRpc3Bvc2l0aW9uS2V5IjoibmV3Y29tZXIifSwicHVibGljUHJvZHVjdGlvbiI6dHJ1ZSwicmVhbG1EaXNwbGF5TmFtZSI6IlNhbHQgSGFyYm9yIiwicmVhbG1TbHVnIjoic2FsdC1oYXJib3IiLCJzY2hlbWFWZXJzaW9uIjozLCJzdGF0ZVNjb3BlIjoiU0hBUkVEIiwidmlzaWJsZSI6dHJ1ZSwid29ybGREaXNwbGF5TmFtZSI6IkVtYmVyIFJlYWNoIiwid29ybGRTbHVnIjoiZW1iZXItdmFsZSJ9"},"contentDigest":"sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1"},"core":{"canonicalJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJkaXNwbGF5TmFtZSI6IldheWZhcmVyIiwiZGlzcG9zaXRpb25LZXkiOiJuZXdjb21lciJ9"}},"descriptor":{"canonicalJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJkZXBlbmRlbmNpZXMiOltdLCJkZXNjcmlwdG9ySWQiOiJhYzAwMDAwMC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDEiLCJkZXNjcmlwdG9yUmV2aXNpb25JZCI6ImFkMDAwMDAwLTAwMDAtNDAwMC04MDAwLTAwMDAwMDAwMDAwMSIsImlucHV0S2luZCI6IkVNUFRZX09CSkVDVCIsInNjaGVtYVZlcnNpb24iOjF9"},"digest":"sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415"},"disposition":{"key":"newcomer","definitionJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJkZW5pZWRBZG1pc3Npb25UYWdzIjpbXSwiZGlzcG9zaXRpb25LZXkiOiJuZXdjb21lciIsInNhZmVGZWVkYmFja0tleSI6IndlbGNvbWUifQ"},"definitionDigest":"sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b","sourceCommitId":"ae000000-0000-4000-8000-000000000001","sourceCommitDigest":"sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2","revisionId":"af000000-0000-4000-8000-000000000001","revisionOrder":"41"},"safeFeedback":{"key":"welcome","definitionJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJhcmd1bWVudHMiOltdLCJhdWRpZW5jZSI6IlNPVVJDRV9BQ1RPUiIsImZlZWRiYWNrS2V5Ijoid2VsY29tZSIsIm1lc3NhZ2VLZXkiOiJ3ZWxjb21lX21lc3NhZ2UiLCJtZXNzYWdlVGVtcGxhdGUiOiJXZWxjb21lLCB0cmF2ZWxlci4iLCJvdXRjb21lRXZlbnQiOiJhY3Rvcl9jcmVhdGVkIiwicmVwbGF5UG9saWN5IjoiRUZGRUNUX0lERU1QT1RFTlQiLCJ2aXNpYmlsaXR5IjoiUFVCTElDIn0"},"definitionDigest":"sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871","sourceCommitId":"ae000000-0000-4000-8000-000000000001","sourceCommitDigest":"sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2","revisionId":"b0000000-0000-4000-8000-000000000001","revisionOrder":"42"}},"canonicalCreationInput":"{}"}} diff --git a/services/common-platform-core/build.gradle.kts b/services/common-platform-core/build.gradle.kts index 6cb1980995..6f1d4950ea 100644 --- a/services/common-platform-core/build.gradle.kts +++ b/services/common-platform-core/build.gradle.kts @@ -33,4 +33,6 @@ dependencies { testFixturesApi(platform(libs.spring.boot.dependencies)) testFixturesApi("tools.jackson.core:jackson-databind") testFixturesApi(libs.grpc.stub) + testFixturesApi(libs.protobuf.java) + testFixturesCompileOnly(libs.spotbugs.annotations) } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java index 3e0fe61df4..fa84ae9712 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidence.java @@ -2,9 +2,11 @@ import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; /** @@ -47,6 +49,9 @@ public static CanonicalGameplayRosterRecoveryResponse response( long ownerFence, UUID targetFence, CanonicalGameplayRosterResponse receipt) { + requireRequest(request); + if (created(request)) + throw new IllegalArgumentException("PRESEEDED_ONLY recovery response factory required"); var result = CanonicalGameplayRosterRecoveryResponse.newBuilder() .setSchemaVersion(1) @@ -58,6 +63,32 @@ public static CanonicalGameplayRosterRecoveryResponse response( return requireResponse(request, result.build()); } + public static CanonicalGameplayRosterRecoveryResponse playerCreatedResponse( + CanonicalGameplayRosterRecoveryRequest request, + UUID admission, + long ownerFence, + UUID targetFence, + CanonicalPlayerCreatedRosterResponse receipt) { + requireRequest(request); + if (!created(request)) + throw new IllegalArgumentException("PLAYER_CREATED recovery response factory required"); + var result = + CanonicalGameplayRosterRecoveryResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setAdmissionUuid(admission.toString()) + .setOwnerFence(ownerFence) + .setTargetFenceUuid(targetFence.toString()); + if (receipt != null) result.setCanonicalPlayerCreatedRosterReceipt(receipt.toByteString()); + return requireResponse(request, result.build()); + } + + private static boolean created(CanonicalGameplayRosterRecoveryRequest request) { + return CanonicalGameplayRosterReferenceEvidence.target(request.getOriginalSelection()) + .getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED; + } + public static CanonicalGameplayRosterRecoveryResponse requireResponse( CanonicalGameplayRosterRecoveryRequest expected, CanonicalGameplayRosterRecoveryResponse response) { @@ -73,12 +104,21 @@ public static CanonicalGameplayRosterRecoveryResponse requireResponse( } CanonicalGameplayRosterReferenceEvidence.uuid(response.getAdmissionUuid()); CanonicalGameplayRosterReferenceEvidence.uuid(response.getTargetFenceUuid()); - if (!response.getCanonicalRosterReceipt().isEmpty()) { - // Reuse the canonical original-receipt parser and exact target/account binding. - CanonicalGameplayRosterReferenceEvidence.receipt( + boolean created = created(expected); + if ((created && !response.getCanonicalRosterReceipt().isEmpty()) + || (!created && !response.getCanonicalPlayerCreatedRosterReceipt().isEmpty())) { + throw new IllegalArgumentException( + "Recovery receipt changed its explicit roster policy branch"); + } + if (!response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + // Exact validated projection only; this does not authenticate an Entity response. + CanonicalGameplayRosterReferenceEvidence.snapshotReceipt( GetCanonicalGameplayRosterReferenceResponse.newBuilder() .setRequest(expected.getOriginalSelection()) .setCanonicalRosterReceipt(response.getCanonicalRosterReceipt()) + .setCanonicalPlayerCreatedRosterReceipt( + response.getCanonicalPlayerCreatedRosterReceipt()) .build()); } return response; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java index bec97c97b1..d60dc1a5e4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java @@ -8,16 +8,30 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; /** Closed original-operation carrier. Neither RESERVED nor RECORDED is retirement authority. */ public final class CanonicalGameplayRosterReferenceEvidence { public static final int MAX_REQUEST_BYTES = 4096; public static final int MAX_RECEIPT_BYTES = 64 * 1024; + public static final int MAX_SELECTED_ASSIGNMENT_BYTES = 8192; + public static final int MAX_RESPONSE_BYTES = 128 * 1024; + public static final int MAX_PLAYER_CREATED_RECEIPT_BYTES = + CanonicalPlayerCreatedRosterEvidence.MAX_ROSTER_RECEIPT_BYTES; + public static final int MAX_SELECTED_PLAYER_CREATED_BYTES = + CanonicalPlayerCreatedRosterEvidence.MAX_SELECTED_RECEIPT_BYTES; + public static final int MAX_PLAYER_CREATED_RESPONSE_BYTES = 194 * 1024 * 1024; private CanonicalGameplayRosterReferenceEvidence() {} @@ -27,6 +41,7 @@ public static GetCanonicalGameplayRosterReferenceRequest request( UUID session, String namespace, CanonicalGameplayRosterTarget target) { + requirePreseeded(target); return requireRequest( GetCanonicalGameplayRosterReferenceRequest.newBuilder() .setSchemaVersion(1) @@ -38,6 +53,27 @@ public static GetCanonicalGameplayRosterReferenceRequest request( .build()); } + public static GetCanonicalGameplayRosterReferenceRequest playerCreatedRequest( + UUID operation, + UUID account, + UUID session, + String namespace, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source) { + requireCreated(target); + return requireRequest( + GetCanonicalGameplayRosterReferenceRequest.newBuilder() + .setSchemaVersion(1) + .setOperationUuid(operation.toString()) + .setCanonicalAccountUuid(account.toString()) + .setSessionUuid(session.toString()) + .setTargetNamespace(namespace) + .setCanonicalTarget(target.toByteString()) + .setCanonicalPlayerCreatedSourceIdentity( + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity(source).toByteString()) + .build()); + } + public static GetCanonicalGameplayRosterReferenceRequest requireRequest( GetCanonicalGameplayRosterReferenceRequest request) { Objects.requireNonNull(request, "request"); @@ -50,7 +86,13 @@ public static GetCanonicalGameplayRosterReferenceRequest requireRequest( uuid(request.getOperationUuid()); uuid(request.getCanonicalAccountUuid()); uuid(request.getSessionUuid()); - target(request); + var target = target(request); + if (isCreated(target)) { + playerCreatedSourceIdentity(request); + } else if (!request.getCanonicalPlayerCreatedSourceIdentity().isEmpty()) { + throw new IllegalArgumentException( + "PRESEEDED_ONLY original cannot carry PLAYER_CREATED source identity"); + } return request; } @@ -66,8 +108,11 @@ public static CanonicalGameplayRosterTarget target( || target.getActiveWorldEpoch() <= 0 || (target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED && target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) - || target.getEntryPolicy() - != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY + || (target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY + && !isCreated(target)) + || (isCreated(target) + && target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) || !target.getWorldSlug().matches("[a-z0-9][a-z0-9-]{0,63}") || !target.getRealmSlug().matches("[a-z0-9][a-z0-9-]{0,63}") || !target.getPublishedPolicyDigest().matches("[0-9a-f]{64}") @@ -97,6 +142,7 @@ public static GetCanonicalGameplayRosterReferenceResponse response( long fence, UUID targetFence, CanonicalGameplayRosterResponse receipt) { + requirePreseeded(target(requireRequest(request))); var response = GetCanonicalGameplayRosterReferenceResponse.newBuilder() .setRequest(requireRequest(request)) @@ -114,6 +160,173 @@ public static GetCanonicalGameplayRosterReferenceResponse response( return requireResponse(request, response.build()); } + public static GetCanonicalGameplayRosterReferenceResponse playerCreatedResponse( + GetCanonicalGameplayRosterReferenceRequest request, + long fence, + UUID targetFence, + CanonicalPlayerCreatedRosterResponse receipt) { + requireCreated(target(requireRequest(request))); + var response = + GetCanonicalGameplayRosterReferenceResponse.newBuilder() + .setRequest(request) + .setOwnerFence(fence) + .setTargetFenceUuid(targetFence.toString()) + .setState( + receipt == null + ? CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RESERVED + : CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED); + if (receipt != null) response.setCanonicalPlayerCreatedRosterReceipt(receipt.toByteString()); + return requireResponse(request, response.build()); + } + + public static CanonicalPlayerCreatedRosterSourceIdentity playerCreatedSourceIdentity( + GetCanonicalGameplayRosterReferenceRequest request) { + requireCreated(target(request)); + try { + var bytes = request.getCanonicalPlayerCreatedSourceIdentity(); + if (bytes.isEmpty() + || bytes.size() > CanonicalPlayerCreatedRosterEvidence.MAX_SOURCE_IDENTITY_BYTES) { + throw new IllegalArgumentException( + "Complete canonical PLAYER_CREATED source identity required"); + } + var source = + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.parseFrom(bytes)); + if (!bytes.equals(source.toByteString())) { + throw new IllegalArgumentException( + "PLAYER_CREATED source identity bytes are not canonical"); + } + return source; + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("PLAYER_CREATED source identity is malformed", invalid); + } + } + + public static CanonicalPlayerCreatedRosterResponse playerCreatedReceipt( + GetCanonicalGameplayRosterReferenceResponse response) { + requireCreated(target(requireRequest(response.getRequest()))); + if (!response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalSelectedAssignmentReceipt().isEmpty()) { + throw new IllegalArgumentException("PLAYER_CREATED receipt cannot use PRESEEDED_ONLY fields"); + } + try { + var bytes = response.getCanonicalPlayerCreatedRosterReceipt(); + if (bytes.isEmpty() || bytes.size() > MAX_PLAYER_CREATED_RECEIPT_BYTES) { + throw new IllegalArgumentException( + "Complete bounded PLAYER_CREATED roster receipt required"); + } + var roster = CanonicalPlayerCreatedRosterResponse.parseFrom(bytes); + if (!bytes.equals(roster.toByteString())) { + throw new IllegalArgumentException("PLAYER_CREATED roster receipt bytes are not canonical"); + } + return CanonicalPlayerCreatedRosterEvidence.requireResponse( + createdRosterRequest(response.getRequest()), roster); + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("PLAYER_CREATED roster receipt is malformed", invalid); + } + } + + /** Exact validated generic snapshot projection; this does not authenticate its producer. */ + public static CanonicalGameplayRosterResponse snapshotReceipt( + GetCanonicalGameplayRosterReferenceResponse response) { + return isCreated(target(response.getRequest())) + ? playerCreatedReceipt(response).getRoster() + : receipt(response); + } + + public static CanonicalSelectedPlayerCreatedCharacterResponse + selectedPlayerCreatedCharacterReceipt(GetCanonicalGameplayRosterReferenceResponse response) { + var roster = playerCreatedReceipt(response).getRoster(); + try { + var bytes = response.getCanonicalSelectedPlayerCreatedCharacterReceipt(); + if (bytes.isEmpty() || bytes.size() > MAX_SELECTED_PLAYER_CREATED_BYTES) { + throw new IllegalArgumentException( + "Complete bounded selected PLAYER_CREATED terminal required"); + } + var selected = CanonicalSelectedPlayerCreatedCharacterResponse.parseFrom(bytes); + if (!bytes.equals(selected.toByteString())) { + throw new IllegalArgumentException( + "Selected PLAYER_CREATED receipt bytes are not canonical"); + } + var original = response.getRequest(); + var expected = + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(response.getSelectedCharacterUuid()) + .setExpectedTarget(target(original)) + .setExpectedSource(playerCreatedSourceIdentity(original)) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.getSnapshotUuid()) + .setSnapshotDigest(roster.getSnapshotDigest())) + .setPlayerExecutionContext( + comparisonContext(original).setCharacterId(response.getSelectedCharacterUuid())) + .build(); + var validated = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(expected, selected); + if (!validated + .getTerminal() + .getOriginalRequest() + .getOriginal() + .getTargetNamespace() + .equals(original.getTargetNamespace())) { + throw new IllegalArgumentException( + "Selected creation terminal changed original workload namespace"); + } + return validated; + } catch (InvalidProtocolBufferException invalid) { + throw new IllegalArgumentException("Selected PLAYER_CREATED terminal is malformed", invalid); + } + } + + private static CanonicalPlayerCreatedRosterRequest createdRosterRequest( + GetCanonicalGameplayRosterReferenceRequest original) { + return CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setExpectedTarget(target(original)) + .setExpectedSource(playerCreatedSourceIdentity(original)) + .setPlayerExecutionContext(comparisonContext(original)) + .build(); + } + + // Reconstruct comparison values only. This is never authenticated execution-context custody. + private static PlayerExecutionContext.Builder comparisonContext( + GetCanonicalGameplayRosterReferenceRequest original) { + var target = target(original); + return PlayerExecutionContext.newBuilder() + .setRequestId(original.getOperationUuid()) + .setAccountId(original.getCanonicalAccountUuid()) + .setSessionId(original.getSessionUuid()) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .setGameInstanceId(target.getGameInstanceUuid()); + } + + private static boolean isCreated(CanonicalGameplayRosterTarget target) { + return target.getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED; + } + + private static void requireCreated(CanonicalGameplayRosterTarget target) { + if (!isCreated(target) + || target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + throw new IllegalArgumentException("Distinct SHARED PLAYER_CREATED carrier required"); + } + } + + private static void requirePreseeded(CanonicalGameplayRosterTarget target) { + if (target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) { + throw new IllegalArgumentException("Distinct PRESEEDED_ONLY carrier required"); + } + } + public static net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput requireSelectionInput( net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput input) { @@ -137,9 +350,12 @@ public static GetCanonicalGameplayRosterReferenceResponse response( public static net.firedevops.firemud.entitymanagement.v1 .CanonicalGameplayRosterSelectedAssignmentResponse selectedAssignmentReceipt(GetCanonicalGameplayRosterReferenceResponse response) { + requirePreseeded(target(requireRequest(response.getRequest()))); + rejectCreatedFields(response); try { if (response.getCanonicalSelectedAssignmentReceipt().isEmpty() - || response.getCanonicalSelectedAssignmentReceipt().size() > 8192) { + || response.getCanonicalSelectedAssignmentReceipt().size() + > MAX_SELECTED_ASSIGNMENT_BYTES) { throw new IllegalArgumentException( "Complete original selected assignment receipt required"); } @@ -175,20 +391,40 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( GetCanonicalGameplayRosterReferenceResponse response) { requireRequest(expected); Objects.requireNonNull(response, "response"); - if (!response.getUnknownFields().asMap().isEmpty() + boolean created = isCreated(target(expected)); + if (created) { + if (!response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalSelectedAssignmentReceipt().isEmpty()) { + throw new IllegalArgumentException( + "PLAYER_CREATED original cannot carry PRESEEDED_ONLY receipts"); + } + } else { + rejectCreatedFields(response); + } + if (response.getSerializedSize() + > (created ? MAX_PLAYER_CREATED_RESPONSE_BYTES : MAX_RESPONSE_BYTES) + || response.getCanonicalPlayerCreatedRosterReceipt().size() + > MAX_PLAYER_CREATED_RECEIPT_BYTES + || response.getCanonicalSelectedPlayerCreatedCharacterReceipt().size() + > MAX_SELECTED_PLAYER_CREATED_BYTES + || !response.getUnknownFields().asMap().isEmpty() || !response.hasRequest() || !expected.equals(requireRequest(response.getRequest())) || response.getOwnerFence() <= 0 || response.getCanonicalRosterReceipt().size() > MAX_RECEIPT_BYTES) { throw new IllegalArgumentException("Original roster selection owner binding is invalid"); } + boolean hasRoster = + !response.getCanonicalRosterReceipt().isEmpty() + || !response.getCanonicalPlayerCreatedRosterReceipt().isEmpty(); + if (hasRoster) snapshotReceipt(response); switch (response.getState()) { case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RESERVED -> { - if (!response.getCanonicalRosterReceipt().isEmpty()) { + if (hasRoster) { throw new IllegalArgumentException("Reserved original selection cannot carry a receipt"); } } - case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED -> receipt(response); + case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED -> snapshotReceipt(response); case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_REPLAY_CLOSED -> { if (response.getTerminalOutcome().isEmpty()) { throw new IllegalArgumentException("Closed replay requires original terminal outcome"); @@ -222,7 +458,7 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( if (!response.getSelectedCharacterUuid().isEmpty()) { uuid(response.getSelectedCharacterUuid()); if (!response.hasSelectionInput() - || receipt(response).getActorsList().stream() + || snapshotReceipt(response).getActorsList().stream() .filter( actor -> actor.getCharacterUuid().equals(response.getSelectedCharacterUuid())) .count() @@ -231,18 +467,22 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( "Original chosen actor must occur once in its recorded roster"); } } - if (!response.getCanonicalSelectedAssignmentReceipt().isEmpty()) { + if (!response.getCanonicalSelectedAssignmentReceipt().isEmpty() + || !response.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty()) { if (response.getSelectedCharacterUuid().isEmpty()) { throw new IllegalArgumentException( "Original assignment receipt requires a frozen chosen actor"); } - selectedAssignmentReceipt(response); + if (created) selectedPlayerCreatedCharacterReceipt(response); + else selectedAssignmentReceipt(response); } return response; } public static CanonicalGameplayRosterResponse receipt( GetCanonicalGameplayRosterReferenceResponse response) { + requirePreseeded(target(requireRequest(response.getRequest()))); + rejectCreatedFields(response); try { ByteString bytes = response.getCanonicalRosterReceipt(); if (bytes.isEmpty() || bytes.size() > MAX_RECEIPT_BYTES) { @@ -280,6 +520,14 @@ public static CanonicalGameplayRosterResponse receipt( } } + private static void rejectCreatedFields(GetCanonicalGameplayRosterReferenceResponse response) { + if (!response.getCanonicalPlayerCreatedRosterReceipt().isEmpty() + || !response.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty()) { + throw new IllegalArgumentException( + "PRESEEDED_ONLY original cannot carry PLAYER_CREATED receipts"); + } + } + public static void requireDereference(GetCanonicalGameplayRosterReferenceResponse response) { requireResponse(response.getRequest(), response); if (!response.getRecoveryUuid().isEmpty() diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java index b5f3135e87..cf61b5fc0d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java @@ -5,6 +5,7 @@ import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; @@ -17,6 +18,10 @@ public final class CanonicalGameplayRosterRetirementEvidence { public static final int MAX_REQUEST_BYTES = 128 * 1024; public static final int MAX_RESPONSE_BYTES = 4096; + public static final int MAX_PLAYER_CREATED_REQUEST_BYTES = 195 * 1024 * 1024; + public static final int MAX_CONFIRMATION_BYTES = MAX_REQUEST_BYTES + MAX_RESPONSE_BYTES + 64; + public static final int MAX_PLAYER_CREATED_CONFIRMATION_BYTES = + MAX_PLAYER_CREATED_REQUEST_BYTES + MAX_RESPONSE_BYTES + 64; private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); @@ -27,7 +32,7 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck Objects.requireNonNull(request, "request"); if (request.getSchemaVersion() != 1 || !request.getUnknownFields().asMap().isEmpty() - || request.getSerializedSize() > MAX_REQUEST_BYTES + || request.getSerializedSize() > MAX_PLAYER_CREATED_REQUEST_BYTES || !request.hasOriginalSelection() || !request.hasObservedRetirement() || request.getMinimumRetentionMillis() <= 0) { @@ -36,6 +41,10 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck } GetCanonicalGameplayRosterReferenceRequest original = CanonicalGameplayRosterReferenceEvidence.requireRequest(request.getOriginalSelection()); + if (request.getSerializedSize() > acknowledgementLimit(original)) { + throw new IllegalArgumentException( + "Retirement acknowledgement exceeds its policy-specific bound"); + } GetCanonicalGameplayRosterReferenceResponse observed = request.getObservedRetirement(); if (!observed.hasRequest()) { throw new IllegalArgumentException("Complete observed retirement proof required"); @@ -49,7 +58,10 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck if (!original.getTargetNamespace().equals(observedRequest.getTargetNamespace()) || !original.getCanonicalAccountUuid().equals(observedRequest.getCanonicalAccountUuid()) - || !original.getCanonicalTarget().equals(observedRequest.getCanonicalTarget())) { + || !original.getCanonicalTarget().equals(observedRequest.getCanonicalTarget()) + || !original + .getCanonicalPlayerCreatedSourceIdentity() + .equals(observedRequest.getCanonicalPlayerCreatedSourceIdentity())) { throw new IllegalArgumentException("Retirement proof changed exact account or target fence"); } boolean sameOperation = original.getOperationUuid().equals(observedRequest.getOperationUuid()); @@ -67,7 +79,7 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck CanonicalGameplayRosterReferenceEvidence.uuid(request.getSnapshotUuid()); requireDigest(request.getSnapshotDigest()); CanonicalGameplayRosterResponse roster = - CanonicalGameplayRosterReferenceEvidence.receipt(observed); + CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(observed); if (!roster.getSnapshotUuid().equals(request.getSnapshotUuid()) || !roster.getSnapshotDigest().equals(request.getSnapshotDigest()) || !roster.getCanonicalAccountUuid().equals(original.getCanonicalAccountUuid()) @@ -81,7 +93,8 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck // the already validated sealed account/target fence above. } else if (!sameOperation || !original.equals(observedRequest) - || !observed.getCanonicalRosterReceipt().isEmpty()) { + || !observed.getCanonicalRosterReceipt().isEmpty() + || !observed.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { throw new IllegalArgumentException( "Unbound retirement acknowledgement requires its own original proof and no roster receipt"); } @@ -151,13 +164,20 @@ public static CanonicalGameplayRosterRetirementConfirmationRequest requireConfir Objects.requireNonNull(confirmation, "confirmation"); if (confirmation.getSchemaVersion() != 1 || !confirmation.getUnknownFields().asMap().isEmpty() - || confirmation.getSerializedSize() > MAX_REQUEST_BYTES + MAX_RESPONSE_BYTES + 64 + || confirmation.getSerializedSize() > MAX_PLAYER_CREATED_CONFIRMATION_BYTES || !confirmation.hasAcknowledgementRequest() || !confirmation.hasAcknowledgement()) { throw new IllegalArgumentException("Closed bounded roster-retirement confirmation required"); } requireAcknowledgementResponse( confirmation.getAcknowledgementRequest(), confirmation.getAcknowledgement()); + if (confirmation.getSerializedSize() + > acknowledgementLimit(confirmation.getAcknowledgementRequest().getOriginalSelection()) + + MAX_RESPONSE_BYTES + + 64) { + throw new IllegalArgumentException( + "Retirement confirmation exceeds its policy-specific bound"); + } return confirmation; } @@ -187,6 +207,13 @@ public static CanonicalGameplayRosterRetirementConfirmationResponse requireConfi return response; } + private static int acknowledgementLimit(GetCanonicalGameplayRosterReferenceRequest original) { + return CanonicalGameplayRosterReferenceEvidence.target(original).getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED + ? MAX_PLAYER_CREATED_REQUEST_BYTES + : MAX_REQUEST_BYTES; + } + private static UUID uuid(String value) { return CanonicalGameplayRosterReferenceEvidence.uuid(value); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidence.java new file mode 100644 index 0000000000..df9618303b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidence.java @@ -0,0 +1,552 @@ +package net.firedevops.firemud.common.world; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +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.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Pure validation and digest functions for the PLAYER_CREATED roster wire values. */ +public final class CanonicalPlayerCreatedRosterEvidence { + public static final int MAX_REQUEST_BYTES = 16 * 1024; + public static final int MAX_SOURCE_IDENTITY_BYTES = 4096; + public static final int MAX_ROSTER_RECEIPT_BYTES = 66 * 1024; + public static final int MAX_TERMINAL_BYTES = 192 * 1024 * 1024; + public static final int MAX_SELECTED_RECEIPT_BYTES = 193 * 1024 * 1024; + + private static final int MAX_ORIGINAL_REQUEST_BYTES = 16 * 1024; + private static final int MAX_ACCOUNT_ORIGINAL_RESPONSE_BYTES = 36 * 1024 * 1024; + private static final int MAX_SOURCE_READBACK_BYTES = 32 * 1024 * 1024; + private static final int MAX_ACCOUNT_PROTECTION_BYTES = 40 * 1024 * 1024; + private static final int MAX_GAME_SESSION_PROTECTION_BYTES = 48 * 1024 * 1024; + private static final int MAX_WORLD_PROTECTION_BYTES = 48 * 1024 * 1024; + + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern UUID_PATTERN = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SLUG = Pattern.compile("[a-z0-9][a-z0-9-]{0,63}"); + private static final String SNAPSHOT_DOMAIN = "firemud.entity.player-created-roster.v1"; + + private CanonicalPlayerCreatedRosterEvidence() {} + + public static CanonicalPlayerCreatedRosterSourceIdentity requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity source) { + Objects.requireNonNull(source, "source"); + if (source.getSerializedSize() > MAX_SOURCE_IDENTITY_BYTES + || !source.getUnknownFields().asMap().isEmpty() + || source.getSchemaVersion() != 1 + || !SHA256.matcher(source.getDescriptorDigest()).matches() + || !SHA256.matcher(source.getAuthoredBindingDigest()).matches()) { + throw new IllegalArgumentException("Closed bounded PLAYER_CREATED source identity required"); + } + uuid(source.getDescriptorUuid()); + uuid(source.getDescriptorRevisionUuid()); + uuid(source.getAuthoredBindingUuid()); + return source; + } + + public static CanonicalPlayerCreatedRosterRequest requireRequest( + CanonicalPlayerCreatedRosterRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasExpectedTarget() + || !request.hasPlayerExecutionContext() + || !request.hasExpectedSource()) { + throw new IllegalArgumentException("Closed bounded PLAYER_CREATED roster request required"); + } + uuid(request.getRequestUuid()); + uuid(request.getCanonicalAccountUuid()); + CanonicalGameplayRosterTarget target = requireTarget(request.getExpectedTarget()); + requireSourceIdentity(request.getExpectedSource()); + requireContext( + request.getPlayerExecutionContext(), + request.getRequestUuid(), + request.getCanonicalAccountUuid(), + target, + null); + return request; + } + + public static CanonicalPlayerCreatedRosterResponse requireResponse( + CanonicalPlayerCreatedRosterRequest expected, CanonicalPlayerCreatedRosterResponse response) { + requireRequest(expected); + Objects.requireNonNull(response, "response"); + if (response.getSerializedSize() > MAX_ROSTER_RECEIPT_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasRoster() + || !response.hasSourceIdentity()) { + throw new IllegalArgumentException("Complete bounded PLAYER_CREATED roster receipt required"); + } + CanonicalPlayerCreatedRosterSourceIdentity source = + requireSourceIdentity(response.getSourceIdentity()); + if (!expected.getExpectedSource().equals(source)) { + throw new IllegalArgumentException("PLAYER_CREATED roster source identity changed"); + } + CanonicalGameplayRosterResponse roster = response.getRoster(); + if (roster.getSerializedSize() > MAX_ROSTER_RECEIPT_BYTES + || !roster.getUnknownFields().asMap().isEmpty() + || !roster.getCanonicalAccountUuid().equals(expected.getCanonicalAccountUuid()) + || !roster.hasTarget() + || !roster.getTarget().equals(expected.getExpectedTarget()) + || !DIGEST.matcher(roster.getSnapshotDigest()).matches() + || roster.getActorsCount() > 100) { + throw new IllegalArgumentException("PLAYER_CREATED roster binding or bounds are invalid"); + } + uuid(roster.getSnapshotUuid()); + Set actors = new HashSet<>(); + for (CanonicalGameplayRosterActor actor : roster.getActorsList()) { + if (!actor.getUnknownFields().asMap().isEmpty() + || !actors.add(uuid(actor.getCharacterUuid())) + || actor.getActorKind() + != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER + || !validDisplayName(actor.getDisplayName())) { + throw new IllegalArgumentException("Closed unique PLAYER actor roster required"); + } + } + String recomputed = + computeSnapshotDigest( + expected.getCanonicalAccountUuid(), + expected.getExpectedTarget(), + source, + roster.getActorsList()); + if (!recomputed.equals(roster.getSnapshotDigest())) { + throw new IllegalArgumentException("PLAYER_CREATED roster snapshot digest changed"); + } + return response; + } + + public static CanonicalSelectedPlayerCreatedCharacterRequest requireSelectedRequest( + CanonicalSelectedPlayerCreatedCharacterRequest request) { + Objects.requireNonNull(request, "request"); + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || !request.hasExpectedTarget() + || !request.hasExpectedSnapshot() + || !request.hasPlayerExecutionContext() + || !request.hasExpectedSource()) { + throw new IllegalArgumentException("Closed bounded selected PLAYER_CREATED request required"); + } + uuid(request.getRequestUuid()); + uuid(request.getCanonicalAccountUuid()); + UUID selected = uuid(request.getSelectedCharacterUuid()); + CanonicalGameplayRosterTarget target = requireTarget(request.getExpectedTarget()); + requireSourceIdentity(request.getExpectedSource()); + if (!request.getExpectedSnapshot().getUnknownFields().asMap().isEmpty() + || !DIGEST.matcher(request.getExpectedSnapshot().getSnapshotDigest()).matches()) { + throw new IllegalArgumentException("Exact canonical roster snapshot reference required"); + } + uuid(request.getExpectedSnapshot().getSnapshotUuid()); + requireContext( + request.getPlayerExecutionContext(), + request.getRequestUuid(), + request.getCanonicalAccountUuid(), + target, + selected); + return request; + } + + /** + * Validates pure selected-created wire values and bindings; this does not authenticate owners or + * establish creation authority. + */ + public static CanonicalSelectedPlayerCreatedCharacterResponse requireSelectedResponse( + CanonicalSelectedPlayerCreatedCharacterRequest expected, + CanonicalSelectedPlayerCreatedCharacterResponse response) { + requireSelectedRequest(expected); + Objects.requireNonNull(response, "response"); + if (response.getSerializedSize() > MAX_SELECTED_RECEIPT_BYTES + || !response.getUnknownFields().asMap().isEmpty() + || !response.hasTarget() + || !response.hasSnapshot() + || !response.hasSourceIdentity() + || !response.hasTerminal() + || !response.getRequestUuid().equals(expected.getRequestUuid()) + || !response.getCanonicalAccountUuid().equals(expected.getCanonicalAccountUuid()) + || !response.getSelectedCharacterUuid().equals(expected.getSelectedCharacterUuid())) { + throw new IllegalArgumentException( + "Complete bounded selected PLAYER_CREATED receipt required"); + } + CanonicalGameplayRosterTarget target = requireTarget(response.getTarget()); + CanonicalPlayerCreatedRosterSourceIdentity source = + requireSourceIdentity(response.getSourceIdentity()); + CanonicalGameplayRosterSnapshotReference snapshot = response.getSnapshot(); + if (!target.equals(expected.getExpectedTarget()) + || !snapshot.equals(expected.getExpectedSnapshot()) + || !source.equals(expected.getExpectedSource())) { + throw new IllegalArgumentException("Selected PLAYER_CREATED receipt binding changed"); + } + + uuid(response.getCreationOperationUuid()); + if (!DIGEST.matcher(response.getMutationDigest()).matches()) { + throw new IllegalArgumentException("Canonical selected creation mutation digest required"); + } + + EntityCharacterCreateTerminal terminal = response.getTerminal(); + if (terminal.getSerializedSize() > MAX_TERMINAL_BYTES + || !terminal.getUnknownFields().asMap().isEmpty() + || !terminal.hasOriginalRequest() + || !terminal.hasAccountOriginal() + || terminal.getOriginalAccountProtection().isEmpty() + || terminal.getOriginalAccountProtection().size() > MAX_ACCOUNT_PROTECTION_BYTES + || terminal.getOriginalGameSessionProtection().isEmpty() + || terminal.getOriginalGameSessionProtection().size() > MAX_GAME_SESSION_PROTECTION_BYTES + || terminal.getOriginalWorldProtection().isEmpty() + || terminal.getOriginalWorldProtection().size() > MAX_WORLD_PROTECTION_BYTES + || terminal.getOutcome() + != EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED + || !terminal.getCharacterId().equals(expected.getSelectedCharacterUuid()) + || terminal.getTerminalFence() != 1L + || !terminal.getAbortRequestId().isEmpty()) { + throw new IllegalArgumentException("Complete committed selected creation terminal required"); + } + uuid(terminal.getTerminalId()); + canonicalInstant(terminal.getCompletedAt()); + uuid(terminal.getEntityIntakeRequestId()); + if (!SHA256.matcher(terminal.getEntitySourceReceiptDigest()).matches()) { + throw new IllegalArgumentException("Canonical Entity source receipt digest required"); + } + requireOriginalCommit(terminal.getOriginalRequest()); + ReadOriginalCharacterCreateResponse accountOriginal = terminal.getAccountOriginal(); + requireAccountOriginal( + accountOriginal, + terminal.getOriginalRequest().getOriginal(), + expected.getCanonicalAccountUuid(), + response.getCreationOperationUuid(), + response.getMutationDigest()); + + byte[] originalActionBytes = accountOriginal.getOriginalAction().toByteArray(); + CharacterCreateOperatorAction action = + CharacterCreateOperatorActionCodec.decode(originalActionBytes); + if (!Arrays.equals(originalActionBytes, CharacterCreateOperatorActionCodec.encode(action)) + || !response + .getMutationDigest() + .equals(CharacterCreateOperatorActionCodec.mutationDigest(action)) + || !action + .scope() + .targetNamespace() + .equals(terminal.getOriginalRequest().getOriginal().getTargetNamespace())) { + throw new IllegalArgumentException("Original CHARACTER_CREATE action is not canonical"); + } + requireCreatedActionBinding(action, target, source, expected.getCanonicalAccountUuid()); + return response; + } + + private static void requireOriginalCommit(CommitProtectedCharacterCreateRequest request) { + if (!request.getUnknownFields().asMap().isEmpty() + || request.getSerializedSize() > MAX_ORIGINAL_REQUEST_BYTES + || !request.hasOriginal() + || !request.hasAccountProtection() + || !request.hasGameSessionProtection() + || !request.hasWorldProtection()) { + throw new IllegalArgumentException("Complete bounded original creation references required"); + } + var original = request.getOriginal(); + if (!original.getUnknownFields().asMap().isEmpty() + || original.getSerializedSize() > MAX_ORIGINAL_REQUEST_BYTES + || !net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace( + original.getTargetNamespace())) { + throw new IllegalArgumentException("Canonical original creation request required"); + } + uuid(original.getOperationId()); + if (!DIGEST.matcher(original.getMutationDigest()).matches()) { + throw new IllegalArgumentException("Canonical original creation digest required"); + } + requireProtectionReference(request.getAccountProtection()); + requireProtectionReference(request.getGameSessionProtection()); + requireProtectionReference(request.getWorldProtection()); + } + + private static void requireProtectionReference(CharacterCreateProtectionReference reference) { + if (!reference.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Closed original creation protection reference required"); + } + uuid(reference.getProtectionId()); + if (reference.getProtectionFence() <= 0L) { + throw new IllegalArgumentException("Positive original creation protection fence required"); + } + } + + private static void requireAccountOriginal( + ReadOriginalCharacterCreateResponse original, + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest request, + String expectedAccount, + String expectedOperation, + String expectedDigest) { + if (!original.getUnknownFields().asMap().isEmpty() + || original.getSerializedSize() > MAX_ACCOUNT_ORIGINAL_RESPONSE_BYTES + || original.getOriginalAction().isEmpty() + || original.getOriginalAction().size() > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + || original.getOriginalSourceReadback().isEmpty() + || original.getOriginalSourceReadback().size() > MAX_SOURCE_READBACK_BYTES + || !original.getTargetNamespace().equals(request.getTargetNamespace()) + || !original.getOperationId().equals(expectedOperation) + || !original.getMutationDigest().equals(expectedDigest) + || !"CHARACTER_CREATE".equals(original.getPurpose()) + || !original.getAuthenticatedAccountId().equals(expectedAccount)) { + throw new IllegalArgumentException("Exact bounded Account creation source required"); + } + uuid(original.getCreateCharacterRequestId()); + requireConnectScope(original.getConnectScopeId()); + if (!request.getOperationId().equals(original.getOperationId()) + || !request.getMutationDigest().equals(original.getMutationDigest())) { + throw new IllegalArgumentException("Account source differs from original request identity"); + } + } + + private static void requireConnectScope(String value) { + if (value.isBlank() + || value.length() > 2048 + || value.indexOf(0) >= 0 + || !StandardCharsets.UTF_8.newEncoder().canEncode(value)) { + throw new IllegalArgumentException("Bounded original creation connect scope required"); + } + } + + private static void requireCreatedActionBinding( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + String accountUuid) { + var scope = action.scope(); + var actionTarget = action.target(); + var mutation = action.mutation(); + var catalog = mutation.catalog(); + var authored = mutation.authoredSource(); + if (!scope.tenantId().equals(target.getTenantUuid()) + || !scope.playableStateNamespaceId().equals(target.getPlayableStateNamespaceUuid()) + || scope.playableStateScope() + != CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || !actionTarget.accountId().equals(accountUuid) + || !actionTarget.realmId().equals(target.getRealmUuid()) + || !actionTarget.worldSlug().equals(target.getWorldSlug()) + || !actionTarget.realmSlug().equals(target.getRealmSlug()) + || !actionTarget.versionId().equals(target.getCanonicalVersionUuid()) + || !authored.canonicalTenantId().equals(target.getTenantUuid()) + || !authored.canonicalVersionId().equals(target.getCanonicalVersionUuid()) + || !authored.worldSlug().equals(target.getWorldSlug()) + || !catalog.tenantId().equals(target.getTenantUuid()) + || !catalog.realmId().equals(target.getRealmUuid()) + || !catalog.worldSlug().equals(target.getWorldSlug()) + || !catalog.realmSlug().equals(target.getRealmSlug()) + || !catalog.playableStateNamespaceId().equals(target.getPlayableStateNamespaceUuid()) + || !"SHARED".equals(catalog.stateScope()) + || !"PLAYER_CREATED".equals(catalog.characterCreationPolicy()) + || !authored.bindingId().equals(source.getAuthoredBindingUuid()) + || !authored.bindingDigest().equals(source.getAuthoredBindingDigest())) { + throw new IllegalArgumentException( + "Original creation durable target or authored binding changed"); + } + PlayerCreationDescriptor descriptor = + PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); + if (!descriptor.descriptorId().equals(source.getDescriptorUuid()) + || !descriptor.descriptorRevisionId().equals(source.getDescriptorRevisionUuid()) + || !descriptor.digest().equals(source.getDescriptorDigest()) + || !authored.descriptor().digest().equals(source.getDescriptorDigest())) { + throw new IllegalArgumentException("Original creation descriptor identity changed"); + } + } + + private static void canonicalInstant(String value) { + try { + if (!java.time.Instant.parse(value).toString().equals(value)) { + throw new IllegalArgumentException("Canonical creation terminal timestamp required"); + } + } catch (java.time.DateTimeException malformed) { + throw new IllegalArgumentException( + "Canonical creation terminal timestamp required", malformed); + } + } + + public static String computeSnapshotDigest( + String account, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + List orderedActors) { + uuid(account); + CanonicalGameplayRosterTarget canonicalTarget = requireTarget(target); + CanonicalPlayerCreatedRosterSourceIdentity canonicalSource = requireSourceIdentity(source); + Objects.requireNonNull(orderedActors, "orderedActors"); + if (orderedActors.size() > 100) { + throw new IllegalArgumentException("PLAYER_CREATED roster exceeds 100 actors"); + } + Set actors = new HashSet<>(); + for (CanonicalGameplayRosterActor actor : orderedActors) { + Objects.requireNonNull(actor, "actor"); + if (!actor.getUnknownFields().asMap().isEmpty() + || !actors.add(uuid(actor.getCharacterUuid())) + || actor.getActorKind() + != CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER + || !validDisplayName(actor.getDisplayName())) { + throw new IllegalArgumentException("Closed unique PLAYER actor roster required"); + } + } + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream output = new DataOutputStream(bytes); + writeUtf8(output, SNAPSHOT_DOMAIN); + writeUtf8(output, account); + writeBytes(output, canonicalTarget.toByteArray()); + writeBytes(output, canonicalSource.toByteArray()); + output.writeInt(orderedActors.size()); + for (CanonicalGameplayRosterActor actor : orderedActors) { + writeUtf8(output, actor.getCharacterUuid()); + writeUtf8(output, actor.getDisplayName()); + } + output.flush(); + return java.util.HexFormat.of().formatHex(sha256(bytes.toByteArray())); + } catch (IOException impossible) { + throw new IllegalStateException("In-memory roster digest encoding failed", impossible); + } + } + + private static CanonicalGameplayRosterTarget requireTarget(CanonicalGameplayRosterTarget target) { + Objects.requireNonNull(target, "target"); + if (!target.getUnknownFields().asMap().isEmpty() + || target.getCatalogRevision() <= 0 + || target.getPointerVersion() <= 0 + || target.getActiveWorldEpoch() <= 0 + || target.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || target.getEntryPolicy() + != CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED + || !SLUG.matcher(target.getWorldSlug()).matches() + || !SLUG.matcher(target.getRealmSlug()).matches() + || !DIGEST.matcher(target.getPublishedPolicyDigest()).matches() + || !DIGEST.matcher(target.getAdmissionPointerSnapshotDigest()).matches() + || !DIGEST.matcher(target.getPublishedOwnerProofDigest()).matches() + || target.getPublishedReleaseBundleRef().isBlank() + || target.getPublishedReleaseBundleRef().length() > 1024 + || !target + .getPublishedReleaseBundleRef() + .equals(target.getPublishedReleaseBundleRef().trim()) + || target.getPublishedReleaseBundleRef().codePoints().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException("Complete SHARED PLAYER_CREATED target required"); + } + uuid(target.getTenantUuid()); + uuid(target.getRealmUuid()); + uuid(target.getGameInstanceUuid()); + uuid(target.getCanonicalVersionUuid()); + uuid(target.getPlayableStateNamespaceUuid()); + return target; + } + + private static void requireContext( + PlayerExecutionContext context, + String requestUuid, + String accountUuid, + CanonicalGameplayRosterTarget target, + UUID selectedCharacter) { + if (!context.getUnknownFields().asMap().isEmpty() + || !context.getAccountId().equals(accountUuid) + || !context.getRequestId().equals(requestUuid) + || !context.getTenantId().equals(target.getTenantUuid()) + || !context.getRealmId().equals(target.getRealmUuid()) + || !context.getPlayableStateNamespaceId().equals(target.getPlayableStateNamespaceUuid()) + || !context.getGameInstanceId().equals(target.getGameInstanceUuid()) + || !context.getPlayableStateScope().equals("SHARED") + || (selectedCharacter == null && !context.getCharacterId().isEmpty()) + || (selectedCharacter != null + && !context.getCharacterId().equals(selectedCharacter.toString()))) { + throw new IllegalArgumentException( + "Player execution context does not match exact request target"); + } + uuid(context.getAccountId()); + uuid(context.getRequestId()); + uuid(context.getTenantId()); + uuid(context.getRealmId()); + uuid(context.getPlayableStateNamespaceId()); + uuid(context.getGameInstanceId()); + uuid(context.getSessionId()); + if (selectedCharacter != null) uuid(context.getCharacterId()); + } + + private static UUID uuid(String value) { + Objects.requireNonNull(value, "uuid"); + if (!UUID_PATTERN.matcher(value).matches()) { + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + UUID parsed = UUID.fromString(value); + if (parsed.equals(NIL_UUID) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException("Canonical non-nil UUID required"); + } + return parsed; + } + + private static boolean validDisplayName(String value) { + if (value.isBlank() + || !value.equals(value.trim()) + || value.codePointCount(0, value.length()) > 100 + || value.codePoints().anyMatch(Character::isISOControl)) { + return false; + } + try { + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(value)); + return true; + } catch (CharacterCodingException malformed) { + return false; + } + } + + private static void writeUtf8(DataOutputStream output, String value) throws IOException { + ByteBuffer encoded = + StandardCharsets.UTF_8 + .newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(java.nio.CharBuffer.wrap(value)); + byte[] bytes = new byte[encoded.remaining()]; + encoded.get(bytes); + writeBytes(output, bytes); + } + + private static void writeBytes(DataOutputStream output, byte[] bytes) throws IOException { + output.writeInt(bytes.length); + output.write(bytes); + } + + private static byte[] sha256(byte[] input) { + try { + return MessageDigest.getInstance("SHA-256").digest(input); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java new file mode 100644 index 0000000000..58eebb2e5b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.common.world; + +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.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import org.junit.jupiter.api.Test; + +/** Pure carrier integrity; these comparison values are not authenticated recovery evidence. */ +class CanonicalGameplayRosterRecoveryEvidenceTest { + @Test + void createdRecoveryReturnsOnlyItsDistinctRosterAndKeepsExactOwnerFenceAndMarker() + throws Exception { + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var request = request(fixture.original()); + var response = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), fixture.roster()); + assertThat(response.getCanonicalRosterReceipt()).isEmpty(); + assertThat(response.getCanonicalPlayerCreatedRosterReceipt()) + .isEqualTo(fixture.roster().toByteString()); + assertThat( + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, CanonicalGameplayRosterRecoveryResponse.parseFrom(response.toByteArray()))) + .isEqualTo(response); + var owner = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), + response.getOwnerFence(), + UUID.fromString(response.getTargetFenceUuid()), + fixture.roster()) + .toBuilder() + .setRecoveryUuid(request.getRecoveryUuid()) + .build(); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireOwnerRecovery(request, owner)) + .isEqualTo(owner); + assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.requireDereference(owner)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.response( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + var noCapture = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), null); + assertThat(noCapture.getCanonicalPlayerCreatedRosterReceipt()).isEmpty(); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireResponse(request, noCapture)) + .isEqualTo(noCapture); + for (var changed : + List.of( + response.toBuilder() + .setCanonicalRosterReceipt(fixture.roster().getRoster().toByteString()) + .build(), + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + fixture.roster().toBuilder() + .setSourceIdentity( + fixture.roster().getSourceIdentity().toBuilder() + .setAuthoredBindingUuid(UUID.randomUUID().toString())) + .build() + .toByteString()) + .build(), + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + fixture.roster().toBuilder() + .setRoster( + fixture.roster().getRoster().toBuilder() + .setCanonicalAccountUuid(UUID.randomUUID().toString())) + .build() + .toByteString()) + .build(), + response.toBuilder() + .setRequest(request.toBuilder().setRecoveryUuid(UUID.randomUUID().toString())) + .build())) { + assertThatThrownBy( + () -> CanonicalGameplayRosterRecoveryEvidence.requireResponse(request, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void recoveryBudgetsStayEightAnd128KiBWithClosedPolicySpecificReceiptFields() { + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var request = request(fixture.original()); + var response = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), null); + assertThat(CanonicalGameplayRosterRecoveryEvidence.MAX_REQUEST_BYTES).isEqualTo(8192); + assertThat(CanonicalGameplayRosterRecoveryEvidence.MAX_RESPONSE_BYTES).isEqualTo(128 * 1024); + int maximumRosterEnvelope = 66 * 1024 + 4096 + 256; + assertThat(maximumRosterEnvelope) + .isLessThanOrEqualTo(CanonicalGameplayRosterRecoveryEvidence.MAX_RESPONSE_BYTES); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( + 66 * 1024 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( + 128 * 1024 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class); + var oldTarget = + CanonicalGameplayRosterReferenceEvidence.target(fixture.original()).toBuilder() + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + var old = + CanonicalGameplayRosterReferenceEvidence.request( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "gameplay", oldTarget); + var oldRequest = request(old); + var oldReceipt = + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(old.getCanonicalAccountUuid()) + .setTarget(oldTarget) + .setSnapshotUuid(UUID.randomUUID().toString()) + .setSnapshotDigest("d".repeat(64)) + .build(); + var oldResponse = + CanonicalGameplayRosterRecoveryEvidence.response( + oldRequest, UUID.randomUUID(), 1L, UUID.randomUUID(), oldReceipt); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireResponse(oldRequest, oldResponse)) + .isEqualTo(oldResponse); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + oldRequest, + oldResponse.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + oldRequest, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static CanonicalGameplayRosterRecoveryRequest request( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original) { + return CanonicalGameplayRosterRecoveryRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(original) + .setRecoveryUuid(UUID.randomUUID().toString()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java index e3ec61c2f5..e975c759d8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java @@ -3,13 +3,22 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.UnknownFieldSet; +import java.util.List; import java.util.UUID; +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.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; import org.junit.jupiter.api.Test; class CanonicalGameplayRosterReferenceEvidenceTest { @@ -232,6 +241,354 @@ void closedRecoveryEchoAndOptionalOriginalReceiptNeverPermitSubstitution() { } } + @Test + void createdMenuAndSelectedReplayRetainTheDistinctCompleteOriginalCreationReceipt() + throws Exception { + var fixture = createdFixture(); + var original = fixture.original(); + var menu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 1L, UUID.randomUUID(), fixture.roster()); + assertThat(CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(menu)) + .isEqualTo(fixture.roster()); + assertThat(CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(menu)) + .isEqualTo(fixture.roster().getRoster()); + var selected = selectedOriginal(fixture, menu); + assertThat(CanonicalGameplayRosterReferenceEvidence.requireResponse(original, selected)) + .isEqualTo(selected); + var replay = GetCanonicalGameplayRosterReferenceResponse.parseFrom(selected.toByteArray()); + assertThat(CanonicalGameplayRosterReferenceEvidence.requireResponse(original, replay)) + .isEqualTo(selected); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt(replay)) + .isEqualTo(fixture.selected()); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt(replay) + .getTerminal()) + .isEqualTo(fixture.selected().getTerminal()); + assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.receipt(menu)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt(selected)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.response( + original, 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.request( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "gameplay", + fixture.roster().getRoster().getTarget())) + .isInstanceOf(IllegalArgumentException.class); + var foreignOriginal = original.toBuilder().setTargetNamespace("other").build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + foreignOriginal, selected.toBuilder().setRequest(foreignOriginal).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("workload namespace"); + for (var changed : + List.of( + selected.toBuilder().setSelectedCharacterUuid(UUID.randomUUID().toString()).build(), + selected.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toBuilder() + .setRequestUuid(UUID.randomUUID().toString()) + .build() + .toByteString()) + .build(), + selected.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toBuilder() + .setCanonicalAccountUuid(UUID.randomUUID().toString()) + .build() + .toByteString()) + .build(), + selected.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toBuilder() + .setSourceIdentity( + fixture.selected().getSourceIdentity().toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString())) + .build() + .toByteString()) + .build())) { + assertThatThrownBy( + () -> CanonicalGameplayRosterReferenceEvidence.requireResponse(original, changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void createdSourceBytesAndPolicyBranchesAreClosedAndMutuallyExclusive() { + var fixture = createdFixture(); + var created = fixture.original(); + var source = CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity(created); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + for (var changed : + List.of( + created.toBuilder().clearCanonicalPlayerCreatedSourceIdentity().build(), + created.toBuilder() + .setCanonicalPlayerCreatedSourceIdentity( + source.toBuilder().setUnknownFields(unknown).build().toByteString()) + .build(), + created.toBuilder() + .setCanonicalPlayerCreatedSourceIdentity( + source.toByteString().concat(ByteString.copyFrom(new byte[] {8, 1}))) + .build(), + created.toBuilder() + .setCanonicalTarget( + CanonicalGameplayRosterReferenceEvidence.target(created).toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) + .build() + .toByteString()) + .build(), + created.toBuilder() + .setCanonicalTarget( + CanonicalGameplayRosterReferenceEvidence.target(created).toBuilder() + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_AUTO_PROVISIONED) + .build() + .toByteString()) + .build(), + request().toBuilder() + .setCanonicalPlayerCreatedSourceIdentity(source.toByteString()) + .build())) { + assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.requireRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + var createdMenu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + created, 1L, UUID.randomUUID(), fixture.roster()); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + created, + createdMenu.toBuilder() + .setCanonicalRosterReceipt(fixture.roster().getRoster().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + var preseeded = request(); + var reserved = + CanonicalGameplayRosterReferenceEvidence.response(preseeded, 1L, UUID.randomUUID(), null); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toByteString()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + preseeded, 1L, UUID.randomUUID(), null)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void largestCreatedSelectorsAndUnicodeReleaseFitUnchangedOriginalAndRecoveryRequestBudgets() { + var fixture = createdFixture(); + var target = + CanonicalGameplayRosterReferenceEvidence.target(fixture.original()).toBuilder() + .setWorldSlug("a".repeat(64)) + .setRealmSlug("b".repeat(64)) + .setCatalogRevision(Long.MAX_VALUE) + .setPointerVersion(Long.MAX_VALUE) + .setActiveWorldEpoch(Long.MAX_VALUE) + .setPublishedReleaseBundleRef("\u0800".repeat(1024)) + .build(); + var largest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(63), + target, + CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity( + fixture.original())); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_REQUEST_BYTES).isEqualTo(4096); + assertThat( + target.getPublishedReleaseBundleRef().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .hasSize(3072); + assertThat(largest.getSerializedSize()) + .isEqualTo(4081) + .isLessThanOrEqualTo(CanonicalGameplayRosterReferenceEvidence.MAX_REQUEST_BYTES); + var recovery = + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest + .newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(largest) + .setRecoveryUuid(UUID.randomUUID().toString()) + .build(); + assertThat(CanonicalGameplayRosterRecoveryEvidence.requireRequest(recovery).getSerializedSize()) + .isEqualTo(4124) + .isLessThanOrEqualTo(CanonicalGameplayRosterRecoveryEvidence.MAX_REQUEST_BYTES); + } + + @Test + void createdPurposeBudgetsRetainTheFullTerminalAndRejectOversizeWithoutHugeBackingArrays() { + var fixture = createdFixture(); + var menu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), 1L, UUID.randomUUID(), fixture.roster()); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_RECEIPT_BYTES).isEqualTo(64 * 1024); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_ASSIGNMENT_BYTES) + .isEqualTo(8192); + assertThat(CanonicalPlayerCreatedRosterEvidence.MAX_TERMINAL_BYTES) + .isEqualTo(192 * 1024 * 1024); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES) + .isEqualTo(193 * 1024 * 1024); + assertThat(CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES) + .isEqualTo(194 * 1024 * 1024); + var preseeded = request(); + var reserved = + CanonicalGameplayRosterReferenceEvidence.response(preseeded, 1L, UUID.randomUUID(), null); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalRosterReceipt(logicalBytes(64 * 1024 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt( + reserved.toBuilder() + .setCanonicalSelectedAssignmentReceipt(logicalBytes(8192 + 1)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + int completeSelectedEnvelope = + CodedOutputStream.computeTagSize(18) + + CodedOutputStream.computeUInt32SizeNoTag( + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES) + + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES; + // A full 193 MiB selected envelope, 66 KiB menu, maximal original and bounded input/metadata + // fit the original-response purpose without constructing a gratuitous 192 MiB terminal. + assertThat(completeSelectedEnvelope + 66 * 1024 + 4096 + 2048) + .isLessThanOrEqualTo( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES); + for (var changed : + List.of( + menu.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RECEIPT_BYTES + + 1)) + .build(), + menu.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES + + 1)) + .build(), + menu.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES + + 1)) + .build())) { + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.original(), changed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + + // Rope ByteStrings share their tiny backing payload; over-budget tests reject before parsing. + static ByteString logicalBytes(int size) { + ByteString bytes = ByteString.copyFrom(new byte[1024]); + while (bytes.size() < size) bytes = bytes.concat(bytes); + return bytes.substring(0, size); + } + + record CreatedFixture( + GetCanonicalGameplayRosterReferenceRequest original, + CanonicalPlayerCreatedRosterResponse roster, + CanonicalSelectedPlayerCreatedCharacterResponse selected) {} + + static CreatedFixture createdFixture() { + var selected = CanonicalPlayerCreatedRosterEvidenceTest.selectedFixture(); + var request = selected.request(); + var actors = + List.of( + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(request.getSelectedCharacterUuid()) + .setDisplayName("Persisted created actor") + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()); + var digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), + request.getExpectedTarget(), + request.getExpectedSource(), + actors); + var snapshot = + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(request.getExpectedSnapshot().getSnapshotUuid()) + .setSnapshotDigest(digest) + .build(); + var roster = + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(request.getExpectedSource()) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(snapshot.getSnapshotUuid()) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .build(); + var original = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), + selected + .response() + .getTerminal() + .getOriginalRequest() + .getOriginal() + .getTargetNamespace(), + request.getExpectedTarget(), + request.getExpectedSource()); + return new CreatedFixture( + original, roster, selected.response().toBuilder().setSnapshot(snapshot).build()); + } + + static GetCanonicalGameplayRosterReferenceResponse selectedOriginal( + CreatedFixture fixture, GetCanonicalGameplayRosterReferenceResponse menu) { + return menu.toBuilder() + .setSelectionInput( + net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("1")) + .setSelectedCharacterUuid(fixture.selected().getSelectedCharacterUuid()) + .setCanonicalSelectedPlayerCreatedCharacterReceipt(fixture.selected().toByteString()) + .setTerminalOutcome("SELECTED") + .build(); + } + private static GetCanonicalGameplayRosterReferenceRequest request() { var target = CanonicalGameplayRosterTarget.newBuilder() diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java index b7f12db50a..195b5693f6 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java @@ -189,6 +189,144 @@ void acknowledgementAndConfirmationBindExactRequestHashesAndHorizons() throws Ex .build())); } + @Test + void createdRetirementCarriesTheCompleteSelectedTerminalAndBindsCrossOriginalSourceIdentity() { + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var original = fixture.original(); + var menu = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 17L, TARGET_FENCE, fixture.roster()); + var selected = CanonicalGameplayRosterReferenceEvidenceTest.selectedOriginal(fixture, menu); + var target = CanonicalGameplayRosterReferenceEvidence.target(original); + var proof = createdRetirement(selected); + var roster = fixture.roster().getRoster(); + var request = + acknowledgement(original, proof, roster.getSnapshotUuid(), roster.getSnapshotDigest()); + assertEquals( + request, CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(request)); + assertEquals( + fixture.selected().toByteString(), + request.getObservedRetirement().getCanonicalSelectedPlayerCreatedCharacterReceipt()); + var ack = CanonicalGameplayRosterRetirementEvidence.response(request, uuid(12), 20_000L); + var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation(request, ack); + assertEquals( + confirmation, CanonicalGameplayRosterRetirementEvidence.requireConfirmation(confirmation)); + var otherOriginal = + original.toBuilder() + .setOperationUuid(uuid(80).toString()) + .setSessionUuid(uuid(81).toString()) + .build(); + var anchored = + acknowledgement(otherOriginal, proof, roster.getSnapshotUuid(), roster.getSnapshotDigest()); + assertEquals( + anchored, CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(anchored)); + var changedSource = + CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity(otherOriginal) + .toBuilder() + .setAuthoredBindingUuid(uuid(82).toString()) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + anchored.toBuilder() + .setOriginalSelection( + otherOriginal.toBuilder() + .setCanonicalPlayerCreatedSourceIdentity(changedSource.toByteString())) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + anchored.toBuilder().clearSnapshotUuid().clearSnapshotDigest().build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + request.toBuilder().setSnapshotDigest("0".repeat(64)).build())); + var unboundProof = + createdRetirement( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 17L, TARGET_FENCE, null) + .toBuilder() + .setTerminalOutcome("DENIED") + .build()); + var unbound = acknowledgement(original, unboundProof, "", ""); + assertEquals( + unbound, CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(unbound)); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + acknowledgement(otherOriginal, unboundProof, "", ""))); + assertEquals( + target, + CanonicalGameplayRosterReferenceEvidence.target( + anchored.getObservedRetirement().getRequest())); + } + + @Test + void acknowledgementPurposeBoundsKeepOldCapsAndFitCompleteCreatedOriginalWithoutHugeArrays() { + assertEquals(128 * 1024, CanonicalGameplayRosterRetirementEvidence.MAX_REQUEST_BYTES); + assertEquals(4096, CanonicalGameplayRosterRetirementEvidence.MAX_RESPONSE_BYTES); + assertEquals( + 195 * 1024 * 1024, + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES); + assertEquals( + CanonicalGameplayRosterRetirementEvidence.MAX_REQUEST_BYTES + 4096 + 64, + CanonicalGameplayRosterRetirementEvidence.MAX_CONFIRMATION_BYTES); + assertEquals( + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES + 4096 + 64, + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + int original = CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES; + int encodedOriginal = + com.google.protobuf.CodedOutputStream.computeTagSize(3) + + com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(original) + + original; + assertTrue( + encodedOriginal + 4096 + 512 + <= CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES); + var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); + var request = + acknowledgement( + fixture.original(), + createdRetirement( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), 17L, TARGET_FENCE, fixture.roster())), + fixture.roster().getRoster().getSnapshotUuid(), + fixture.roster().getRoster().getSnapshotDigest()); + var oversized = + request.toBuilder() + .setObservedRetirement( + request.getObservedRetirement().toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_REQUEST_BYTES + + 1))) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(oversized)); + } + + private static GetCanonicalGameplayRosterReferenceResponse createdRetirement( + GetCanonicalGameplayRosterReferenceResponse original) { + var target = CanonicalGameplayRosterReferenceEvidence.target(original.getRequest()); + return CanonicalGameplayRosterReferenceEvidence.sealRetirement( + original.toBuilder() + .setState( + CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) + .setTerminalOutcome( + original.getTerminalOutcome().isEmpty() ? "MENU" : original.getTerminalOutcome()) + .setRetirementUuid(uuid(18).toString()) + .setSupersedingPointerDigest("9".repeat(64)) + .setSupersedingPointerVersion(target.getPointerVersion() + 1L) + .setSupersedingCatalogRevision(target.getCatalogRevision()) + .setSupersedingWorldEpoch(target.getActiveWorldEpoch()) + .build()); + } + private static CanonicalGameplayRosterRetirementAcknowledgementRequest acknowledgement( GetCanonicalGameplayRosterReferenceRequest original, GetCanonicalGameplayRosterReferenceResponse observed, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidenceTest.java new file mode 100644 index 0000000000..828d9fa645 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalPlayerCreatedRosterEvidenceTest.java @@ -0,0 +1,856 @@ +package net.firedevops.firemud.common.world; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.IOException; +import java.io.InputStream; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.AuthoredSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Catalog; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Core; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Descriptor; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.ExpectedVersion; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Mutation; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Pointer; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Policy; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Rule; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Scope; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction.Target; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +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.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; + +/** + * Pure controlled PLAYER_CREATED value tests; these do not establish authenticated creation proof. + */ +class CanonicalPlayerCreatedRosterEvidenceTest { + private static final String VECTOR_RESOURCE = "/operator/character-create-v1-vectors.json"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String ACCOUNT = uuid(1); + private static final String CHARACTER_1 = uuid(2); + private static final String CHARACTER_2 = uuid(3); + private static final String SNAPSHOT = uuid(4); + + record SelectedFixture( + CanonicalSelectedPlayerCreatedCharacterRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse response) {} + + private record Fixture( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + CanonicalSelectedPlayerCreatedCharacterRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse response) {} + + static SelectedFixture selectedFixture() { + try { + Fixture fixture = fixture(false); + return new SelectedFixture(fixture.request(), fixture.response()); + } catch (IOException failure) { + throw new IllegalStateException("Controlled CHARACTER_CREATE vector is unavailable", failure); + } + } + + @Test + void acceptsEmptyRosterWithoutInventingAnActor() { + CanonicalPlayerCreatedRosterRequest request = request(target(), source(), context(null)); + CanonicalPlayerCreatedRosterResponse response = response(request, List.of()); + + assertEquals(response, CanonicalPlayerCreatedRosterEvidence.requireResponse(request, response)); + } + + @Test + void digestBindsOneAndManyOrderedActors() { + var one = List.of(actor(CHARACTER_1, "Mira")); + var many = List.of(actor(CHARACTER_1, "Mira"), actor(CHARACTER_2, "Tāne")); + + String oneDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), one); + String manyDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), many); + String reversedDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), List.of(many.get(1), many.get(0))); + + assertEquals(64, oneDigest.length()); + assertEquals(64, manyDigest.length()); + org.junit.jupiter.api.Assertions.assertNotEquals(oneDigest, manyDigest); + org.junit.jupiter.api.Assertions.assertNotEquals(manyDigest, reversedDigest); + } + + @Test + void responseRejectsChangedSourceTargetAndSnapshotDigest() { + CanonicalPlayerCreatedRosterRequest request = request(target(), source(), context(null)); + CanonicalPlayerCreatedRosterResponse valid = + response(request, List.of(actor(CHARACTER_1, "Mira"))); + + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, valid.toBuilder().setSourceIdentity(source(9)).build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, + valid.toBuilder() + .setRoster(valid.getRoster().toBuilder().setTarget(target(9))) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, + valid.toBuilder() + .setRoster(valid.getRoster().toBuilder().setSnapshotDigest("0".repeat(64))) + .build())); + } + + @Test + void requestRejectsUnknownNilAndMalformedContextValues() { + var request = request(target(), source(), context(null)); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder().setRequestUuid(uuid(0)).build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder().setUnknownFields(unknown).build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder() + .setPlayerExecutionContext( + request.getPlayerExecutionContext().toBuilder().setPlayableStateScope("1")) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder() + .setExpectedTarget( + request.getExpectedTarget().toBuilder() + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY)) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireRequest( + request.toBuilder() + .setPlayerExecutionContext( + request.getPlayerExecutionContext().toBuilder().setUnknownFields(unknown)) + .build())); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + source().toBuilder().setDescriptorUuid(uuid(0)).build())); + } + + @Test + void rejectsDuplicateActorsAndMalformedSelectedContext() { + var duplicateActors = List.of(actor(CHARACTER_1, "Mira"), actor(CHARACTER_1, "Mira")); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + ACCOUNT, target(), source(), duplicateActors)); + + var selected = selectedRequest(context(CHARACTER_1)); + assertEquals(selected, CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest(selected)); + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest( + selected.toBuilder() + .setPlayerExecutionContext( + selected.getPlayerExecutionContext().toBuilder() + .setCharacterId(CHARACTER_2)) + .build())); + } + + @Test + void acceptsExactSelectedCreationReceiptAndReturnsTheOriginalImmutableResponse() { + Fixture controlled = uncheckedFixture(false); + assertNotEquals( + rawDigest(controlled.action().mutation().authoredSource().policy().contentDigest()), + controlled.target().getPublishedPolicyDigest()); + PlayerCreationDescriptor actualDescriptor = + PlayerCreationDescriptor.parse( + controlled.action().mutation().authoredSource().descriptor().canonicalJson()); + assertEquals(actualDescriptor.digest(), controlled.source().getDescriptorDigest()); + assertEquals( + actualDescriptor.digest(), controlled.response().getSourceIdentity().getDescriptorDigest()); + SelectedFixture fixture = new SelectedFixture(controlled.request(), controlled.response()); + + assertSame( + fixture.response(), + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( + fixture.request(), fixture.response())); + } + + @Test + void acceptsOriginalCreationAcrossRuntimeReplacement() throws IOException { + Fixture fixture = fixture(true); + + assertEquals( + fixture.response(), + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( + fixture.request(), fixture.response())); + } + + @Test + void rejectsOuterSubstitutionsAndChangedCreationOperationDigestOrActor() { + Fixture fixture = uncheckedFixture(false); + var response = fixture.response(); + + assertRejected(fixture.request(), response.toBuilder().setRequestUuid(uuid(101)).build()); + assertRejected( + fixture.request(), response.toBuilder().setCanonicalAccountUuid(uuid(102)).build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTarget(response.getTarget().toBuilder().setPointerVersion(99)) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setSnapshot(response.getSnapshot().toBuilder().setSnapshotDigest("f".repeat(64))) + .build()); + assertRejected( + fixture.request(), response.toBuilder().setCreationOperationUuid(uuid(103)).build()); + assertRejected( + fixture.request(), response.toBuilder().setMutationDigest("f".repeat(64)).build()); + + var changedActorRequest = + selectedCreatedRequest(fixture.action(), fixture.target(), fixture.source(), uuid(104)); + assertRejected( + changedActorRequest, response.toBuilder().setSelectedCharacterUuid(uuid(104)).build()); + } + + @Test + void rejectsDescriptorBindingPolicyAndVersionSubstitution() throws IOException { + Fixture fixture = fixture(false); + var changedDescriptor = fixture.source().toBuilder().setDescriptorUuid(uuid(111)).build(); + assertRejectedWithSource(fixture, changedDescriptor); + var changedBindingId = fixture.source().toBuilder().setAuthoredBindingUuid(uuid(112)).build(); + assertRejectedWithSource(fixture, changedBindingId); + var changedBindingDigest = + fixture.source().toBuilder().setAuthoredBindingDigest("sha256:" + "f".repeat(64)).build(); + assertRejectedWithSource(fixture, changedBindingDigest); + + CanonicalGameplayRosterTarget changedPolicy = + fixture.target().toBuilder().setPublishedPolicyDigest("f".repeat(64)).build(); + assertRejected( + fixture.request(), fixture.response().toBuilder().setTarget(changedPolicy).build()); + CanonicalGameplayRosterTarget changedVersion = + fixture.target().toBuilder().setCanonicalVersionUuid(uuid(113)).build(); + assertRejectedWithTarget(fixture, changedVersion); + } + + @Test + void rejectsMalformedUnknownMissingAndAbortedTerminalValues() { + Fixture fixture = uncheckedFixture(false); + var response = fixture.response(); + var terminal = response.getTerminal(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertRejected(fixture.request(), response.toBuilder().setUnknownFields(unknown).build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().setUnknownFields(unknown)).build()); + assertRejected(fixture.request(), response.toBuilder().clearTerminal().build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().clearOriginalRequest()).build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOutcome( + EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED)) + .build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().setTerminalId("")).build()); + assertRejected( + fixture.request(), + response.toBuilder().setTerminal(terminal.toBuilder().setTerminalFence(0)).build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setCompletedAt("not-an-instant")) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setAbortRequestId(uuid(115))) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setOriginalWorldProtection(ByteString.EMPTY)) + .build()); + + var malformedAccountOriginal = + terminal.getAccountOriginal().toBuilder() + .setOriginalSourceReadback(ByteString.EMPTY) + .build(); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setAccountOriginal(malformedAccountOriginal)) + .build()); + var unknownReference = + terminal.getOriginalRequest().getWorldProtection().toBuilder() + .setUnknownFields(unknown) + .build(); + var unknownOriginalRequest = + terminal.getOriginalRequest().toBuilder().setWorldProtection(unknownReference).build(); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setOriginalRequest(unknownOriginalRequest)) + .build()); + } + + @Test + void enforcesOriginalSourceAndProtectionPurposeBoundsWithoutLargeByteArrays() { + Fixture fixture = uncheckedFixture(false); + var response = fixture.response(); + var terminal = response.getTerminal(); + var tooLargeSourceReadback = + terminal.getAccountOriginal().toBuilder() + .setOriginalSourceReadback(bytesWithSize(32 * 1024 * 1024 + 1)) + .build(); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal(terminal.toBuilder().setAccountOriginal(tooLargeSourceReadback)) + .build()); + + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOriginalAccountProtection(bytesWithSize(40 * 1024 * 1024 + 1))) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOriginalGameSessionProtection(bytesWithSize(48 * 1024 * 1024 + 1))) + .build()); + assertRejected( + fixture.request(), + response.toBuilder() + .setTerminal( + terminal.toBuilder() + .setOriginalWorldProtection(bytesWithSize(48 * 1024 * 1024 + 1))) + .build()); + } + + private static Fixture fixture(boolean runtimeReplacement) throws IOException { + CharacterCreateOperatorAction action = controlledAction(); + CanonicalGameplayRosterTarget target = target(action, runtimeReplacement); + CanonicalPlayerCreatedRosterSourceIdentity source = source(action); + CanonicalSelectedPlayerCreatedCharacterRequest request = + selectedCreatedRequest(action, target, source, CHARACTER_1); + CanonicalSelectedPlayerCreatedCharacterResponse response = + selectedCreatedResponse(action, target, source, request); + return new Fixture(action, target, source, request, response); + } + + private static Fixture uncheckedFixture(boolean runtimeReplacement) { + try { + return fixture(runtimeReplacement); + } catch (IOException failure) { + throw new IllegalStateException("Controlled CHARACTER_CREATE vector is unavailable", failure); + } + } + + private static CharacterCreateOperatorAction controlledAction() throws IOException { + JsonNode root; + try (InputStream input = + CanonicalPlayerCreatedRosterEvidenceTest.class.getResourceAsStream(VECTOR_RESOURCE)) { + if (input == null) throw new IOException("Missing CHARACTER_CREATE test vector"); + root = JSON.readTree(input); + } + for (JsonNode vector : root.path("vectors")) { + if ("base-public-player-created".equals(text(vector, "name"))) return action(vector); + } + throw new IOException("Missing controlled PLAYER_CREATED action vector"); + } + + private static CharacterCreateOperatorAction action(JsonNode vector) { + JsonNode scopeNode = vector.path("scope"); + JsonNode targetNode = vector.path("target"); + JsonNode expectedNode = vector.path("expectedVersion"); + JsonNode mutationNode = vector.path("mutation"); + JsonNode catalogNode = mutationNode.path("catalog"); + JsonNode pointerNode = mutationNode.path("pointer"); + JsonNode authoredNode = mutationNode.path("authoredSource"); + JsonNode policyNode = authoredNode.path("policy"); + JsonNode coreNode = authoredNode.path("core"); + JsonNode descriptorNode = authoredNode.path("descriptor"); + + Scope scope = + new Scope( + text(scopeNode, "targetNamespace"), + text(scopeNode, "tenantId"), + text(scopeNode, "playableStateNamespaceId"), + CharacterCreateOperatorAction.PlayableStateScope.valueOf( + text(scopeNode, "playableStateScope"))); + Target target = + new Target( + text(targetNode, "accountId"), + text(targetNode, "realmId"), + text(targetNode, "worldSlug"), + text(targetNode, "realmSlug"), + text(targetNode, "gameInstanceId"), + text(targetNode, "versionId")); + ExpectedVersion expected = + new ExpectedVersion( + text(expectedNode, "catalogRevision"), + text(expectedNode, "pointerVersion"), + text(expectedNode, "activeLifecycleEpoch"), + Instant.parse(text(expectedNode, "evaluatedAt")), + Instant.parse(text(expectedNode, "connectScopeExpiresAt"))); + Catalog catalog = + new Catalog( + text(catalogNode, "tenantId"), + text(catalogNode, "tenantSlug"), + text(catalogNode, "worldSlug"), + text(catalogNode, "worldDisplayName"), + text(catalogNode, "realmId"), + text(catalogNode, "realmSlug"), + text(catalogNode, "realmDisplayName"), + catalogNode.path("visible").booleanValue(), + catalogNode.path("publicProduction").booleanValue(), + text(catalogNode, "stateScope"), + text(catalogNode, "playableStateNamespaceId"), + text(catalogNode, "characterCreationPolicy"), + text(catalogNode, "catalogRevision")); + Pointer pointer = + new Pointer( + text(pointerNode, "tenantId"), + text(pointerNode, "realmId"), + text(pointerNode, "worldSlug"), + text(pointerNode, "realmSlug"), + text(pointerNode, "admissionState"), + text(pointerNode, "admissibleGameInstanceId"), + text(pointerNode, "pointerVersion"), + text(pointerNode, "catalogRevision"), + Instant.parse(text(pointerNode, "updatedAt"))); + Policy policy = + new Policy( + text(policyNode, "commitId"), + text(policyNode, "revisionId"), + text(policyNode, "logicalRevisionId"), + text(policyNode, "canonicalPolicyJson"), + text(policyNode, "contentDigest")); + Core core = new Core(text(coreNode, "canonicalJson")); + Descriptor descriptor = + new Descriptor(text(descriptorNode, "canonicalJson"), text(descriptorNode, "digest")); + AuthoredSource authored = + new AuthoredSource( + text(authoredNode, "schema"), + text(authoredNode, "bindingId"), + text(authoredNode, "bindingDigest"), + text(authoredNode, "canonicalTenantId"), + text(authoredNode, "canonicalVersionId"), + text(authoredNode, "worldSourceOperationId"), + text(authoredNode, "worldSourceEvidenceDigest"), + text(authoredNode, "worldSlug"), + text(authoredNode, "publicationWorkflowId"), + text(authoredNode, "selectedCommitId"), + text(authoredNode, "selectedCommitDigest"), + policy, + core, + descriptor, + rule(authoredNode.path("disposition")), + rule(authoredNode.path("safeFeedback"))); + Mutation mutation = + new Mutation( + text(mutationNode, "purpose"), + text(mutationNode, "entryPolicy"), + catalog, + pointer, + authored, + text(mutationNode, "canonicalCreationInput")); + return new CharacterCreateOperatorAction( + scope, target, expected, mutation, CharacterCreateOperatorAction.AuditReason.ABSENT); + } + + private static Rule rule(JsonNode node) { + return new Rule( + text(node, "key"), + text(node, "definitionJson"), + text(node, "definitionDigest"), + text(node, "sourceCommitId"), + text(node, "sourceCommitDigest"), + text(node, "revisionId"), + text(node, "revisionOrder")); + } + + private static String text(JsonNode node, String field) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Missing text field " + field); + } + return value.textValue(); + } + + private static CanonicalGameplayRosterTarget target( + CharacterCreateOperatorAction action, boolean runtimeReplacement) { + var target = action.target(); + var expected = action.expectedVersion(); + long catalogRevision = Long.parseLong(expected.catalogRevision()); + long pointerVersion = Long.parseLong(expected.pointerVersion()); + long worldEpoch = Long.parseLong(expected.activeLifecycleEpoch()); + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(action.scope().tenantId()) + .setRealmUuid(target.realmId()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(runtimeReplacement ? uuid(119) : target.gameInstanceId()) + .setCatalogRevision(runtimeReplacement ? catalogRevision + 11 : catalogRevision) + .setPublishedPolicyDigest("e".repeat(64)) + .setPublishedReleaseBundleRef("release/controlled-player-created") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCanonicalVersionUuid(target.versionId()) + .setPointerVersion(runtimeReplacement ? pointerVersion + 13 : pointerVersion) + .setActiveWorldEpoch(runtimeReplacement ? worldEpoch + 17 : worldEpoch) + .build(); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source( + CharacterCreateOperatorAction action) { + var authored = action.mutation().authoredSource(); + PlayerCreationDescriptor descriptor = + PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); + return CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(authored.bindingId()) + .setAuthoredBindingDigest(authored.bindingDigest()) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterRequest selectedCreatedRequest( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + String character) { + String requestUuid = uuid(117); + return CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(requestUuid) + .setCanonicalAccountUuid(action.target().accountId()) + .setSelectedCharacterUuid(character) + .setExpectedTarget(target) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(SNAPSHOT) + .setSnapshotDigest("a".repeat(64))) + .setPlayerExecutionContext( + context(target, action.target().accountId(), requestUuid, character)) + .setExpectedSource(source) + .build(); + } + + private static PlayerExecutionContext context( + CanonicalGameplayRosterTarget target, String account, String request, String character) { + return PlayerExecutionContext.newBuilder() + .setAccountId(account) + .setTenantId(target.getTenantUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setSessionId(uuid(118)) + .setRealmId(target.getRealmUuid()) + .setRequestId(request) + .setPlayableStateScope("SHARED") + .setCharacterId(character) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterResponse selectedCreatedResponse( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + CanonicalSelectedPlayerCreatedCharacterRequest request) { + byte[] originalAction = CharacterCreateOperatorActionCodec.encode(action); + String mutationDigest = CharacterCreateOperatorActionCodec.mutationDigest(originalAction); + ReadOriginalCharacterCreateRequest originalRequest = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setMutationDigest(mutationDigest) + .build(); + CommitProtectedCharacterCreateRequest terminalRequest = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(originalRequest) + .setAccountProtection(protectionReference(121)) + .setGameSessionProtection(protectionReference(122)) + .setWorldProtection(protectionReference(123)) + .build(); + ReadOriginalCharacterCreateResponse accountOriginal = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setCreateCharacterRequestId(uuid(124)) + .setConnectScopeId("controlled-connect-scope") + .setAuthenticatedAccountId(action.target().accountId()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(originalAction)) + // This opaque fixture is preserved as bytes and is not treated as remote authority. + .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-source-readback")) + .setMutationDigest(mutationDigest) + .build(); + EntityCharacterCreateTerminal terminal = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest(terminalRequest) + .setAccountOriginal(accountOriginal) + .setOriginalAccountProtection(ByteString.copyFromUtf8("account-protection")) + .setOriginalGameSessionProtection(ByteString.copyFromUtf8("game-session-protection")) + .setOriginalWorldProtection(ByteString.copyFromUtf8("world-protection")) + .setEntityIntakeRequestId(uuid(125)) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(request.getSelectedCharacterUuid()) + .setTerminalId(uuid(126)) + .setTerminalFence(1) + .setCompletedAt("2026-10-23T00:00:00Z") + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .build(); + return CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(target) + .setSnapshot(request.getExpectedSnapshot()) + .setSourceIdentity(source) + .setCreationOperationUuid(uuid(120)) + .setMutationDigest(mutationDigest) + .setTerminal(terminal) + .build(); + } + + private static CharacterCreateProtectionReference protectionReference(int value) { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(uuid(value)) + .setProtectionFence(1) + .build(); + } + + private static String rawDigest(String prefixedDigest) { + return prefixedDigest.substring("sha256:".length()); + } + + private static void assertRejected( + CanonicalSelectedPlayerCreatedCharacterRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse response) { + assertThrows( + IllegalArgumentException.class, + () -> CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, response)); + } + + private static void assertRejectedWithSource( + Fixture fixture, CanonicalPlayerCreatedRosterSourceIdentity source) { + var request = selectedCreatedRequest(fixture.action(), fixture.target(), source, CHARACTER_1); + var response = fixture.response().toBuilder().setSourceIdentity(source).build(); + assertRejected(request, response); + } + + private static void assertRejectedWithTarget( + Fixture fixture, CanonicalGameplayRosterTarget target) { + var request = selectedCreatedRequest(fixture.action(), target, fixture.source(), CHARACTER_1); + var response = fixture.response().toBuilder().setTarget(target).build(); + assertRejected(request, response); + } + + private static ByteString bytesWithSize(int size) { + ByteString megabyte = ByteString.copyFrom(new byte[1024 * 1024]); + ByteString result = ByteString.EMPTY; + int remaining = size; + while (remaining >= megabyte.size()) { + result = result.concat(megabyte); + remaining -= megabyte.size(); + } + if (remaining > 0) result = result.concat(megabyte.substring(0, remaining)); + return result; + } + + private static CanonicalPlayerCreatedRosterResponse response( + CanonicalPlayerCreatedRosterRequest request, List actors) { + String digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), + request.getExpectedTarget(), + request.getExpectedSource(), + actors); + return CanonicalPlayerCreatedRosterResponse.newBuilder() + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .setSourceIdentity(request.getExpectedSource()) + .build(); + } + + private static CanonicalPlayerCreatedRosterRequest request( + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + PlayerExecutionContext context) { + return CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(uuid(5)) + .setCanonicalAccountUuid(ACCOUNT) + .setExpectedTarget(target) + .setPlayerExecutionContext(context) + .setExpectedSource(source) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterRequest selectedRequest( + PlayerExecutionContext context) { + return CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(uuid(5)) + .setCanonicalAccountUuid(ACCOUNT) + .setSelectedCharacterUuid(CHARACTER_1) + .setExpectedTarget(target()) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(SNAPSHOT) + .setSnapshotDigest("a".repeat(64))) + .setPlayerExecutionContext(context) + .setExpectedSource(source()) + .build(); + } + + private static PlayerExecutionContext context(String character) { + var builder = + PlayerExecutionContext.newBuilder() + .setAccountId(ACCOUNT) + .setTenantId(uuid(10)) + .setPlayableStateNamespaceId(uuid(11)) + .setGameInstanceId(uuid(12)) + .setSessionId(uuid(13)) + .setRealmId(uuid(14)) + .setRequestId(uuid(5)) + .setPlayableStateScope("SHARED"); + if (character != null) builder.setCharacterId(character); + return builder.build(); + } + + private static CanonicalGameplayRosterTarget target() { + return target(0); + } + + private static CanonicalGameplayRosterTarget target(int variant) { + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(uuid(10)) + .setRealmUuid(uuid(14)) + .setWorldSlug("world") + .setRealmSlug("realm") + .setGameInstanceUuid(uuid(12)) + .setCatalogRevision(7) + .setPublishedPolicyDigest("a".repeat(64)) + .setPublishedReleaseBundleRef("release/one") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setPlayableStateNamespaceUuid(uuid(11)) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCanonicalVersionUuid(uuid(15)) + .setPointerVersion(variant == 0 ? 2 : 3) + .setActiveWorldEpoch(4) + .build(); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source() { + return source(0); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source(int variant) { + return CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(uuid(20 + variant)) + .setDescriptorRevisionUuid(uuid(30)) + .setDescriptorDigest("sha256:" + "d".repeat(64)) + .setAuthoredBindingUuid(uuid(40)) + .setAuthoredBindingDigest("sha256:" + "e".repeat(64)) + .build(); + } + + private static CanonicalGameplayRosterActor actor(String character, String displayName) { + return CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(character) + .setDisplayName(displayName) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build(); + } + + private static String uuid(int value) { + return new UUID(0L, value).toString(); + } +} diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java new file mode 100644 index 0000000000..7fdede06fc --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java @@ -0,0 +1,391 @@ +package net.firedevops.firemud.common.testing; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +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.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationRequest; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** + * Controlled complete CHARACTER_CREATE values for transport proofs only. Foreign protection and + * source-readback bytes are stipulated fixtures; this class grants no authenticated owner custody. + */ +public final class ControlledPlayerCreatedRosterTerminalFixtures { + private ControlledPlayerCreatedRosterTerminalFixtures() {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "All retained generated protobuf messages are immutable.") + public record Bundle( + GetCanonicalGameplayRosterReferenceRequest originalRequest, + GetCanonicalGameplayRosterReferenceResponse original, + CanonicalSelectedPlayerCreatedCharacterResponse selected, + CanonicalGameplayRosterRetirementAcknowledgementRequest acknowledgementRequest, + CanonicalGameplayRosterRetirementAcknowledgementResponse acknowledgement, + CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "All retained generated protobuf messages are immutable.") + public Bundle {} + } + + /** One real canonical action/terminal with a controlled 5 MiB opaque Account protection. */ + public static Bundle withFiveMebibyteAccountProtection(String namespace) { + var action = action(namespace); + var target = target(action); + var source = source(action); + var account = action.target().accountId(); + var operation = uuid(117); + var character = uuid(2); + var context = + PlayerExecutionContext.newBuilder() + .setRequestId(operation) + .setAccountId(account) + .setSessionId(uuid(118)) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .setGameInstanceId(target.getGameInstanceUuid()) + .build(); + var rosterRequest = + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(operation) + .setCanonicalAccountUuid(account) + .setExpectedTarget(target) + .setExpectedSource(source) + .setPlayerExecutionContext(context) + .build(); + var actors = + List.of( + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(character) + .setDisplayName("Persisted created actor") + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()); + var digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest(account, target, source, actors); + var roster = + CanonicalPlayerCreatedRosterEvidence.requireResponse( + rosterRequest, + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(source) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(account) + .setTarget(target) + .setSnapshotUuid(uuid(4)) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .build()); + var selectedRequest = + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(operation) + .setCanonicalAccountUuid(account) + .setSelectedCharacterUuid(character) + .setExpectedTarget(target) + .setExpectedSource(source) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(uuid(4)) + .setSnapshotDigest(digest)) + .setPlayerExecutionContext(context.toBuilder().setCharacterId(character)) + .build(); + var selected = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( + selectedRequest, selectedCreatedResponse(action, target, source, selectedRequest)); + var originalRequest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(operation), + UUID.fromString(account), + UUID.fromString(uuid(118)), + namespace, + target, + source); + var original = + CanonicalGameplayRosterReferenceEvidence.requireResponse( + originalRequest, + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + originalRequest, 1L, UUID.fromString(uuid(130)), roster) + .toBuilder() + .setSelectionInput( + CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("1")) + .setSelectedCharacterUuid(character) + .setCanonicalSelectedPlayerCreatedCharacterReceipt(selected.toByteString()) + .setTerminalOutcome("SELECTED") + .build()); + var retired = + CanonicalGameplayRosterReferenceEvidence.sealRetirement( + original.toBuilder() + .setState( + CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) + .setRetirementUuid(uuid(131)) + .setSupersedingPointerDigest("e".repeat(64)) + .setSupersedingPointerVersion(target.getPointerVersion() + 1) + .setSupersedingCatalogRevision(target.getCatalogRevision()) + .setSupersedingWorldEpoch(target.getActiveWorldEpoch()) + .build()); + var request = + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(originalRequest) + .setObservedRetirement(retired) + .setObservationUuid(uuid(132)) + .setAdmissionUuid(uuid(133)) + .setSnapshotUuid(uuid(4)) + .setSnapshotDigest(digest) + .setMinimumRetentionMillis(1000) + .build()); + var acknowledgement = + CanonicalGameplayRosterRetirementEvidence.response( + request, UUID.fromString(uuid(134)), 1000); + return new Bundle( + originalRequest, + original, + selected, + request, + acknowledgement, + CanonicalGameplayRosterRetirementEvidence.confirmation(request, acknowledgement)); + } + + private static CanonicalGameplayRosterTarget target(CharacterCreateOperatorAction action) { + var target = action.target(); + var expected = action.expectedVersion(); + long catalogRevision = Long.parseLong(expected.catalogRevision()); + long pointerVersion = Long.parseLong(expected.pointerVersion()); + long worldEpoch = Long.parseLong(expected.activeLifecycleEpoch()); + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(action.scope().tenantId()) + .setRealmUuid(target.realmId()) + .setWorldSlug(target.worldSlug()) + .setRealmSlug(target.realmSlug()) + .setGameInstanceUuid(target.gameInstanceId()) + .setCatalogRevision(catalogRevision) + .setPublishedPolicyDigest("e".repeat(64)) + .setPublishedReleaseBundleRef("release/controlled-player-created") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCanonicalVersionUuid(target.versionId()) + .setPointerVersion(pointerVersion) + .setActiveWorldEpoch(worldEpoch) + .build(); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source( + CharacterCreateOperatorAction action) { + var authored = action.mutation().authoredSource(); + PlayerCreationDescriptor descriptor = + PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); + return CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(authored.bindingId()) + .setAuthoredBindingDigest(authored.bindingDigest()) + .build(); + } + + private static CanonicalSelectedPlayerCreatedCharacterResponse selectedCreatedResponse( + CharacterCreateOperatorAction action, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + CanonicalSelectedPlayerCreatedCharacterRequest request) { + byte[] originalAction = CharacterCreateOperatorActionCodec.encode(action); + String mutationDigest = CharacterCreateOperatorActionCodec.mutationDigest(originalAction); + ReadOriginalCharacterCreateRequest originalRequest = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setMutationDigest(mutationDigest) + .build(); + CommitProtectedCharacterCreateRequest terminalRequest = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(originalRequest) + .setAccountProtection(protectionReference(121)) + .setGameSessionProtection(protectionReference(122)) + .setWorldProtection(protectionReference(123)) + .build(); + ReadOriginalCharacterCreateResponse accountOriginal = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(uuid(120)) + .setCreateCharacterRequestId(uuid(124)) + .setConnectScopeId("controlled-connect-scope") + .setAuthenticatedAccountId(action.target().accountId()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(originalAction)) + // This opaque fixture is preserved as bytes and is not treated as remote authority. + .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-source-readback")) + .setMutationDigest(mutationDigest) + .build(); + EntityCharacterCreateTerminal terminal = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest(terminalRequest) + .setAccountOriginal(accountOriginal) + .setOriginalAccountProtection(ByteString.copyFrom(new byte[5 * 1024 * 1024])) + .setOriginalGameSessionProtection(ByteString.copyFromUtf8("game-session-protection")) + .setOriginalWorldProtection(ByteString.copyFromUtf8("world-protection")) + .setEntityIntakeRequestId(uuid(125)) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(request.getSelectedCharacterUuid()) + .setTerminalId(uuid(126)) + .setTerminalFence(1) + .setCompletedAt("2026-10-23T00:00:00Z") + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .build(); + return CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(target) + .setSnapshot(request.getExpectedSnapshot()) + .setSourceIdentity(source) + .setCreationOperationUuid(uuid(120)) + .setMutationDigest(mutationDigest) + .setTerminal(terminal) + .build(); + } + + private static CharacterCreateProtectionReference protectionReference(int value) { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(uuid(value)) + .setProtectionFence(1) + .build(); + } + + // Same complete base-public-player-created action values as the Common codec vector. + private static CharacterCreateOperatorAction action(String namespace) { + return new CharacterCreateOperatorAction( + new CharacterCreateOperatorAction.Scope( + namespace, + "a1000000-0000-4000-8000-000000000001", + "a3000000-0000-4000-8000-000000000001", + CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + new CharacterCreateOperatorAction.Target( + "a4000000-0000-4000-8000-000000000001", + "a2000000-0000-4000-8000-000000000001", + "ember-vale", + "salt-harbor", + "a5000000-0000-4000-8000-000000000001", + "a6000000-0000-4000-8000-000000000001"), + new CharacterCreateOperatorAction.ExpectedVersion( + "17", + "23", + "31", + Instant.parse("2026-10-11T12:34:56.123456789Z"), + Instant.parse("2026-10-11T12:39:56.987654321Z")), + new CharacterCreateOperatorAction.Mutation( + "CHARACTER_CREATE", + "PLAYER_CREATED", + new CharacterCreateOperatorAction.Catalog( + "a1000000-0000-4000-8000-000000000001", + "tideward", + "ember-vale", + "Ember Reach", + "a2000000-0000-4000-8000-000000000001", + "salt-harbor", + "Salt Harbor", + true, + true, + "SHARED", + "a3000000-0000-4000-8000-000000000001", + "PLAYER_CREATED", + "17"), + new CharacterCreateOperatorAction.Pointer( + "a1000000-0000-4000-8000-000000000001", + "a2000000-0000-4000-8000-000000000001", + "ember-vale", + "salt-harbor", + "OPEN", + "a5000000-0000-4000-8000-000000000001", + "23", + "17", + Instant.parse("2026-10-11T12:30:01.012345678Z")), + new CharacterCreateOperatorAction.AuthoredSource( + "game-design-authored-initial-actor-core-projection/v1", + "a7000000-0000-4000-8000-000000000001", + "sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a", + "a1000000-0000-4000-8000-000000000001", + "a6000000-0000-4000-8000-000000000001", + "a8000000-0000-4000-8000-000000000001", + "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + "ember-vale", + "published-ember-workflow-2026-10-11", + "a9000000-0000-4000-8000-000000000001", + "sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a", + new CharacterCreateOperatorAction.Policy( + "aa000000-0000-4000-8000-000000000001", + "ab000000-0000-4000-8000-000000000001", + "policy-logical-ember-r4", + "{\"creationDescriptor\":{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1},\"entryPolicy\":\"PLAYER_CREATED\",\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"},\"publicProduction\":true,\"realmDisplayName\":\"Salt Harbor\",\"realmSlug\":\"salt-harbor\",\"schemaVersion\":3,\"stateScope\":\"SHARED\",\"visible\":true,\"worldDisplayName\":\"Ember Reach\",\"worldSlug\":\"ember-vale\"}", + "sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1"), + new CharacterCreateOperatorAction.Core( + "{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}"), + new CharacterCreateOperatorAction.Descriptor( + "{\"dependencies\":[],\"descriptorId\":\"ac000000-0000-4000-8000-000000000001\",\"descriptorRevisionId\":\"ad000000-0000-4000-8000-000000000001\",\"inputKind\":\"EMPTY_OBJECT\",\"schemaVersion\":1}", + "sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415"), + new CharacterCreateOperatorAction.Rule( + "newcomer", + "{\"deniedAdmissionTags\":[],\"dispositionKey\":\"newcomer\",\"safeFeedbackKey\":\"welcome\"}", + "sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b", + "ae000000-0000-4000-8000-000000000001", + "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "af000000-0000-4000-8000-000000000001", + "41"), + new CharacterCreateOperatorAction.Rule( + "welcome", + "{\"arguments\":[],\"audience\":\"SOURCE_ACTOR\",\"feedbackKey\":\"welcome\",\"messageKey\":\"welcome_message\",\"messageTemplate\":\"Welcome, traveler.\",\"outcomeEvent\":\"actor_created\",\"replayPolicy\":\"EFFECT_IDEMPOTENT\",\"visibility\":\"PUBLIC\"}", + "sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871", + "ae000000-0000-4000-8000-000000000001", + "sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2", + "b0000000-0000-4000-8000-000000000001", + "42")), + "{}"), + CharacterCreateOperatorAction.AuditReason.ABSENT); + } + + private static String uuid(int value) { + return new UUID(0L, value).toString(); + } +} diff --git a/services/entity-management-service/build.gradle.kts b/services/entity-management-service/build.gradle.kts index 68a5100a5c..ccf06239d0 100644 --- a/services/entity-management-service/build.gradle.kts +++ b/services/entity-management-service/build.gradle.kts @@ -2,6 +2,7 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { + `java-test-fixtures` id("net.firedevops.firemud.secured-stateful-service-conventions") id("net.firedevops.firemud.jooq-conventions") } @@ -11,10 +12,18 @@ firemudJooq { } dependencies { + testFixturesCompileOnly(libs.spotbugs.annotations) implementation(project(":common-platform-core")) implementation(project(":common-security")) implementation(libs.spring.boot.starter.cache) testImplementation(testFixtures(project(":common-platform-core"))) + testImplementation(testFixtures(project(":common-test-support"))) + testFixturesImplementation(testFixtures(project(":common-platform-core"))) + testFixturesImplementation(testFixtures(project(":common-test-support"))) + testFixturesImplementation("io.grpc:grpc-netty-shaded:${libs.versions.grpc.get()}") + testFixturesImplementation("io.grpc:grpc-protobuf:${libs.versions.grpc.get()}") + testFixturesImplementation("io.grpc:grpc-stub:${libs.versions.grpc.get()}") + testFixturesImplementation("com.google.protobuf:protobuf-java:${libs.versions.protobuf.get()}") } // Export only owner classes for composed proofs; application and Flyway resources stay local. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java new file mode 100644 index 0000000000..5640c3d281 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.entitymanagement.v1.AbortProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityCharacterCreateTerminalRequest; + +/** Manually composed only; no annotation, bean, controller, feature flag or route registration. */ +public final class EntityCharacterCreateGrpcService + extends EntityCharacterCreateServiceGrpc.EntityCharacterCreateServiceImplBase { + private final EntityCharacterCreateService owner; + + public EntityCharacterCreateGrpcService(EntityCharacterCreateService owner) { + this.owner = Objects.requireNonNull(owner); + } + + @Override + public void commitProtectedCharacterCreate( + CommitProtectedCharacterCreateRequest request, + StreamObserver observer) { + deliver(() -> owner.commit(request), observer); + } + + @Override + public void abortProtectedCharacterCreate( + AbortProtectedCharacterCreateRequest request, + StreamObserver observer) { + deliver(() -> owner.abort(request), observer); + } + + @Override + public void readEntityCharacterCreateTerminal( + ReadEntityCharacterCreateTerminalRequest request, + StreamObserver observer) { + deliver(() -> owner.read(request), observer); + } + + private static void deliver( + Supplier action, + StreamObserver observer) { + try { + observer.onNext(action.get()); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Entity creation storage unavailable; no terminal inferred") + .asRuntimeException()); + } catch (RuntimeException invalid) { + observer.onError( + Status.DATA_LOSS + .withDescription("Entity creation owner evidence failed closed") + .asRuntimeException()); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePeerInterceptor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePeerInterceptor.java new file mode 100644 index 0000000000..ccfce656b8 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePeerInterceptor.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Set; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Unregistered certificate-only method allowlist; JWT/header claims never substitute for mTLS. */ +public final class EntityCharacterCreatePeerInterceptor implements ServerInterceptor { + private static final String PREFIX = "entity_management.v1.EntityCharacterCreateService/"; + private static final Set OWNERS = + Set.of("account-service", "game-session-service", "world-management-service"); + private static final Context.Key VERIFIED_PEER = + Context.key("entity-character-create-verified-peer"); + private final String namespace; + + public EntityCharacterCreatePeerInterceptor(String namespace) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + String method = call.getMethodDescriptor().getFullMethodName(); + if (!method.startsWith(PREFIX)) return next.startCall(call, headers); + var peer = + GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) + .orElse(null); + boolean read = method.equals(PREFIX + "ReadEntityCharacterCreateTerminal"); + boolean mutation = + method.equals(PREFIX + "CommitProtectedCharacterCreate") + || method.equals(PREFIX + "AbortProtectedCharacterCreate"); + if ((!read && !mutation) + || peer == null + || !namespace.equals(peer.namespace()) + || !(read ? OWNERS.contains(peer.service()) : "account-service".equals(peer.service())) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + call.close( + Status.PERMISSION_DENIED.withDescription("Exact creation owner workload required"), + new Metadata()); + return new ServerCall.Listener<>() {}; + } + return Contexts.interceptCall( + Context.current() + .withValue(VERIFIED_PEER, peer) + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer), + call, + headers, + next); + } + + static void requirePeer(String namespace, boolean mutation) { + var peer = VERIFIED_PEER.get(); + if (peer == null + || !namespace.equals(peer.namespace()) + || !(mutation ? "account-service".equals(peer.service()) : OWNERS.contains(peer.service())) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + throw Status.PERMISSION_DENIED + .withDescription("Exact authenticated creation owner required") + .asRuntimeException(); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProofs.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProofs.java new file mode 100644 index 0000000000..56d7a6c7ac --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProofs.java @@ -0,0 +1,95 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import java.util.Objects; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; + +/** Internal result of independent owner reads; never accepted as an RPC request. */ +record EntityCharacterCreateProofs( + CommitProtectedCharacterCreateRequest request, + ReadOriginalCharacterCreateResponse original, + ReadOriginalCharacterCreateProtectionResponse account, + GameSessionCharacterCreateProtectionReader.Readback gameSession, + WorldCharacterCreateLifecycleProtection world, + EntityEmptySelectedSourceIntakeReceipt entitySource) { + EntityCharacterCreateProofs { + EntityCharacterCreateBindings.requireRequest(request); + CharacterCreateOperatorAction action = + EntityCharacterCreateBindings.requireOriginal(request.getOriginal(), original); + EntityCharacterCreateBindings.requireAccountProtection(request, original, account); + Objects.requireNonNull(gameSession); + EntityCharacterCreateBindings.requireBound( + world, EntityCharacterCreateBindings.MAX_WORLD_RESPONSE_BYTES); + Objects.requireNonNull(entitySource); + if (!account.equals(gameSession.accountProtection()) + || !request.getGameSessionProtection().equals(gameSession.reference()) + || !world.hasAccountProtection() + || !account.equals(world.getAccountProtection()) + || !request.getWorldProtection().getProtectionId().equals(world.getWorldProtectionId()) + || request.getWorldProtection().getProtectionFence() != world.getWorldProtectionFence() + || world.getOriginalLifecycleEvidence().isEmpty()) + throw EntityCharacterCreateBindings.conflict(); + for (String acquiredAt : + java.util.List.of( + account.getAcquiredAt(), gameSession.acquiredAt(), world.getAcquiredAt())) { + // Each owner establishes acquisition validity with its own clock. Retain and parse its + // original timestamp without comparing clocks belonging to different services. + EntityCharacterCreateBindings.instant(acquiredAt); + } + if (!action.scope().targetNamespace().equals(entitySource.targetNamespace()) + || !action.scope().tenantId().equals(entitySource.canonicalTenantId().toString()) + || !action.target().versionId().equals(entitySource.canonicalVersionId().toString()) + || !action + .mutation() + .authoredSource() + .selectedCommitId() + .equals(entitySource.selectedCommitId().toString())) { + throw EntityCharacterCreateBindings.conflict(); + } + var lifecycle = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + world.getOriginalLifecycleEvidence().toByteArray()); + var target = lifecycle.request(); + var authored = action.mutation().authoredSource(); + var launch = lifecycle.launchBinding(); + if (!authored + .worldSourceOperationId() + .equals(launch.descriptor().authoredWorldSourceOperationId().toString()) + || !authored + .worldSourceEvidenceDigest() + .equals(launch.descriptor().authoredWorldSourceEvidenceDigest()) + || !authored.selectedCommitId().equals(launch.releaseAttestation().commitId()) + || !authored + .publicationWorkflowId() + .equals(launch.releaseAttestation().publishWorkflowId())) + throw EntityCharacterCreateBindings.conflict(); + if (!original.getOperationId().equals(target.readRequestId().toString()) + || !action.scope().targetNamespace().equals(target.targetNamespace()) + || !action.scope().tenantId().equals(target.canonicalTenantId().toString()) + || !action + .scope() + .playableStateNamespaceId() + .equals(target.playableStateNamespaceId().toString()) + || !action.mutation().catalog().stateScope().equals(target.playableStateScope()) + || !action.target().gameInstanceId().equals(target.canonicalGameInstanceId().toString()) + || !action.target().versionId().equals(target.canonicalVersionId().toString()) + || !action.target().worldSlug().equals(target.worldSlug()) + || !target.publicProduction() + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || !action + .expectedVersion() + .activeLifecycleEpoch() + .equals(Long.toString(lifecycle.lifecycleEpoch()))) { + throw EntityCharacterCreateBindings.conflict(); + } + } + + CharacterCreateOperatorAction action() { + return EntityCharacterCreateBindings.requireOriginal(request.getOriginal(), original); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java new file mode 100644 index 0000000000..7558020a3a --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java @@ -0,0 +1,561 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import com.google.protobuf.InvalidProtocolBufferException; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.time.Clock; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection.AuthoredCore; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered short owner transactions. No RPC, credential, external mapping or seed promotion. + */ +public final class EntityCharacterCreateRepository { + private final DSLContext dsl; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal service collaborator.") + public EntityCharacterCreateRepository(DSLContext dsl, Clock clock) { + this.dsl = Objects.requireNonNull(dsl); + this.clock = Objects.requireNonNull(clock); + } + + public Optional read(ReadOriginalCharacterCreateRequest request) { + outsideTransaction(); + EntityCharacterCreateBindings.requireOriginalRequest(request); + Record row = + dsl.fetchOne( + "SELECT * FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + request.getTargetNamespace(), + UUID.fromString(request.getOperationId())); + if (row == null) return Optional.empty(); + if (!request.getMutationDigest().equals(row.get("mutation_digest", String.class))) + throw EntityCharacterCreateBindings.conflict(); + return Optional.of(terminal(row)); + } + + Optional replay(CommitProtectedCharacterCreateRequest request) { + var result = read(request.getOriginal()); + result.ifPresent(terminal -> requireSameRequest(request, terminal)); + return result; + } + + List readPlayerCreatedRoster( + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterReadService.PublishedIdentity published) { + outsideTransaction(); + Objects.requireNonNull(account, "account"); + Objects.requireNonNull(published, "published"); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var actors = + tx.fetch( + "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL ORDER BY character_uuid", + published.tenantId(), + account.accountId(), + published.playableStateNamespaceId()); + var result = new java.util.ArrayList(actors.size()); + for (Record actor : actors) { + readStoredPlayerCreatedTerminal(tx, account, published, actor, false); + result.add( + new CanonicalGameplayRosterActor( + actor.get("character_uuid", UUID.class), actor.get("name", String.class))); + } + return List.copyOf(result); + }); + } + + EntityCharacterCreateTerminal readSelectedPlayerCreatedTerminal( + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterReadService.PublishedIdentity published, + UUID characterId) { + outsideTransaction(); + Objects.requireNonNull(account, "account"); + Objects.requireNonNull(published, "published"); + requireCanonicalCharacterId(characterId); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record actor = + tx.fetchOne( + "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ? AND tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL", + characterId, + published.tenantId(), + account.accountId(), + published.playableStateNamespaceId()); + if (actor == null) throw selectedPlayerCreatedActorUnavailable(); + return readStoredPlayerCreatedTerminal(tx, account, published, actor, true); + }); + } + + /** + * Reads the current persisted created roster inside an existing writable owner transaction. This + * bounded path deliberately shares the same terminal and source-provenance verifier as the public + * read path, while avoiding a nested read-only transaction. + */ + static List readPlayerCreatedRosterWithinOwnerTransaction( + DSLContext tx, + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterReadService.PublishedIdentity published) { + Objects.requireNonNull(tx, "tx"); + Objects.requireNonNull(account, "account"); + Objects.requireNonNull(published, "published"); + var actors = + tx.fetch( + "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL ORDER BY character_uuid LIMIT 101 FOR SHARE", + published.tenantId(), + account.accountId(), + published.playableStateNamespaceId()); + if (actors.size() > 100) { + throw Status.RESOURCE_EXHAUSTED + .withDescription("PLAYER_CREATED roster exceeds its bounded size") + .asRuntimeException(); + } + var result = new java.util.ArrayList(actors.size()); + for (Record actor : actors) { + readStoredPlayerCreatedTerminal(tx, account, published, actor, false); + result.add( + new CanonicalGameplayRosterActor( + actor.get("character_uuid", UUID.class), actor.get("name", String.class))); + } + return List.copyOf(result); + } + + /** Reads one selected created terminal inside the caller's writable owner transaction. */ + static EntityCharacterCreateTerminal readSelectedPlayerCreatedTerminalWithinOwnerTransaction( + DSLContext tx, + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterReadService.PublishedIdentity published, + UUID characterId) { + Objects.requireNonNull(tx, "tx"); + Objects.requireNonNull(account, "account"); + Objects.requireNonNull(published, "published"); + requireCanonicalCharacterId(characterId); + Record actor = + tx.fetchOne( + "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ? AND tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL FOR SHARE", + characterId, + published.tenantId(), + account.accountId(), + published.playableStateNamespaceId()); + if (actor == null) throw selectedPlayerCreatedActorUnavailable(); + return readStoredPlayerCreatedTerminal(tx, account, published, actor, true); + } + + private static EntityCharacterCreateTerminal readStoredPlayerCreatedTerminal( + DSLContext tx, + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterReadService.PublishedIdentity published, + Record actor, + boolean sourceMismatchIsUnavailable) { + UUID operationId = actor.get("creation_operation_id", UUID.class); + String operationNamespace = actor.get("creation_target_namespace", String.class); + if (operationId == null || operationNamespace == null) throw corruptRoster(); + Record operation = + tx.fetchOne( + "SELECT * FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + operationNamespace, + operationId); + if (operation == null) throw corruptRoster(); + EntityCharacterCreateTerminal creation = terminal(operation); + CharacterCreateOperatorAction action; + try { + action = + EntityCharacterCreateBindings.requireOriginal( + creation.getOriginalRequest().getOriginal(), creation.getAccountOriginal()); + } catch (RuntimeException malformed) { + throw corruptRoster(); + } + if (creation.getOutcome() + != EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED + || !action.target().accountId().equals(account.accountId().toString()) + || !creation.getCharacterId().equals(actor.get("character_uuid", UUID.class).toString()) + || !account.accountId().equals(actor.get("account_uuid", UUID.class)) + || !published.tenantId().equals(actor.get("tenant_uuid", UUID.class)) + || !published + .playableStateNamespaceId() + .equals(actor.get("playable_state_namespace_id", UUID.class)) + || !"PLAYABLE_STATE_SCOPE_SHARED".equals(actor.get("playable_state_scope", String.class)) + || !"OWNER_RESOLVED".equals(actor.get("actor_identity_status", String.class)) + || actor.get("actor_identity_quarantine_reason", String.class) != null + || !"PLAYER_CREATED".equals(actor.get("actor_entry_policy", String.class)) + || !action + .mutation() + .authoredSource() + .core() + .canonicalJson() + .equals(actor.get("authored_initial_core_json", String.class)) + || !action + .mutation() + .authoredSource() + .descriptor() + .canonicalJson() + .equals(actor.get("creation_descriptor_json", String.class)) + || !action + .mutation() + .authoredSource() + .descriptor() + .digest() + .equals(actor.get("creation_descriptor_digest", String.class))) throw corruptRoster(); + if (!published.matches(action) || !published.targetNamespace().equals(operationNamespace)) { + if (sourceMismatchIsUnavailable) throw selectedPlayerCreatedActorUnavailable(); + throw corruptRoster(); + } + return creation; + } + + static void requireCanonicalCharacterId(UUID characterId) { + Objects.requireNonNull(characterId, "characterId"); + if (characterId.equals(new UUID(0L, 0L))) throw EntityCharacterCreateBindings.invalid(); + } + + private static RuntimeException selectedPlayerCreatedActorUnavailable() { + return Status.FAILED_PRECONDITION + .withDescription("Selected PLAYER_CREATED character is unavailable") + .asRuntimeException(); + } + + private static RuntimeException corruptRoster() { + return Status.DATA_LOSS + .withDescription("Stored PLAYER_CREATED roster provenance is inconsistent") + .asRuntimeException(); + } + + EntityCharacterCreateTerminal settle(EntityCharacterCreateProofs proof, String abortRequestId) { + outsideTransaction(); + if (abortRequestId != null) EntityCharacterCreateBindings.id(abortRequestId); + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + var action = proof.action(); + UUID tenant = UUID.fromString(action.scope().tenantId()); + UUID namespace = UUID.fromString(action.scope().playableStateNamespaceId()); + UUID account = UUID.fromString(action.target().accountId()); + UUID operation = UUID.fromString(proof.original().getOperationId()); + UUID requestId = UUID.fromString(proof.original().getCreateCharacterRequestId()); + String workloadNamespace = proof.request().getOriginal().getTargetNamespace(); + String scope = action.scope().playableStateScope().name(); + // The selected intake association is actual Entity owner storage, not a numeric ID + // bridge. + var association = + tx.fetchOne( + "SELECT receipt_bytes FROM entity_empty_selected_source_receipt WHERE target_namespace = ? AND intake_request_id = ? FOR KEY SHARE", + workloadNamespace, + proof.entitySource().intakeRequestId()); + if (association == null + || !Arrays.equals( + association.get(0, byte[].class), proof.entitySource().canonicalBytes())) { + throw EntityCharacterCreateBindings.conflict(); + } + tx.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + tenant, + namespace, + scope); + var enrolled = + tx.fetchOne( + "SELECT playable_state_scope FROM entity_playable_state_namespace_scopes WHERE tenant_uuid = ? AND playable_state_namespace_id = ? FOR UPDATE", + tenant, + namespace); + if (enrolled == null || !scope.equals(enrolled.get(0, String.class))) + throw EntityCharacterCreateBindings.conflict(); + tx.execute( + "INSERT INTO entity_character_create_operations (target_namespace, operation_id, create_character_request_id, mutation_digest, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_uuid, canonical_version_id, original_request, original_account, original_account_protection, original_game_session_protection, original_world_protection, entity_source_receipt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + workloadNamespace, + operation, + requestId, + proof.original().getMutationDigest(), + tenant, + namespace, + scope, + account, + UUID.fromString(action.target().versionId()), + proof.request().toByteArray(), + proof.original().toByteArray(), + proof.account().toByteArray(), + proof.gameSession().originalOwnerReadback().toByteArray(), + proof.world().toByteArray(), + proof.entitySource().canonicalBytes()); + var candidates = + tx.fetch( + "SELECT * FROM entity_character_create_operations WHERE (target_namespace = ? AND operation_id = ?) OR (tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? AND create_character_request_id = ?) FOR UPDATE", + workloadNamespace, + operation, + tenant, + namespace, + account, + requestId); + if (candidates.size() != 1) throw EntityCharacterCreateBindings.conflict(); + Record row = candidates.getFirst(); + requireSameProof(row, proof); + if (!"PENDING".equals(row.get("status", String.class))) return terminal(row); + + // Match the existing canonical assignment writer's real tenant row lock before + // zero-roster + // observation, then lock the exact account/namespace roster scope. No identity is + // derived. + tx.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?) ON CONFLICT DO NOTHING", + tenant); + var tenantRow = + tx.fetchOne( + "SELECT entity_tenant_row_id FROM entity_tenant_identities WHERE canonical_tenant_uuid = ? FOR UPDATE", + tenant); + if (tenantRow == null) + throw new IllegalStateException("Entity tenant identity unavailable"); + tx.execute( + "INSERT INTO entity_character_create_roster_guards (tenant_uuid, playable_state_namespace_id, account_uuid) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + tenant, + namespace, + account); + tx.fetchOne( + "SELECT account_uuid FROM entity_character_create_roster_guards WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", + tenant, + namespace, + account); + UUID character = null; + if (abortRequestId == null) { + // Recheck expiry after every potentially blocking lock and immediately before + // allocation. + requireCurrentAuthority(proof); + if (!tx.fetch( + "SELECT character_uuid FROM characters WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", + tenant, + namespace, + account) + .isEmpty()) { + throw Status.FAILED_PRECONDITION + .withDescription("PLAYER_CREATED roster is not empty") + .asRuntimeException(); + } + requireCurrentAuthority(proof); + character = UUID.randomUUID(); + String core = action.mutation().authoredSource().core().canonicalJson(); + int inserted = + tx.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) VALUES (?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL, ?, NULL, NULL, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, 'PLAYER_CREATED', ?, ?, ?) ON CONFLICT DO NOTHING", + character, + account, + tenant, + namespace, + scope, + tenantRow.get(0, Long.class), + new AuthoredCore(core).displayName(), + workloadNamespace, + operation, + core, + action.mutation().authoredSource().descriptor().canonicalJson(), + action.mutation().authoredSource().descriptor().digest()); + if (inserted != 1) + throw Status.FAILED_PRECONDITION + .withDescription("Canonical roster changed before creation") + .asRuntimeException(); + } + var builder = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest(proof.request()) + .setAccountOriginal(proof.original()) + .setOriginalAccountProtection(proof.account().toByteString()) + .setOriginalGameSessionProtection(proof.gameSession().originalOwnerReadback()) + .setOriginalWorldProtection(proof.world().toByteString()) + .setEntityIntakeRequestId(proof.entitySource().intakeRequestId().toString()) + .setEntitySourceReceiptDigest(proof.entitySource().receiptDigest()) + .setOutcome( + character == null + ? EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED + : EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1L) + .setCompletedAt(clock.instant().toString()); + if (character != null) builder.setCharacterId(character.toString()); + if (abortRequestId != null) builder.setAbortRequestId(abortRequestId); + var terminal = builder.build(); + EntityCharacterCreateBindings.requireBound( + terminal, EntityCharacterCreateBindings.MAX_TERMINAL_BYTES); + int updated = + tx.execute( + "UPDATE entity_character_create_operations SET status = ?, terminal_bytes = ?, character_uuid = ? WHERE target_namespace = ? AND operation_id = ? AND status = 'PENDING'", + character == null ? "ABORTED" : "COMMITTED", + terminal.toByteArray(), + character, + workloadNamespace, + operation); + if (updated != 1) + throw new IllegalStateException("Creation terminal serialization failed"); + return terminal; + }); + } + + private void requireCurrentAuthority(EntityCharacterCreateProofs proof) { + // This is Entity's local admission deadline. Remote observation/acquisition timestamps remain + // exact retained owner values and are never compared with Entity's clock. + if (!clock.instant().isBefore(proof.action().expectedVersion().connectScopeExpiresAt())) { + throw Status.FAILED_PRECONDITION + .withDescription("Original creation authority expired; no abort inferred") + .asRuntimeException(); + } + } + + private static void requireSameProof(Record row, EntityCharacterCreateProofs proof) { + if (!Arrays.equals(row.get("original_request", byte[].class), proof.request().toByteArray()) + || !Arrays.equals(row.get("original_account", byte[].class), proof.original().toByteArray()) + || !Arrays.equals( + row.get("original_account_protection", byte[].class), proof.account().toByteArray()) + || !Arrays.equals( + row.get("original_game_session_protection", byte[].class), + proof.gameSession().originalOwnerReadback().toByteArray()) + || !Arrays.equals( + row.get("original_world_protection", byte[].class), proof.world().toByteArray()) + || !Arrays.equals( + row.get("entity_source_receipt", byte[].class), proof.entitySource().canonicalBytes())) + throw EntityCharacterCreateBindings.conflict(); + } + + private static EntityCharacterCreateTerminal terminal(Record row) { + byte[] bytes = row.get("terminal_bytes", byte[].class); + if (bytes == null) + throw Status.UNAVAILABLE + .withDescription("Creation has no definitive terminal") + .asRuntimeException(); + try { + var terminal = EntityCharacterCreateTerminal.parseFrom(bytes); + EntityCharacterCreateBindings.exact(terminal); + EntityCharacterCreateBindings.requireRequest(terminal.getOriginalRequest()); + var action = + EntityCharacterCreateBindings.requireOriginal( + terminal.getOriginalRequest().getOriginal(), terminal.getAccountOriginal()); + if (!action.scope().tenantId().equals(row.get("tenant_uuid", UUID.class).toString()) + || !action + .scope() + .playableStateNamespaceId() + .equals(row.get("playable_state_namespace_id", UUID.class).toString()) + || !action + .scope() + .playableStateScope() + .name() + .equals(row.get("playable_state_scope", String.class)) + || !action.target().accountId().equals(row.get("account_uuid", UUID.class).toString()) + || !action + .target() + .versionId() + .equals(row.get("canonical_version_id", UUID.class).toString()) + || !terminal + .getAccountOriginal() + .getCreateCharacterRequestId() + .equals(row.get("create_character_request_id", UUID.class).toString())) { + throw new IllegalStateException( + "Stored creation target differs from its immutable original"); + } + EntityCharacterCreateBindings.id(terminal.getTerminalId()); + EntityCharacterCreateBindings.instant(terminal.getCompletedAt()); + var source = + net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt + .fromStored(row.get("entity_source_receipt", byte[].class)); + if (!action.scope().targetNamespace().equals(source.targetNamespace()) + || !action.scope().tenantId().equals(source.canonicalTenantId().toString()) + || !action.target().versionId().equals(source.canonicalVersionId().toString()) + || !action + .mutation() + .authoredSource() + .selectedCommitId() + .equals(source.selectedCommitId().toString()) + || !action + .mutation() + .authoredSource() + .selectedCommitDigest() + .equals(source.authorizationBinding().selected().digest()) + || !terminal.getEntityIntakeRequestId().equals(source.intakeRequestId().toString()) + || !terminal.getEntitySourceReceiptDigest().equals(source.receiptDigest())) + throw new IllegalStateException("Corrupt creation source identity"); + boolean committed = + terminal.getOutcome() + == EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED; + boolean aborted = + terminal.getOutcome() + == EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED; + if ((!committed && !aborted) + || terminal.getTerminalFence() != 1L + || !Arrays.equals(bytes, terminal.toByteArray()) + || !Arrays.equals( + row.get("original_request", byte[].class), + terminal.getOriginalRequest().toByteArray()) + || !Arrays.equals( + row.get("original_account", byte[].class), + terminal.getAccountOriginal().toByteArray()) + || !Arrays.equals( + row.get("original_account_protection", byte[].class), + terminal.getOriginalAccountProtection().toByteArray()) + || !Arrays.equals( + row.get("original_game_session_protection", byte[].class), + terminal.getOriginalGameSessionProtection().toByteArray()) + || !Arrays.equals( + row.get("original_world_protection", byte[].class), + terminal.getOriginalWorldProtection().toByteArray()) + || !terminal + .getOriginalRequest() + .getOriginal() + .getTargetNamespace() + .equals(row.get("target_namespace", String.class)) + || !terminal + .getOriginalRequest() + .getOriginal() + .getOperationId() + .equals(row.get("operation_id", UUID.class).toString()) + || !terminal + .getAccountOriginal() + .getMutationDigest() + .equals(row.get("mutation_digest", String.class)) + || !(committed ? "COMMITTED" : "ABORTED").equals(row.get("status", String.class))) + throw new IllegalStateException("Corrupt creation terminal"); + if (committed) { + EntityCharacterCreateBindings.id(terminal.getCharacterId()); + if (!terminal.getAbortRequestId().isEmpty() + || !UUID.fromString(terminal.getCharacterId()) + .equals(row.get("character_uuid", UUID.class))) + throw new IllegalStateException("Corrupt committed actor"); + } else { + EntityCharacterCreateBindings.id(terminal.getAbortRequestId()); + if (!terminal.getCharacterId().isEmpty() || row.get("character_uuid", UUID.class) != null) + throw new IllegalStateException("Corrupt abort terminal"); + } + return terminal; + } catch (InvalidProtocolBufferException | IllegalArgumentException corrupt) { + throw Status.DATA_LOSS + .withDescription("Stored creation terminal is invalid") + .asRuntimeException(); + } + } + + static void requireSameRequest( + CommitProtectedCharacterCreateRequest request, EntityCharacterCreateTerminal terminal) { + if (!request.equals(terminal.getOriginalRequest())) + throw EntityCharacterCreateBindings.conflict(); + } + + static void outsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("CHARACTER_CREATE owns its short Entity transactions"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java new file mode 100644 index 0000000000..0b7490d110 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import java.util.Objects; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionRequest; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.entitymanagement.client.AccountCharacterCreateSourceClient; +import net.firedevops.firemud.entitymanagement.client.WorldCharacterCreateLifecycleClient; +import net.firedevops.firemud.entitymanagement.v1.AbortProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityCharacterCreateTerminalRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalCharacterCreateLifecycleProtectionRequest; + +/** + * Sole Entity allocator and definitive terminal owner. All owner calls finish before the local + * zero-roster/actor/association/terminal transaction; no protection is released here. + */ +public final class EntityCharacterCreateService { + private final String namespace; + private final AccountCharacterCreateSourceClient account; + private final GameSessionCharacterCreateProtectionReader gameSession; + private final WorldCharacterCreateLifecycleClient world; + private final EntityCharacterCreateSource source; + private final EntityCharacterCreateRepository repository; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected repositories are managed dependencies kept internal.") + public EntityCharacterCreateService( + String namespace, + AccountCharacterCreateSourceClient account, + GameSessionCharacterCreateProtectionReader gameSession, + WorldCharacterCreateLifecycleClient world, + EntityCharacterCreateSource source, + EntityCharacterCreateRepository repository) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical namespace required"); + this.namespace = namespace; + this.account = Objects.requireNonNull(account); + this.gameSession = Objects.requireNonNull(gameSession); + this.world = Objects.requireNonNull(world); + this.source = Objects.requireNonNull(source); + this.repository = Objects.requireNonNull(repository); + } + + public EntityCharacterCreateTerminal commit(CommitProtectedCharacterCreateRequest request) { + requireMutation(request); + var existing = repository.replay(request); + if (existing.isPresent()) return existing.orElseThrow(); + return repository.settle(readAllOwners(request), null); + } + + public EntityCharacterCreateTerminal abort(AbortProtectedCharacterCreateRequest request) { + EntityCharacterCreatePeerInterceptor.requirePeer(namespace, true); + EntityCharacterCreateBindings.exact(request); + if (!request.hasCreation()) throw EntityCharacterCreateBindings.invalid(); + EntityCharacterCreateBindings.id(request.getAbortRequestId()); + requireMutation(request.getCreation()); + var existing = repository.replay(request.getCreation()); + var terminal = + existing.orElseGet( + () -> + repository.settle( + readAllOwners(request.getCreation()), request.getAbortRequestId())); + if (terminal.getOutcome() + == EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED + && !request.getAbortRequestId().equals(terminal.getAbortRequestId())) + throw EntityCharacterCreateBindings.conflict(); + // A winning COMMITTED result is returned unchanged: an abort never overwrites it. + return terminal; + } + + public EntityCharacterCreateTerminal read(ReadEntityCharacterCreateTerminalRequest request) { + EntityCharacterCreatePeerInterceptor.requirePeer(namespace, false); + EntityCharacterCreateRepository.outsideTransaction(); + EntityCharacterCreateBindings.exact(request); + if (!request.hasOriginal()) throw EntityCharacterCreateBindings.invalid(); + EntityCharacterCreateBindings.requireOriginalRequest(request.getOriginal()); + if (!namespace.equals(request.getOriginal().getTargetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + return repository + .read(request.getOriginal()) + .orElseThrow( + () -> + Status.NOT_FOUND + .withDescription("No definitive Entity creation terminal; absence is not abort") + .asRuntimeException()); + } + + private void requireMutation(CommitProtectedCharacterCreateRequest request) { + EntityCharacterCreatePeerInterceptor.requirePeer(namespace, true); + EntityCharacterCreateRepository.outsideTransaction(); + EntityCharacterCreateBindings.requireRequest(request); + if (!namespace.equals(request.getOriginal().getTargetNamespace())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private EntityCharacterCreateProofs readAllOwners(CommitProtectedCharacterCreateRequest request) { + var original = account.readOriginal(request.getOriginal()); + var action = EntityCharacterCreateBindings.requireOriginal(request.getOriginal(), original); + var accountRequest = + ReadOriginalCharacterCreateProtectionRequest.newBuilder() + .setOriginal(request.getOriginal()) + .setAccountProtectionId(request.getAccountProtection().getProtectionId()) + .setAccountProtectionFence(request.getAccountProtection().getProtectionFence()) + .build(); + var accountProtection = account.readProtection(accountRequest); + EntityCharacterCreateBindings.requireAccountProtection(request, original, accountProtection); + var gameSessionProtection = + gameSession.readOriginal(accountProtection, request.getGameSessionProtection()); + var worldProtection = + world.readOriginal( + ReadOriginalCharacterCreateLifecycleProtectionRequest.newBuilder() + .setAccountProtection(accountRequest) + .setWorldProtectionId(request.getWorldProtection().getProtectionId()) + .setWorldProtectionFence(request.getWorldProtection().getProtectionFence()) + .build()); + return new EntityCharacterCreateProofs( + request, + original, + accountProtection, + gameSessionProtection, + worldProtection, + source.read(action)); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java new file mode 100644 index 0000000000..dadf2687a5 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import org.jooq.DSLContext; + +/** Correlates published creation provenance with Entity's real immutable selected-source intake. */ +public final class EntityCharacterCreateSource { + private final DSLContext dsl; + private final EntityEmptySelectedSourceIntakeRepository intakes; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext and repository are internal service collaborators.") + public EntityCharacterCreateSource( + DSLContext dsl, EntityEmptySelectedSourceIntakeRepository intakes) { + this.dsl = Objects.requireNonNull(dsl); + this.intakes = Objects.requireNonNull(intakes); + } + + public EntityEmptySelectedSourceIntakeReceipt read(CharacterCreateOperatorAction action) { + var source = action.mutation().authoredSource(); + var association = + dsl.fetchOne( + "SELECT intake_request_id FROM entity_empty_selected_source_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND canonical_version_id = ?", + action.scope().targetNamespace(), + UUID.fromString(action.scope().tenantId()), + UUID.fromString(action.target().versionId())); + if (association == null) + throw new IllegalStateException("Genuine Entity selected source is unavailable"); + var receipt = + intakes + .read(action.scope().targetNamespace(), association.get(0, UUID.class)) + .orElseThrow( + () -> new IllegalStateException("Entity selected source receipt is unavailable")); + var owner = + receipt.inputs().worldInventoryReadEvidence().inventory().publicEvidence().ownerScope(); + if (!action.scope().targetNamespace().equals(receipt.targetNamespace()) + || !action.scope().tenantId().equals(receipt.canonicalTenantId().toString()) + || !action.target().versionId().equals(receipt.canonicalVersionId().toString()) + || !source.selectedCommitId().equals(receipt.selectedCommitId().toString()) + || !source.selectedCommitDigest().equals(receipt.authorizationBinding().selected().digest()) + || !source.worldSourceOperationId().equals(owner.sourceOperationId().toString()) + || !source.worldSourceEvidenceDigest().equals(owner.sourceEvidenceDigest())) { + throw EntityCharacterCreateBindings.conflict(); + } + return receipt; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadService.java new file mode 100644 index 0000000000..95dafeaae5 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadService.java @@ -0,0 +1,192 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; + +/** + * Unregistered Entity composition for persisted PLAYER_CREATED roster discovery. It allocates no + * actor and establishes no selection, admission, activation, retirement, or PKI authority. + */ +public final class EntityPlayerCreatedRosterReadService { + private final EntityCharacterCreateRepository repository; + private final EntityPlayerCreatedRosterSourceClient sourceClient; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected owner client and repository are internal service collaborators.") + public EntityPlayerCreatedRosterReadService( + EntityCharacterCreateRepository repository, + EntityPlayerCreatedRosterSourceClient sourceClient) { + this.repository = Objects.requireNonNull(repository); + this.sourceClient = Objects.requireNonNull(sourceClient); + } + + /** Reads the authenticated source before entering the short Entity owner transaction. */ + public List read( + AuthenticatedAccountSelector account, ReadPlayerCreatedRosterSourceRequest request) { + EntityCharacterCreateRepository.outsideTransaction(); + var source = sourceClient.read(Objects.requireNonNull(request)); + return read(account, source); + } + + /** The source type is constructible only by the mTLS client that actually observed its owner. */ + public List read( + AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source) { + EntityCharacterCreateRepository.outsideTransaction(); + return repository.readPlayerCreatedRoster( + Objects.requireNonNull(account), PublishedIdentity.from(Objects.requireNonNull(source))); + } + + /** Reads the current authenticated source before the short selected-terminal owner read. */ + public EntityCharacterCreateTerminal readSelectedTerminal( + AuthenticatedAccountSelector account, + UUID characterId, + ReadPlayerCreatedRosterSourceRequest request) { + EntityCharacterCreateRepository.outsideTransaction(); + Objects.requireNonNull(account, "account"); + EntityCharacterCreateRepository.requireCanonicalCharacterId(characterId); + var source = sourceClient.read(Objects.requireNonNull(request, "request")); + return readSelectedTerminal(account, characterId, source); + } + + /** The source type is constructible only by the mTLS client that actually observed its owner. */ + EntityCharacterCreateTerminal readSelectedTerminal( + AuthenticatedAccountSelector account, + UUID characterId, + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source) { + return readSelectedTerminal( + account, characterId, PublishedIdentity.from(Objects.requireNonNull(source, "source"))); + } + + EntityCharacterCreateTerminal readSelectedTerminal( + AuthenticatedAccountSelector account, UUID characterId, PublishedIdentity published) { + EntityCharacterCreateRepository.outsideTransaction(); + return repository.readSelectedPlayerCreatedTerminal( + Objects.requireNonNull(account, "account"), + Objects.requireNonNull(published, "published"), + characterId); + } + + /** Account authentication is supplied by the owning caller; this value is only its selector. */ + public record AuthenticatedAccountSelector(UUID accountId) { + public AuthenticatedAccountSelector { + Objects.requireNonNull(accountId, "accountId"); + if (accountId.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException("accountId must be non-nil"); + } + } + + record PublishedIdentity( + String targetNamespace, + UUID tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + UUID playableStateNamespaceId, + UUID canonicalVersionId, + AuthoredInitialActorCoreProjection projection) { + static PublishedIdentity from( + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source) { + var target = source.target(); + var request = source.response().getRequest(); + if (target.entryPolicy() != CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED + || target.playableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || source.authored().projections().size() != 1 + || !request.getCanonicalTenantId().equals(target.tenantUuid().toString()) + || !request.getRealmId().equals(target.realmUuid().toString()) + || !request.getWorldSlug().equals(target.worldSlug()) + || !request.getRealmSlug().equals(target.realmSlug()) + || !request + .getPlayableStateNamespaceId() + .equals(target.playableStateNamespaceId().toString()) + || !request + .getExpectedCanonicalVersionId() + .equals(target.canonicalVersionUuid().toString())) throw invalid(); + return new PublishedIdentity( + request.getTargetNamespace(), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.canonicalVersionUuid(), + source.authored().projections().getFirst()); + } + + boolean matches(CharacterCreateOperatorAction action) { + var scope = action.scope(); + var target = action.target(); + var catalog = action.mutation().catalog(); + var authored = action.mutation().authoredSource(); + return targetNamespace.equals(scope.targetNamespace()) + && tenantId.toString().equals(scope.tenantId()) + && playableStateNamespaceId.toString().equals(scope.playableStateNamespaceId()) + && scope.playableStateScope() + == CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && realmId.toString().equals(target.realmId()) + && worldSlug.equals(target.worldSlug()) + && realmSlug.equals(target.realmSlug()) + && canonicalVersionId.toString().equals(target.versionId()) + && "CHARACTER_CREATE".equals(action.mutation().purpose()) + && "PLAYER_CREATED".equals(action.mutation().entryPolicy()) + && catalog.visible() + && catalog.publicProduction() + && "SHARED".equals(catalog.stateScope()) + && "PLAYER_CREATED".equals(catalog.characterCreationPolicy()) + && tenantId.toString().equals(catalog.tenantId()) + && realmId.toString().equals(catalog.realmId()) + && worldSlug.equals(catalog.worldSlug()) + && realmSlug.equals(catalog.realmSlug()) + && playableStateNamespaceId.toString().equals(catalog.playableStateNamespaceId()) + && authored.schema().equals(AuthoredInitialActorCoreProjection.SCHEMA) + && authored.bindingId().equals(projection.bindingId().toString()) + && authored.bindingDigest().equals(projection.bindingDigest()) + && authored.canonicalTenantId().equals(projection.canonicalTenantId().toString()) + && authored.canonicalVersionId().equals(projection.canonicalVersionId().toString()) + && authored + .worldSourceOperationId() + .equals(projection.worldSourceOperationId().toString()) + && authored.worldSourceEvidenceDigest().equals(projection.worldSourceEvidenceDigest()) + && authored.worldSlug().equals(projection.worldSlug()) + && authored.publicationWorkflowId().equals(projection.publicationWorkflowId()) + && authored.selectedCommitId().equals(projection.selectedCommitId().toString()) + && authored.selectedCommitDigest().equals(projection.selectedCommitDigest()) + && authored.policy().commitId().equals(projection.policy().commitId().toString()) + && authored.policy().revisionId().equals(projection.policy().revisionId().toString()) + && authored.policy().logicalRevisionId().equals(projection.policy().logicalRevisionId()) + && authored.policy().canonicalPolicyJson().equals(projection.policy().canonicalJson()) + && authored.policy().contentDigest().equals(projection.policy().contentDigest()) + && authored.core().canonicalJson().equals(projection.core().canonicalJson()) + && authored.descriptor().canonicalJson().equals(projection.descriptor().canonicalJson()) + && authored.descriptor().digest().equals(projection.descriptor().digest()) + && same(authored.disposition(), projection.disposition()) + && same(authored.safeFeedback(), projection.safeFeedback()); + } + + private static boolean same( + CharacterCreateOperatorAction.Rule expected, + AuthoredInitialActorCoreProjection.RuleDefinition actual) { + return expected.key().equals(actual.key()) + && expected.definitionJson().equals(actual.definitionJson()) + && expected.definitionDigest().equals(actual.definitionDigest()) + && expected.sourceCommitId().equals(actual.sourceCommitId().toString()) + && expected.sourceCommitDigest().equals(actual.sourceCommitDigest()) + && expected.revisionId().equals(actual.revisionId().toString()) + && expected.revisionOrder().equals(actual.revisionOrder()); + } + + private static RuntimeException invalid() { + return EntityCharacterCreateBindings.invalid(); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java new file mode 100644 index 0000000000..143913b310 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java @@ -0,0 +1,144 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CanonicalGameplayRosterRetentionRepository; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered composition for the two non-admitting PLAYER_CREATED roster owner reads. */ +public final class EntityPlayerCreatedRosterService { + private final String namespace; + private final EntityPlayerCreatedRosterSourceClient sourceClient; + private final GameSessionCanonicalGameplayRosterOwnerReadClient originalOwnerClient; + private final EntityPlayerCreatedRosterSnapshotRepository snapshotRepository; + private final CanonicalGameplayRosterRetentionRepository retentionRepository; + private final TransactionOperations transactions; + + public EntityPlayerCreatedRosterService( + String namespace, + EntityPlayerCreatedRosterSourceClient sourceClient, + GameSessionCanonicalGameplayRosterOwnerReadClient originalOwnerClient, + EntityPlayerCreatedRosterSnapshotRepository snapshotRepository, + CanonicalGameplayRosterRetentionRepository retentionRepository, + TransactionOperations transactions) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException( + "Entity Management workload namespace must be one DNS label"); + } + this.namespace = namespace; + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + this.originalOwnerClient = Objects.requireNonNull(originalOwnerClient, "originalOwnerClient"); + this.snapshotRepository = Objects.requireNonNull(snapshotRepository, "snapshotRepository"); + this.retentionRepository = Objects.requireNonNull(retentionRepository, "retentionRepository"); + this.transactions = Objects.requireNonNull(transactions, "transactions"); + } + + /** Retains one local admission, resolves the exact owner operation, then reads current source. */ + public CanonicalPlayerCreatedRosterResponse list(CanonicalPlayerCreatedRosterRequest request) { + requireNoAmbientTransaction(); + CanonicalPlayerCreatedRosterEvidence.requireRequest(request); + UUID admission = + requireTransactionResult( + transactions.execute(status -> retentionRepository.reserveAdmission(request)), + "PLAYER_CREATED admission reservation returned no nonce"); + var expectedOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), + namespace, + request.getExpectedTarget(), + request.getExpectedSource()); + GetCanonicalGameplayRosterReferenceResponse original = + originalOwnerClient.getCanonicalGameplayRosterReference(expectedOriginal); + var checkedOriginal = + CanonicalGameplayRosterReferenceEvidence.requireResponse(expectedOriginal, original); + CanonicalGameplayRosterReferenceEvidence.requireDereference(checkedOriginal); + var retained = + requireTransactionResult( + transactions.execute( + status -> retentionRepository.originalPlayerCreatedReceipt(checkedOriginal)), + "PLAYER_CREATED receipt lookup returned no result"); + if (retained.isPresent()) { + return CanonicalPlayerCreatedRosterEvidence.requireResponse(request, retained.orElseThrow()); + } + if (!checkedOriginal.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED"); + } + + var source = sourceClient.read(sourceRequest(namespace, request.getExpectedTarget())); + return snapshotRepository.capture(request, source, checkedOriginal, admission); + } + + /** Reads the actual current source and original owner before the repository's writable TX. */ + public CanonicalSelectedPlayerCreatedCharacterResponse selected( + CanonicalSelectedPlayerCreatedCharacterRequest request) { + requireNoAmbientTransaction(); + CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest(request); + var source = sourceClient.read(sourceRequest(namespace, request.getExpectedTarget())); + var sourceIdentity = EntityPlayerCreatedRosterSnapshotRepository.sourceIdentity(source); + if (!source.target().toWire().equals(request.getExpectedTarget()) + || !sourceIdentity.equals(request.getExpectedSource())) { + throw new IllegalArgumentException("Current PLAYER_CREATED source binding changed"); + } + var published = EntityPlayerCreatedRosterReadService.PublishedIdentity.from(source); + var expectedOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), + published.targetNamespace(), + request.getExpectedTarget(), + sourceIdentity); + GetCanonicalGameplayRosterReferenceResponse original = + originalOwnerClient.getCanonicalGameplayRosterReference(expectedOriginal); + var checkedOriginal = + CanonicalGameplayRosterReferenceEvidence.requireResponse(expectedOriginal, original); + CanonicalGameplayRosterReferenceEvidence.requireDereference(checkedOriginal); + return snapshotRepository.readSelected(request, source, checkedOriginal); + } + + private static ReadPlayerCreatedRosterSourceRequest sourceRequest( + String namespace, + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget target) { + return ReadPlayerCreatedRosterSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(UUID.randomUUID().toString()) + .setTargetNamespace(namespace) + .setCanonicalTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setWorldSlug(target.getWorldSlug()) + .setRealmSlug(target.getRealmSlug()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .setCatalogRevision(target.getCatalogRevision()) + .setPointerVersion(target.getPointerVersion()) + .setActiveWorldEpoch(target.getActiveWorldEpoch()) + .setCanonicalGameInstanceId(target.getGameInstanceUuid()) + .setExpectedCanonicalVersionId(target.getCanonicalVersionUuid()) + .build(); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "PLAYER_CREATED owner reads require no ambient Entity transaction"); + } + } + + private static T requireTransactionResult(T result, String message) { + return Objects.requireNonNull(result, message); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java new file mode 100644 index 0000000000..5a343b6ac4 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java @@ -0,0 +1,587 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.repository.CanonicalGameplayRosterRetentionRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered owner-local immutable PLAYER_CREATED roster capture. The only source input is an + * AuthenticatedSource produced by Entity's configured mTLS client; this repository performs no + * remote calls and establishes no selection, activation, admission, or PKI authority. + */ +public final class EntityPlayerCreatedRosterSnapshotRepository { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final DSLContext dsl; + private final TransactionTemplate transaction; + + public EntityPlayerCreatedRosterSnapshotRepository( + DSLContext dsl, PlatformTransactionManager transactionManager) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + transaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + transaction.setReadOnly(false); + } + + /** + * Captures the current persisted owner-resolved roster after the authenticated source RPC has + * completed. The original owner fences, local admission nonce, snapshot, and retained receipt + * commit together in one short writable transaction. + */ + public CanonicalPlayerCreatedRosterResponse capture( + CanonicalPlayerCreatedRosterRequest request, + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source, + GetCanonicalGameplayRosterReferenceResponse original, + UUID localAdmission) { + EntityCharacterCreateRepository.outsideTransaction(); + CanonicalPlayerCreatedRosterEvidence.requireRequest(request); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(original, "original"); + requireAdmissionNonce(localAdmission); + + var target = request.getExpectedTarget(); + if (!source.target().toWire().equals(target)) { + throw new IllegalArgumentException("Current PLAYER_CREATED target changed"); + } + var sourceIdentity = sourceIdentity(source); + if (!request.getExpectedSource().equals(sourceIdentity)) { + throw new IllegalArgumentException("Current PLAYER_CREATED source identity changed"); + } + var published = EntityPlayerCreatedRosterReadService.PublishedIdentity.from(source); + var expectedOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), + published.targetNamespace(), + target, + sourceIdentity); + var checkedOriginal = + CanonicalGameplayRosterReferenceEvidence.requireResponse(expectedOriginal, original); + CanonicalGameplayRosterReferenceEvidence.requireDereference(checkedOriginal); + + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account = + new EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector( + UUID.fromString(request.getCanonicalAccountUuid())); + return Objects.requireNonNull( + transaction.execute( + ignored -> { + DSLContext tx = dsl; + var retention = new CanonicalGameplayRosterRetentionRepository(tx); + + // Keep the retention family's established admission-before-snapshot lock order. + retention.requireAdmission(request, localAdmission); + Optional retained = + retention.originalPlayerCreatedReceipt(checkedOriginal); + if (retained.isPresent()) { + Record boundAdmission = + tx.fetchOne( + "SELECT snapshot_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ? AND admission_uuid = ? AND admission_state = 'OPEN' FOR UPDATE", + UUID.fromString(request.getRequestUuid()), + localAdmission); + if (boundAdmission == null + || !UUID.fromString(retained.orElseThrow().getRoster().getSnapshotUuid()) + .equals(boundAdmission.get("snapshot_uuid", UUID.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + } + if (!checkedOriginal.getCanonicalPlayerCreatedRosterReceipt().isEmpty() + && !checkedOriginal + .getCanonicalPlayerCreatedRosterReceipt() + .equals(retained.get().toByteString())) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } + return CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, retained.orElseThrow()); + } + if (!checkedOriginal.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED"); + } + + CanonicalGameplayRosterTarget currentTarget = + CanonicalGameplayRosterTarget.fromWire(target); + lockCreationRoster(tx, currentTarget, account.accountId()); + + List actors = + EntityCharacterCreateRepository.readPlayerCreatedRosterWithinOwnerTransaction( + tx, account, published); + List + wireActors = + actors.stream() + .map(EntityPlayerCreatedRosterSnapshotRepository::wireActor) + .toList(); + String snapshotDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), target, sourceIdentity, wireActors); + + CanonicalPlayerCreatedRosterResponse receipt = + persistOrReuseSnapshot( + tx, + request, + currentTarget, + sourceIdentity, + sourceIdentity.toByteArray(), + wireActors, + snapshotDigest); + + UUID snapshotUuid = UUID.fromString(receipt.getRoster().getSnapshotUuid()); + retention.bindAdmission( + UUID.fromString(request.getRequestUuid()), localAdmission, snapshotUuid); + retention.bindPlayerCreatedOriginal(checkedOriginal, receipt); + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + checkedOriginal.getRequest(), + checkedOriginal.getOwnerFence(), + UUID.fromString(checkedOriginal.getTargetFenceUuid()), + receipt); + return CanonicalPlayerCreatedRosterEvidence.requireResponse(request, receipt); + }), + "PLAYER_CREATED capture transaction returned no receipt"); + } + + /** + * Reads the exact committed terminal for the frozen selected actor without creating a receipt. + */ + public CanonicalSelectedPlayerCreatedCharacterResponse readSelected( + CanonicalSelectedPlayerCreatedCharacterRequest request, + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source, + GetCanonicalGameplayRosterReferenceResponse original) { + EntityCharacterCreateRepository.outsideTransaction(); + CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest(request); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(original, "original"); + + var target = request.getExpectedTarget(); + if (!source.target().toWire().equals(target)) { + throw new IllegalArgumentException("Current PLAYER_CREATED target changed"); + } + var sourceIdentity = sourceIdentity(source); + if (!request.getExpectedSource().equals(sourceIdentity)) { + throw new IllegalArgumentException("Current PLAYER_CREATED source identity changed"); + } + var published = EntityPlayerCreatedRosterReadService.PublishedIdentity.from(source); + var createdRequest = + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setExpectedTarget(target) + .setPlayerExecutionContext( + request.getPlayerExecutionContext().toBuilder().clearCharacterId().build()) + .setExpectedSource(sourceIdentity) + .build(); + CanonicalPlayerCreatedRosterEvidence.requireRequest(createdRequest); + var expectedOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), + published.targetNamespace(), + target, + sourceIdentity); + var checkedOriginal = + CanonicalGameplayRosterReferenceEvidence.requireResponse(expectedOriginal, original); + CanonicalGameplayRosterReferenceEvidence.requireDereference(checkedOriginal); + if (!request.getSelectedCharacterUuid().equals(checkedOriginal.getSelectedCharacterUuid())) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_SELECTION_CHANGED"); + } + var originalRoster = + CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(checkedOriginal); + if (!request + .getExpectedSnapshot() + .getSnapshotUuid() + .equals(originalRoster.getRoster().getSnapshotUuid()) + || !request + .getExpectedSnapshot() + .getSnapshotDigest() + .equals(originalRoster.getRoster().getSnapshotDigest()) + || originalRoster.getRoster().getActorsList().stream() + .filter( + actor -> request.getSelectedCharacterUuid().equals(actor.getCharacterUuid())) + .count() + != 1L) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_SELECTION_CHANGED"); + } + + var account = + new EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector( + UUID.fromString(request.getCanonicalAccountUuid())); + return Objects.requireNonNull( + transaction.execute( + ignored -> { + DSLContext tx = dsl; + var retention = new CanonicalGameplayRosterRetentionRepository(tx); + UUID operation = UUID.fromString(request.getRequestUuid()); + Record admission = + tx.fetchOne( + "SELECT admission_uuid, snapshot_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ? FOR UPDATE", + operation); + if (admission == null) { + throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + } + UUID nonce = admission.get("admission_uuid", UUID.class); + retention.requireAdmission(createdRequest, nonce); + if (!UUID.fromString(request.getExpectedSnapshot().getSnapshotUuid()) + .equals(admission.get("snapshot_uuid", UUID.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); + } + CanonicalPlayerCreatedRosterResponse retained = + retention + .originalPlayerCreatedReceipt(checkedOriginal) + .orElseThrow( + () -> + new IllegalStateException( + "CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED")); + if (!retained.equals(originalRoster)) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } + + CanonicalGameplayRosterTarget currentTarget = + CanonicalGameplayRosterTarget.fromWire(target); + lockCreationRoster(tx, currentTarget, account.accountId()); + List actors = + EntityCharacterCreateRepository.readPlayerCreatedRosterWithinOwnerTransaction( + tx, account, published); + List + wireActors = + actors.stream() + .map(EntityPlayerCreatedRosterSnapshotRepository::wireActor) + .toList(); + String digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), target, sourceIdentity, wireActors); + CanonicalPlayerCreatedRosterResponse readback = + readBackSnapshot( + tx, + createdRequest, + UUID.fromString(request.getExpectedSnapshot().getSnapshotUuid()), + currentTarget, + sourceIdentity, + sourceIdentity.toByteArray(), + wireActors, + digest); + if (!readback + .getRoster() + .getSnapshotDigest() + .equals(request.getExpectedSnapshot().getSnapshotDigest())) { + throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); + } + long selectedCount = + actors.stream() + .filter( + actor -> + actor + .characterUuid() + .toString() + .equals(request.getSelectedCharacterUuid())) + .count(); + if (selectedCount != 1L) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_SELECTION_CHANGED"); + } + + var terminal = + EntityCharacterCreateRepository + .readSelectedPlayerCreatedTerminalWithinOwnerTransaction( + tx, + account, + published, + UUID.fromString(request.getSelectedCharacterUuid())); + var originalCreateRequest = terminal.getOriginalRequest().getOriginal(); + var result = + CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(target) + .setSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(readback.getRoster().getSnapshotUuid()) + .setSnapshotDigest(readback.getRoster().getSnapshotDigest())) + .setSourceIdentity(sourceIdentity) + .setCreationOperationUuid(originalCreateRequest.getOperationId()) + .setMutationDigest(originalCreateRequest.getMutationDigest()) + .setTerminal(terminal) + .build(); + var checkedResult = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, result); + if (!checkedOriginal.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty() + && !CanonicalGameplayRosterReferenceEvidence + .selectedPlayerCreatedCharacterReceipt(checkedOriginal) + .equals(checkedResult)) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } + return checkedResult; + }), + "PLAYER_CREATED selected read returned no terminal"); + } + + private static void lockCreationRoster( + DSLContext tx, CanonicalGameplayRosterTarget target, UUID account) { + UUID tenant = target.tenantUuid(); + UUID namespace = target.playableStateNamespaceId(); + String scope = target.playableStateScope().name(); + + tx.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + tenant, + namespace, + scope); + Record enrollment = + tx.fetchOne( + "SELECT playable_state_scope FROM entity_playable_state_namespace_scopes WHERE tenant_uuid = ? AND playable_state_namespace_id = ? FOR UPDATE", + tenant, + namespace); + if (enrollment == null || !scope.equals(enrollment.get("playable_state_scope", String.class))) { + throw new IllegalStateException("PLAYER_CREATED namespace enrollment changed"); + } + + tx.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?) ON CONFLICT DO NOTHING", + tenant); + Record tenantIdentity = + tx.fetchOne( + "SELECT entity_tenant_row_id FROM entity_tenant_identities WHERE canonical_tenant_uuid = ? FOR UPDATE", + tenant); + if (tenantIdentity == null) { + throw new IllegalStateException("Entity tenant identity unavailable"); + } + + tx.execute( + "INSERT INTO entity_character_create_roster_guards (tenant_uuid, playable_state_namespace_id, account_uuid) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + tenant, + namespace, + account); + Record rosterGuard = + tx.fetchOne( + "SELECT account_uuid FROM entity_character_create_roster_guards WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", + tenant, + namespace, + account); + if (rosterGuard == null || !account.equals(rosterGuard.get("account_uuid", UUID.class))) { + throw new IllegalStateException("PLAYER_CREATED account roster guard unavailable"); + } + } + + private static CanonicalPlayerCreatedRosterResponse persistOrReuseSnapshot( + DSLContext tx, + CanonicalPlayerCreatedRosterRequest request, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + byte[] sourceBytes, + List actors, + String digest) { + Record existing = + tx.fetchOne( + "SELECT snapshot_uuid FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_digest = ? FOR UPDATE", + digest); + UUID snapshotUuid; + if (existing != null) { + snapshotUuid = existing.get("snapshot_uuid", UUID.class); + } else { + snapshotUuid = UUID.randomUUID(); + tx.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshots (snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, canonical_version_uuid, pointer_version, active_world_epoch, published_policy_digest, published_release_bundle_ref, admission_pointer_snapshot_digest, published_owner_proof_digest, playable_state_namespace_uuid, playable_state_scope, entry_policy, publication_evidence_format, canonical_player_created_source_identity, roster_count, construction_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PLAYER_CREATED', 'CANONICAL_UUID_V2', ?, ?, 'BUILDING')", + snapshotUuid, + digest, + UUID.fromString(request.getCanonicalAccountUuid()), + target.tenantUuid(), + target.realmUuid(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid(), + target.catalogRevision(), + target.canonicalVersionUuid(), + target.pointerVersion(), + target.activeWorldEpoch(), + target.publishedPolicyDigest(), + target.publishedReleaseBundleRef(), + target.admissionPointerSnapshotDigest(), + target.publishedOwnerProofDigest(), + target.playableStateNamespaceId(), + target.playableStateScope().name(), + sourceBytes, + (short) actors.size()); + for (int i = 0; i < actors.size(); i++) { + var actor = actors.get(i); + tx.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshot_actors (snapshot_uuid, ordinal_position, character_uuid, display_name, actor_kind) VALUES (?, ?, ?, ?, 'PLAYER')", + snapshotUuid, + (short) i, + UUID.fromString(actor.getCharacterUuid()), + actor.getDisplayName()); + } + int sealed = + tx.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET construction_state = 'SEALED' WHERE snapshot_uuid = ? AND construction_state = 'BUILDING'", + snapshotUuid); + if (sealed != 1) { + throw new IllegalStateException("PLAYER_CREATED roster snapshot did not seal"); + } + } + + return readBackSnapshot(tx, request, snapshotUuid, target, source, sourceBytes, actors, digest); + } + + private static CanonicalPlayerCreatedRosterResponse readBackSnapshot( + DSLContext tx, + CanonicalPlayerCreatedRosterRequest request, + UUID snapshotUuid, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity expectedSource, + byte[] expectedSourceBytes, + List expectedActors, + String expectedDigest) { + Record snapshot = + tx.fetchOne( + "SELECT * FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ? FOR SHARE", + snapshotUuid); + if (snapshot == null + || !expectedDigest.equals(snapshot.get("snapshot_digest", String.class)) + || !UUID.fromString(request.getCanonicalAccountUuid()) + .equals(snapshot.get("canonical_account_uuid", UUID.class)) + || !target.tenantUuid().equals(snapshot.get("tenant_uuid", UUID.class)) + || !target.realmUuid().equals(snapshot.get("realm_uuid", UUID.class)) + || !target.worldSlug().equals(snapshot.get("world_slug", String.class)) + || !target.realmSlug().equals(snapshot.get("realm_slug", String.class)) + || !target.gameInstanceUuid().equals(snapshot.get("game_instance_uuid", UUID.class)) + || target.catalogRevision() != snapshot.get("catalog_revision", Long.class) + || !target.canonicalVersionUuid().equals(snapshot.get("canonical_version_uuid", UUID.class)) + || target.pointerVersion() != snapshot.get("pointer_version", Long.class) + || target.activeWorldEpoch() != snapshot.get("active_world_epoch", Long.class) + || !target + .publishedPolicyDigest() + .equals(snapshot.get("published_policy_digest", String.class)) + || !target + .publishedReleaseBundleRef() + .equals(snapshot.get("published_release_bundle_ref", String.class)) + || !target + .admissionPointerSnapshotDigest() + .equals(snapshot.get("admission_pointer_snapshot_digest", String.class)) + || !target + .publishedOwnerProofDigest() + .equals(snapshot.get("published_owner_proof_digest", String.class)) + || !target + .playableStateNamespaceId() + .equals(snapshot.get("playable_state_namespace_uuid", UUID.class)) + || !target + .playableStateScope() + .name() + .equals(snapshot.get("playable_state_scope", String.class)) + || !"PLAYER_CREATED".equals(snapshot.get("entry_policy", String.class)) + || !"CANONICAL_UUID_V2".equals(snapshot.get("publication_evidence_format", String.class)) + || !Arrays.equals( + expectedSourceBytes, + snapshot.get("canonical_player_created_source_identity", byte[].class)) + || !"SEALED".equals(snapshot.get("construction_state", String.class))) { + throw new IllegalStateException("PLAYER_CREATED roster snapshot readback changed"); + } + + List storedActors = + tx.fetch( + "SELECT ordinal_position, character_uuid, display_name, actor_kind FROM entity_canonical_gameplay_roster_snapshot_actors WHERE snapshot_uuid = ? ORDER BY ordinal_position", + snapshotUuid); + Number persistedCountValue = (Number) snapshot.get("roster_count"); + if (persistedCountValue == null) { + throw new IllegalStateException("PLAYER_CREATED roster snapshot actor count changed"); + } + int persistedCount = persistedCountValue.intValue(); + if (persistedCount != expectedActors.size() || storedActors.size() != expectedActors.size()) { + throw new IllegalStateException("PLAYER_CREATED roster snapshot actor count changed"); + } + var readbackActors = + new java.util.ArrayList< + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor>( + storedActors.size()); + for (int i = 0; i < storedActors.size(); i++) { + Record actor = storedActors.get(i); + var expected = expectedActors.get(i); + UUID characterUuid = actor.get("character_uuid", UUID.class); + if (characterUuid == null) { + throw new IllegalStateException("PLAYER_CREATED roster snapshot actor readback changed"); + } + Number ordinalPosition = (Number) actor.get("ordinal_position"); + if (ordinalPosition == null) { + throw new IllegalStateException("PLAYER_CREATED roster snapshot actor readback changed"); + } + if (ordinalPosition.intValue() != i + || !"PLAYER".equals(actor.get("actor_kind", String.class)) + || !expected.getCharacterUuid().equals(characterUuid.toString()) + || !expected.getDisplayName().equals(actor.get("display_name", String.class))) { + throw new IllegalStateException("PLAYER_CREATED roster snapshot actor readback changed"); + } + readbackActors.add( + wireActor( + new CanonicalGameplayRosterActor( + characterUuid, actor.get("display_name", String.class)))); + } + + var roster = + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSnapshotUuid(snapshotUuid.toString()) + .setSnapshotDigest(expectedDigest) + .setTarget(request.getExpectedTarget()) + .addAllActors(readbackActors) + .build(); + var receipt = + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setRoster(roster) + .setSourceIdentity(expectedSource) + .build(); + CanonicalPlayerCreatedRosterEvidence.requireResponse(request, receipt); + return receipt; + } + + private static net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor wireActor( + CanonicalGameplayRosterActor actor) { + return net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(actor.characterUuid().toString()) + .setDisplayName(actor.displayName()) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build(); + } + + static CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity( + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source) { + if (source.authored().projections().size() != 1) { + throw new IllegalArgumentException("One current authored PLAYER_CREATED projection required"); + } + var projection = source.authored().projections().getFirst(); + var descriptor = source.creationDescriptor(); + return CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(projection.bindingId().toString()) + .setAuthoredBindingDigest(projection.bindingDigest()) + .build()); + } + + private static void requireAdmissionNonce(UUID admission) { + Objects.requireNonNull(admission, "localAdmission"); + if (NIL_UUID.equals(admission)) { + throw new IllegalArgumentException("PLAYER_CREATED admission nonce must be non-nil"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/GameSessionCharacterCreateProtectionReader.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/GameSessionCharacterCreateProtectionReader.java new file mode 100644 index 0000000000..964ae453bd --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/GameSessionCharacterCreateProtectionReader.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; + +/** + * Distinct catalog/pointer/active-target creation protection. Roster-reference, StartSession and + * initial-admission readers cannot implement this contract. No positive production adapter exists. + */ +@FunctionalInterface +public interface GameSessionCharacterCreateProtectionReader { + Readback readOriginal( + ReadOriginalCharacterCreateProtectionResponse accountProtection, + CharacterCreateProtectionReference reference); + + record Readback( + ReadOriginalCharacterCreateProtectionResponse accountProtection, + CharacterCreateProtectionReference reference, + String acquiredAt, + ByteString originalOwnerReadback) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Protobuf messages and ByteString are immutable.") + public Readback { + EntityCharacterCreateBindings.exact(accountProtection); + EntityCharacterCreateBindings.requireReference(reference); + EntityCharacterCreateBindings.instant(acquiredAt); + if (originalOwnerReadback == null + || originalOwnerReadback.isEmpty() + || originalOwnerReadback.size() + > EntityCharacterCreateBindings.MAX_GAME_SESSION_RESPONSE_BYTES) { + throw EntityCharacterCreateBindings.invalid(); + } + } + + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Protobuf messages are immutable.") + public ReadOriginalCharacterCreateProtectionResponse accountProtection() { + return accountProtection; + } + + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Protobuf messages are immutable.") + public CharacterCreateProtectionReference reference() { + return reference; + } + + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "ByteString is immutable.") + public ByteString originalOwnerReadback() { + return originalOwnerReadback; + } + } + + static GameSessionCharacterCreateProtectionReader unavailable() { + return (account, reference) -> { + throw Status.UNAVAILABLE + .withDescription("Genuine Game Session CHARACTER_CREATE owner protection is unavailable") + .asRuntimeException(); + }; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountCharacterCreateSourceClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountCharacterCreateSourceClient.java new file mode 100644 index 0000000000..291e70a8a6 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/AccountCharacterCreateSourceClient.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.entitymanagement.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.CharacterCreateSourceServiceGrpc; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +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.entitymanagement.charactercreate.EntityCharacterCreateBindings; + +/** Unregistered direct same-namespace mTLS read of original Account creation intent and hold. */ +public final class AccountCharacterCreateSourceClient + extends AbstractReloadingBlockingGrpcClient< + CharacterCreateSourceServiceGrpc.CharacterCreateSourceServiceBlockingStub> { + private final String namespace; + + public AccountCharacterCreateSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + EntityManagementSourceClientValidation.requireEntityManagementMtls( + tls, "CHARACTER_CREATE source reads"), + channels, + AccountCharacterCreateSourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + } + + public void init() throws SSLException, IOException { + initOnce( + "Account creation source client is closed", + "Account creation source client is not initialized"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected CharacterCreateSourceServiceGrpc.CharacterCreateSourceServiceBlockingStub buildStub( + ManagedChannel channel) { + return CharacterCreateSourceServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + namespace + "/sa/account-service")); + } + + public ReadOriginalCharacterCreateResponse readOriginal( + ReadOriginalCharacterCreateRequest request) { + requireNoAmbientSql("Independent Account creation source read required"); + EntityCharacterCreateBindings.requireOriginalRequest(request); + if (!namespace.equals(request.getTargetNamespace())) + throw EntityCharacterCreateBindings.invalid(); + var response = + requireInitializedStub("Account creation source client is not initialized") + .withMaxInboundMessageSize( + EntityCharacterCreateBindings.MAX_ACCOUNT_ORIGINAL_RESPONSE_BYTES) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readOriginalCharacterCreate(request); + EntityCharacterCreateBindings.requireOriginal(request, response); + return response; + } + + public ReadOriginalCharacterCreateProtectionResponse readProtection( + ReadOriginalCharacterCreateProtectionRequest request) { + requireNoAmbientSql("Independent Account creation protection read required"); + EntityCharacterCreateBindings.exact(request); + if (!request.hasOriginal() || request.getAccountProtectionFence() <= 0) + throw EntityCharacterCreateBindings.invalid(); + EntityCharacterCreateBindings.requireOriginalRequest(request.getOriginal()); + EntityCharacterCreateBindings.id(request.getAccountProtectionId()); + if (!namespace.equals(request.getOriginal().getTargetNamespace())) + throw EntityCharacterCreateBindings.invalid(); + var response = + requireInitializedStub("Account creation source client is not initialized") + .withMaxInboundMessageSize(EntityCharacterCreateBindings.MAX_ACCOUNT_RESPONSE_BYTES) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readOriginalCharacterCreateProtection(request); + EntityCharacterCreateBindings.requireBound( + response, EntityCharacterCreateBindings.MAX_ACCOUNT_RESPONSE_BYTES); + if (!response.hasOriginal() + || !request.getAccountProtectionId().equals(response.getAccountProtectionId()) + || request.getAccountProtectionFence() != response.getAccountProtectionFence()) + throw EntityCharacterCreateBindings.invalid(); + EntityCharacterCreateBindings.requireOriginal(request.getOriginal(), response.getOriginal()); + return response; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java index a48bcc9dd6..d3a00dc3c1 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java @@ -93,13 +93,24 @@ protected String defaultTarget() { throw new IllegalStateException( "Original roster owner transport requires no ambient transaction"); } - net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.requireRequest( - request); + var checkedRequest = + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.requireRequest( + request); if (!workloadNamespace.equals(request.getTargetNamespace())) { throw new IllegalArgumentException("Original roster selection belongs to another namespace"); } var current = requireInitializedStub("Game Session original roster owner client is not initialized"); + if (net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.target( + checkedRequest) + .getEntryPolicy() + == net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) { + current = + current.withMaxInboundMessageSize( + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .MAX_PLAYER_CREATED_RESPONSE_BYTES); + } var response = current .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCharacterCreateTargetClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCharacterCreateTargetClient.java new file mode 100644 index 0000000000..3ef4235cce --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCharacterCreateTargetClient.java @@ -0,0 +1,159 @@ +package net.firedevops.firemud.entitymanagement.client; + +import com.google.protobuf.InvalidProtocolBufferException; +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +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.entitymanagement.charactercreate.EntityCharacterCreateBindings; +import net.firedevops.firemud.entitymanagement.charactercreate.GameSessionCharacterCreateProtectionReader; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CharacterCreateTargetSnapshot; +import net.firedevops.firemud.gamesession.v1.ReadOriginalCharacterCreateTargetProtectionRequest; + +/** + * Direct authenticated creation-specific Game Session target-protection read, never roster + * evidence. + */ +public final class GameSessionCharacterCreateTargetClient + extends AbstractReloadingBlockingGrpcClient< + CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub> + implements GameSessionCharacterCreateProtectionReader { + private final String namespace; + + public GameSessionCharacterCreateTargetClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + EntityManagementSourceClientValidation.requireEntityManagementMtls( + tls, "CHARACTER_CREATE target reads"), + channels, + GameSessionCharacterCreateTargetClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + } + + public void init() throws SSLException, IOException { + initOnce( + "Game Session creation target client is closed", + "Game Session creation target client is not initialized"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected CharacterCreateTargetServiceGrpc.CharacterCreateTargetServiceBlockingStub buildStub( + ManagedChannel channel) { + return CharacterCreateTargetServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + namespace + "/sa/game-session-service")); + } + + @Override + public Readback readOriginal( + ReadOriginalCharacterCreateProtectionResponse account, + CharacterCreateProtectionReference reference) { + requireNoAmbientSql("Independent Game Session creation protection read required"); + EntityCharacterCreateBindings.exact(account); + EntityCharacterCreateBindings.requireReference(reference); + if (!account.hasOriginal() || !namespace.equals(account.getOriginal().getTargetNamespace())) + throw EntityCharacterCreateBindings.invalid(); + var original = + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(namespace) + .setOperationId(account.getOriginal().getOperationId()) + .setMutationDigest(account.getOriginal().getMutationDigest()) + .build(); + var action = EntityCharacterCreateBindings.requireOriginal(original, account.getOriginal()); + var request = + ReadOriginalCharacterCreateTargetProtectionRequest.newBuilder() + .setAccountProtection( + ReadOriginalCharacterCreateProtectionRequest.newBuilder() + .setOriginal(original) + .setAccountProtectionId(account.getAccountProtectionId()) + .setAccountProtectionFence(account.getAccountProtectionFence())) + .setGameSessionProtectionId(reference.getProtectionId()) + .setGameSessionProtectionFence(reference.getProtectionFence()) + .build(); + var reply = + requireInitializedStub("Game Session creation target client is not initialized") + .withMaxInboundMessageSize( + EntityCharacterCreateBindings.MAX_GAME_SESSION_RESPONSE_BYTES) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readOriginalCharacterCreateTargetProtection(request); + EntityCharacterCreateBindings.requireBound( + reply, EntityCharacterCreateBindings.MAX_GAME_SESSION_RESPONSE_BYTES); + if (!reply.hasAccountProtection() + || !account.equals(reply.getAccountProtection()) + || !reference.getProtectionId().equals(reply.getGameSessionProtectionId()) + || reference.getProtectionFence() != reply.getGameSessionProtectionFence() + || reply.getOriginalTargetEvidence().isEmpty()) + throw EntityCharacterCreateBindings.conflict(); + try { + var snapshot = CharacterCreateTargetSnapshot.parseFrom(reply.getOriginalTargetEvidence()); + EntityCharacterCreateBindings.exact(snapshot); + if (!Arrays.equals(snapshot.toByteArray(), reply.getOriginalTargetEvidence().toByteArray()) + || snapshot.getSchemaVersion() != 1 + || !account.getOriginal().getOriginalAction().equals(snapshot.getOriginalAction()) + || !namespace.equals(snapshot.getTargetNamespace()) + || !original.getOperationId().equals(snapshot.getOperationId()) + || !original.getMutationDigest().equals(snapshot.getMutationDigest()) + || !action.scope().tenantId().equals(snapshot.getCanonicalTenantId()) + || !action.target().realmId().equals(snapshot.getRealmId()) + || !action.target().gameInstanceId().equals(snapshot.getCanonicalGameInstanceId()) + || !action.target().versionId().equals(snapshot.getCanonicalVersionId()) + || !action + .scope() + .playableStateNamespaceId() + .equals(snapshot.getPlayableStateNamespaceId()) + || !action + .expectedVersion() + .catalogRevision() + .equals(Long.toString(snapshot.getCatalogRevision())) + || !action + .expectedVersion() + .pointerVersion() + .equals(Long.toString(snapshot.getPointerVersion())) + || !action + .expectedVersion() + .activeLifecycleEpoch() + .equals(Long.toString(snapshot.getActiveWorldEpoch())) + || !snapshot.getCatalogReceiptDigest().matches("sha256:[0-9a-f]{64}") + || !snapshot.getInitialAdmissionOwnerProofDigest().matches("sha256:[0-9a-f]{64}") + || !snapshot.getAdmissionPointerSnapshotDigest().matches("[0-9a-f]{64}")) + throw EntityCharacterCreateBindings.conflict(); + // This owner request identity is opaque; do not impose UUID shape on its native contract. + if (snapshot.getInitialAdmissionRequestId().isBlank() + || !snapshot + .getInitialAdmissionRequestId() + .equals(snapshot.getInitialAdmissionRequestId().trim())) + throw EntityCharacterCreateBindings.invalid(); + } catch (InvalidProtocolBufferException invalid) { + throw EntityCharacterCreateBindings.invalid(); + } + return new Readback(account, reference, reply.getAcquiredAt(), reply.toByteString()); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/WorldCharacterCreateLifecycleClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/WorldCharacterCreateLifecycleClient.java new file mode 100644 index 0000000000..39f4b6be36 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/WorldCharacterCreateLifecycleClient.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.entitymanagement.client; + +import io.grpc.ManagedChannel; +import java.io.IOException; +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.entitymanagement.charactercreate.EntityCharacterCreateBindings; +import net.firedevops.firemud.worldmanagement.v1.CharacterCreateLifecycleServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.ReadOriginalCharacterCreateLifecycleProtectionRequest; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; + +/** Unregistered direct World owner read; other lifecycle/admission evidence cannot substitute. */ +public final class WorldCharacterCreateLifecycleClient + extends AbstractReloadingBlockingGrpcClient< + CharacterCreateLifecycleServiceGrpc.CharacterCreateLifecycleServiceBlockingStub> { + private final String namespace; + + public WorldCharacterCreateLifecycleClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + EntityManagementSourceClientValidation.requireEntityManagementMtls( + tls, "CHARACTER_CREATE lifecycle reads"), + channels, + WorldCharacterCreateLifecycleClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + } + + public void init() throws SSLException, IOException { + initOnce( + "World creation lifecycle client is closed", + "World creation lifecycle client is not initialized"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getWorldManagementService(); + } + + @Override + protected String defaultTarget() { + return "world-management-service:6565"; + } + + @Override + protected CharacterCreateLifecycleServiceGrpc.CharacterCreateLifecycleServiceBlockingStub + buildStub(ManagedChannel channel) { + return CharacterCreateLifecycleServiceGrpc.newBlockingStub(channel) + .withInterceptors( + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://firemud/ns/" + namespace + "/sa/world-management-service")); + } + + public WorldCharacterCreateLifecycleProtection readOriginal( + ReadOriginalCharacterCreateLifecycleProtectionRequest request) { + requireNoAmbientSql("Independent World creation protection read required"); + EntityCharacterCreateBindings.exact(request); + if (!request.hasAccountProtection() + || !request.getAccountProtection().hasOriginal() + || !namespace.equals(request.getAccountProtection().getOriginal().getTargetNamespace()) + || request.getWorldProtectionFence() <= 0L) throw EntityCharacterCreateBindings.invalid(); + EntityCharacterCreateBindings.id(request.getWorldProtectionId()); + var response = + requireInitializedStub("World creation lifecycle client is not initialized") + .withMaxInboundMessageSize(EntityCharacterCreateBindings.MAX_WORLD_RESPONSE_BYTES) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readOriginalCharacterCreateLifecycleProtection(request); + EntityCharacterCreateBindings.requireBound( + response, EntityCharacterCreateBindings.MAX_WORLD_RESPONSE_BYTES); + if (!response.hasAccountProtection() + || !request.getWorldProtectionId().equals(response.getWorldProtectionId()) + || request.getWorldProtectionFence() != response.getWorldProtectionFence() + || response.getOriginalLifecycleEvidence().isEmpty()) + throw EntityCharacterCreateBindings.invalid(); + EntityCharacterCreateBindings.instant(response.getAcquiredAt()); + return response; + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java index 8a0a58bcbd..02124a9176 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java @@ -8,11 +8,14 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterRecoveryEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRetentionBinding; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterSnapshot; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationResponse; @@ -43,20 +46,31 @@ public CanonicalGameplayRosterRetentionRepository(DSLContext dsl) { public UUID reserveAdmission( net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest request) { + return reserveAdmission(request.requestUuid(), admissionBinding(request), "PRESEEDED_ONLY"); + } + + public UUID reserveAdmission(CanonicalPlayerCreatedRosterRequest request) { + CanonicalPlayerCreatedRosterEvidence.requireRequest(request); + return reserveAdmission( + UUID.fromString(request.getRequestUuid()), admissionBinding(request), "PLAYER_CREATED"); + } + + private UUID reserveAdmission(UUID operation, byte[] binding, String policy) { requireOwnerTransaction(); - requireNoRetirementTransfer(request.requestUuid()); - byte[] binding = admissionBinding(request); + requireNoRetirementTransfer(operation); dsl.execute( - "INSERT INTO entity_canonical_roster_admissions (operation_uuid, admission_uuid, request_binding) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", - request.requestUuid(), + "INSERT INTO entity_canonical_roster_admissions (operation_uuid, admission_uuid, request_binding, entry_policy) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", + operation, UUID.randomUUID(), - binding); + binding, + policy); Record original = dsl.fetchSingle( - "SELECT admission_uuid, request_binding, admission_state FROM entity_canonical_roster_admissions WHERE operation_uuid = ? FOR UPDATE", - request.requestUuid()); - requireNoRetirementTransfer(request.requestUuid()); - if (!Arrays.equals(binding, original.get("request_binding", byte[].class))) { + "SELECT admission_uuid, request_binding, admission_state, entry_policy FROM entity_canonical_roster_admissions WHERE operation_uuid = ? FOR UPDATE", + operation); + requireNoRetirementTransfer(operation); + if (!Arrays.equals(binding, original.get("request_binding", byte[].class)) + || !policy.equals(original.get("entry_policy", String.class))) { throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT"); } if (!"OPEN".equals(original.get("admission_state", String.class))) { @@ -68,17 +82,29 @@ public UUID reserveAdmission( public void requireAdmission( net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest request, UUID nonce) { + requireAdmission(request.requestUuid(), nonce, admissionBinding(request), "PRESEEDED_ONLY"); + } + + public void requireAdmission(CanonicalPlayerCreatedRosterRequest request, UUID nonce) { + CanonicalPlayerCreatedRosterEvidence.requireRequest(request); + requireAdmission( + UUID.fromString(request.getRequestUuid()), + nonce, + admissionBinding(request), + "PLAYER_CREATED"); + } + + private void requireAdmission(UUID operation, UUID nonce, byte[] binding, String policy) { requireOwnerTransaction(); Record original = dsl.fetchOne( - "SELECT request_binding FROM entity_canonical_roster_admissions WHERE operation_uuid = ? " - + "AND admission_uuid = ? AND admission_state = 'OPEN' FOR UPDATE", - request.requestUuid(), + "SELECT request_binding, entry_policy FROM entity_canonical_roster_admissions WHERE operation_uuid = ? AND admission_uuid = ? AND admission_state = 'OPEN' FOR UPDATE", + operation, nonce); - requireNoRetirementTransfer(request.requestUuid()); + requireNoRetirementTransfer(operation); if (original == null - || !Arrays.equals( - admissionBinding(request), original.get("request_binding", byte[].class))) { + || !Arrays.equals(binding, original.get("request_binding", byte[].class)) + || !policy.equals(original.get("entry_policy", String.class))) { throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); } } @@ -101,6 +127,11 @@ public void bindAdmission(UUID operation, UUID nonce, UUID snapshot) { private static byte[] admissionBinding( net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterReadRequest request) { + if (request.expectedTarget().entryPolicy() + != net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy + .PRESEEDED_ONLY) { + throw new IllegalArgumentException("PRESEEDED_ONLY admission request required"); + } return net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest.newBuilder() .setRequestUuid(request.requestUuid().toString()) .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) @@ -112,8 +143,44 @@ private static byte[] admissionBinding( .toByteArray(); } + private static byte[] admissionBinding(CanonicalPlayerCreatedRosterRequest request) { + return CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setExpectedTarget(request.getExpectedTarget()) + .setExpectedSource(request.getExpectedSource()) + .setPlayerExecutionContext( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setSessionId(request.getPlayerExecutionContext().getSessionId())) + .build() + .toByteArray(); + } + + private static boolean playerCreated(GetCanonicalGameplayRosterReferenceRequest request) { + return CanonicalGameplayRosterReferenceEvidence.target(request).getEntryPolicy() + == net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED; + } + + private static String entryPolicy(GetCanonicalGameplayRosterReferenceRequest request) { + return playerCreated(request) ? "PLAYER_CREATED" : "PRESEEDED_ONLY"; + } + private static byte[] admissionBinding(GetCanonicalGameplayRosterReferenceRequest request) { CanonicalGameplayRosterReferenceEvidence.requireRequest(request); + if (playerCreated(request)) { + return admissionBinding( + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(request.getOperationUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setExpectedTarget(CanonicalGameplayRosterReferenceEvidence.target(request)) + .setExpectedSource( + CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity(request)) + .setPlayerExecutionContext( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setSessionId(request.getSessionUuid())) + .build()); + } return net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest.newBuilder() .setRequestUuid(request.getOperationUuid()) .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) @@ -142,15 +209,17 @@ public CanonicalGameplayRosterRecoveryResponse closeAdmission( // The provisional insert and closure commit together. Normal handlers can never observe an // OPEN admission created by this transaction; conflict paths lock the existing nonce first. dsl.execute( - "INSERT INTO entity_canonical_roster_admissions (operation_uuid, admission_uuid, request_binding) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + "INSERT INTO entity_canonical_roster_admissions (operation_uuid, admission_uuid, request_binding, entry_policy) VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", operation, UUID.randomUUID(), - binding); + binding, + entryPolicy(original)); Record admission = dsl.fetchSingle( "SELECT * FROM entity_canonical_roster_admissions WHERE operation_uuid = ? FOR UPDATE", operation); - if (!Arrays.equals(binding, admission.get("request_binding", byte[].class))) { + if (!Arrays.equals(binding, admission.get("request_binding", byte[].class)) + || !entryPolicy(original).equals(admission.get("entry_policy", String.class))) { throw new RecoveryConflictException("CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT"); } String state = admission.get("admission_state", String.class); @@ -169,8 +238,12 @@ public CanonicalGameplayRosterRecoveryResponse closeAdmission( request, CanonicalGameplayRosterRecoveryResponse.parseFrom( admission.get("recovery_response", byte[].class))); - if (!owner.getCanonicalRosterReceipt().isEmpty() - && !owner.getCanonicalRosterReceipt().equals(retained.getCanonicalRosterReceipt())) { + if ((!owner.getCanonicalRosterReceipt().isEmpty() + && !owner.getCanonicalRosterReceipt().equals(retained.getCanonicalRosterReceipt())) + || (!owner.getCanonicalPlayerCreatedRosterReceipt().isEmpty() + && !owner + .getCanonicalPlayerCreatedRosterReceipt() + .equals(retained.getCanonicalPlayerCreatedRosterReceipt()))) { throw new IllegalStateException("CANONICAL_ROSTER_RECOVERY_LOCAL_RECEIPT_MISMATCH"); } return retained; @@ -182,19 +255,31 @@ public CanonicalGameplayRosterRecoveryResponse closeAdmission( if (!"OPEN".equals(state)) { throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); } - var receipt = originalReceipt(owner).orElse(null); + var createdReceipt = + playerCreated(original) ? originalPlayerCreatedReceipt(owner).orElse(null) : null; + var receipt = + playerCreated(original) + ? (createdReceipt == null ? null : createdReceipt.getRoster()) + : originalReceipt(owner).orElse(null); UUID snapshot = admission.get("snapshot_uuid", UUID.class); if ((snapshot == null) != (receipt == null) || (snapshot != null && !snapshot.toString().equals(receipt.getSnapshotUuid()))) { throw new IllegalStateException("CANONICAL_ROSTER_RECOVERY_LOCAL_RECEIPT_MISMATCH"); } var response = - CanonicalGameplayRosterRecoveryEvidence.response( - request, - admission.get("admission_uuid", UUID.class), - owner.getOwnerFence(), - UUID.fromString(owner.getTargetFenceUuid()), - receipt); + playerCreated(original) + ? CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + request, + admission.get("admission_uuid", UUID.class), + owner.getOwnerFence(), + UUID.fromString(owner.getTargetFenceUuid()), + createdReceipt) + : CanonicalGameplayRosterRecoveryEvidence.response( + request, + admission.get("admission_uuid", UUID.class), + owner.getOwnerFence(), + UUID.fromString(owner.getTargetFenceUuid()), + receipt); dsl.execute( "UPDATE entity_canonical_roster_admissions SET admission_state = 'CLOSED', closed_at = clock_timestamp(), " + "minimum_retention_millis = ?, recovery_uuid = ?, recovery_request = ?, recovery_response = ?, " @@ -356,6 +441,8 @@ public Optional originalReceipt( requireOwnerTransaction(); var request = owner.getRequest(); CanonicalGameplayRosterReferenceEvidence.requireResponse(request, owner); + if (playerCreated(request)) + throw new IllegalArgumentException("PRESEEDED_ONLY original receipt required"); UUID operation = CanonicalGameplayRosterReferenceEvidence.uuid(request.getOperationUuid()); dsl.execute( "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", @@ -394,6 +481,107 @@ public Optional originalReceipt( } } + public Optional originalPlayerCreatedReceipt( + GetCanonicalGameplayRosterReferenceResponse owner) { + requireOwnerTransaction(); + var request = owner.getRequest(); + CanonicalGameplayRosterReferenceEvidence.requireResponse(request, owner); + if (!playerCreated(request)) + throw new IllegalArgumentException("PLAYER_CREATED original receipt required"); + UUID operation = UUID.fromString(request.getOperationUuid()); + dsl.execute( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "entity-roster-original:" + operation); + Record retained = + dsl.fetchOne( + "SELECT * FROM entity_canonical_roster_original_selections WHERE operation_uuid = ? FOR UPDATE", + operation); + if (retained == null) return Optional.empty(); + if (!Arrays.equals(request.toByteArray(), retained.get("owner_request", byte[].class)) + || owner.getOwnerFence() != retained.get("owner_fence", Long.class) + || !owner + .getTargetFenceUuid() + .equals(retained.get("owner_target_fence_uuid", UUID.class).toString()) + || !"PLAYER_CREATED".equals(retained.get("entry_policy", String.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT"); + } + try { + var receipt = + CanonicalPlayerCreatedRosterResponse.parseFrom( + retained.get("canonical_player_created_roster_receipt", byte[].class)); + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + request, owner.getOwnerFence(), UUID.fromString(owner.getTargetFenceUuid()), receipt); + if (!owner.getCanonicalPlayerCreatedRosterReceipt().isEmpty() + && !owner.getCanonicalPlayerCreatedRosterReceipt().equals(receipt.toByteString())) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } + return Optional.of(receipt); + } catch (com.google.protobuf.InvalidProtocolBufferException + | IllegalArgumentException invalid) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_INVALID", invalid); + } + } + + /** + * Joins capture's owner transaction and retains the full created source, never a preseeded + * receipt. + */ + public void bindPlayerCreatedOriginal( + GetCanonicalGameplayRosterReferenceResponse owner, + CanonicalPlayerCreatedRosterResponse receipt) { + requireOwnerTransaction(); + var request = owner.getRequest(); + CanonicalGameplayRosterReferenceEvidence.requireResponse(request, owner); + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + request, owner.getOwnerFence(), UUID.fromString(owner.getTargetFenceUuid()), receipt); + UUID operation = UUID.fromString(request.getOperationUuid()); + Record admission = + dsl.fetchOne( + "SELECT * FROM entity_canonical_roster_admissions WHERE operation_uuid = ? AND admission_state = 'OPEN' FOR UPDATE", + operation); + requireNoRetirementTransfer(operation); + if (admission == null + || !"PLAYER_CREATED".equals(admission.get("entry_policy", String.class)) + || !Arrays.equals(admissionBinding(request), admission.get("request_binding", byte[].class)) + || (admission.get("snapshot_uuid", UUID.class) != null + && !admission + .get("snapshot_uuid", UUID.class) + .toString() + .equals(receipt.getRoster().getSnapshotUuid()))) { + throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + } + var roster = receipt.getRoster(); + var binding = + new CanonicalGameplayRosterRetentionBinding( + UUID.fromString(roster.getCanonicalAccountUuid()), + new net.firedevops.firemud.entitymanagement.service + .CanonicalGameplayRosterSnapshotReference( + UUID.fromString(roster.getSnapshotUuid()), roster.getSnapshotDigest()), + net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget.fromWire( + roster.getTarget())); + lock(binding); + var source = + dsl.fetchSingle( + "SELECT canonical_player_created_source_identity FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid()); + if (!Arrays.equals( + request.getCanonicalPlayerCreatedSourceIdentity().toByteArray(), + source.get(0, byte[].class))) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT"); + } + acquire(binding, operation, operation, ReferenceKind.ORIGINAL_SELECTION); + dsl.execute( + "INSERT INTO entity_canonical_roster_original_selections " + + "(operation_uuid, owner_request, owner_fence, owner_target_fence_uuid, snapshot_uuid, snapshot_digest, canonical_player_created_roster_receipt, entry_policy) VALUES (?, ?, ?, ?, ?, ?, ?, 'PLAYER_CREATED')", + operation, + request.toByteArray(), + owner.getOwnerFence(), + UUID.fromString(owner.getTargetFenceUuid()), + binding.snapshot().snapshotUuid(), + binding.snapshot().snapshotDigest(), + receipt.toByteArray()); + } + /** Must join snapshot capture's transaction; a failed reference bind rolls the capture back. */ public void bindOriginal( GetCanonicalGameplayRosterReferenceResponse owner, CanonicalGameplayRosterSnapshot snapshot) { @@ -493,7 +681,7 @@ public boolean observeRetirement( policy) { CanonicalGameplayRosterReferenceEvidence.requireResponse(candidate.ownerRequest(), proof); CanonicalGameplayRosterReferenceEvidence.requireRetirement(proof); - var receipt = CanonicalGameplayRosterReferenceEvidence.receipt(proof); + var receipt = CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(proof); if (!candidate.binding().snapshot().snapshotUuid().toString().equals(receipt.getSnapshotUuid()) || !candidate.binding().snapshot().snapshotDigest().equals(receipt.getSnapshotDigest())) { throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_SNAPSHOT_MISMATCH"); @@ -549,7 +737,10 @@ public boolean observeRetirement( .parseFrom(original.get("owner_request", byte[].class)); if (!request.getCanonicalAccountUuid().equals(proof.getRequest().getCanonicalAccountUuid()) || !request.getTargetNamespace().equals(proof.getRequest().getTargetNamespace()) - || !request.getCanonicalTarget().equals(proof.getRequest().getCanonicalTarget())) { + || !request.getCanonicalTarget().equals(proof.getRequest().getCanonicalTarget()) + || !request + .getCanonicalPlayerCreatedSourceIdentity() + .equals(proof.getRequest().getCanonicalPlayerCreatedSourceIdentity())) { return false; } } catch (com.google.protobuf.InvalidProtocolBufferException invalid) { @@ -696,7 +887,7 @@ private void lockSnapshotAdmissions(UUID snapshot) { private void queueBoundRetirementTransfers( UUID snapshot, GetCanonicalGameplayRosterReferenceResponse proof, long minimum) { CanonicalGameplayRosterReferenceEvidence.requireRetirement(proof); - var roster = CanonicalGameplayRosterReferenceEvidence.receipt(proof); + var roster = CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(proof); if (!snapshot.toString().equals(roster.getSnapshotUuid())) { throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_SNAPSHOT_MISMATCH"); } @@ -748,6 +939,7 @@ private void queueRetirementTransfer( if (!closed.getRequest().getOriginalSelection().equals(original) || !closed.getAdmissionUuid().equals(admission.toString()) || !closed.getCanonicalRosterReceipt().isEmpty() + || !closed.getCanonicalPlayerCreatedRosterReceipt().isEmpty() || closed.getOwnerFence() != ownerFence || !closed.getTargetFenceUuid().equals(targetFence.toString())) { throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_CLOSURE_MISMATCH"); @@ -762,6 +954,7 @@ private void queueRetirementTransfer( || !admission.equals(retained.get("admission_uuid", UUID.class)) || !Objects.equals(snapshot, retained.get("snapshot_uuid", UUID.class)) || !Objects.equals(snapshotDigest, retained.get("snapshot_digest", String.class)) + || !entryPolicy(original).equals(retained.get("entry_policy", String.class)) || ownerFence != retained.get("owner_fence", Long.class) || !targetFence.equals(retained.get("target_fence_uuid", UUID.class)) || !Arrays.equals( @@ -791,8 +984,8 @@ private void queueRetirementTransfer( proof); dsl.execute( "INSERT INTO entity_canonical_roster_retirement_transfers " - + "(observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, closed_admission_receipt, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state, observed_retirement, acknowledgement_request, request_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + + "(observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, closed_admission_receipt, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state, observed_retirement, acknowledgement_request, request_digest, entry_policy) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", observation, UUID.fromString(original.getOperationUuid()), original.toByteArray(), @@ -806,7 +999,8 @@ private void queueRetirementTransfer( proof == null ? "WAITING_RETIREMENT" : "PENDING_ACK", proof == null ? null : proof.toByteArray(), request == null ? null : request.toByteArray(), - request == null ? null : CanonicalGameplayRosterRetirementEvidence.requestDigest(request)); + request == null ? null : CanonicalGameplayRosterRetirementEvidence.requestDigest(request), + entryPolicy(original)); } private static CanonicalGameplayRosterRetirementAcknowledgementRequest acknowledgementRequest( @@ -874,6 +1068,9 @@ public java.util.List retirementTransfers(UUID after, int li GetCanonicalGameplayRosterReferenceRequest.parseFrom( row.get("original_request", byte[].class)); CanonicalGameplayRosterReferenceEvidence.requireRequest(original); + if (!entryPolicy(original).equals(row.get("entry_policy", String.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); + } if (!original .getOperationUuid() .equals(row.get("operation_uuid", UUID.class).toString())) { @@ -890,6 +1087,7 @@ public java.util.List retirementTransfers(UUID after, int li .getAdmissionUuid() .equals(row.get("admission_uuid", UUID.class).toString()) || !closed.getCanonicalRosterReceipt().isEmpty() + || !closed.getCanonicalPlayerCreatedRosterReceipt().isEmpty() || closed.getOwnerFence() != row.get("owner_fence", Long.class) || !closed .getTargetFenceUuid() @@ -1274,9 +1472,10 @@ private void lock(CanonicalGameplayRosterRetentionBinding binding) { } dsl.execute( "INSERT INTO entity_canonical_roster_retention_lifecycle " - + "(snapshot_uuid, snapshot_digest) VALUES (?, ?) ON CONFLICT DO NOTHING", + + "(snapshot_uuid, snapshot_digest, entry_policy) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", binding.snapshot().snapshotUuid(), - binding.snapshot().snapshotDigest()); + binding.snapshot().snapshotDigest(), + target.entryPolicy().name()); dsl.fetchSingle( "SELECT snapshot_uuid FROM entity_canonical_roster_retention_lifecycle " + "WHERE snapshot_uuid = ? AND snapshot_digest = ? FOR UPDATE", diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java index 4f950f4f2c..d21b371fe7 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java @@ -17,6 +17,10 @@ public final class CanonicalGameplayRosterPeerInterceptor implements ServerInter "entity_management.v1.CanonicalGameplayRosterService/ListPreseededRoster"; public static final String SELECTED_ASSIGNMENT_METHOD_NAME = "entity_management.v1.CanonicalGameplayRosterService/ReadSelectedPreseededAssignment"; + public static final String PLAYER_CREATED_METHOD_NAME = + "entity_management.v1.CanonicalGameplayRosterService/ListPlayerCreatedRoster"; + public static final String SELECTED_PLAYER_CREATED_METHOD_NAME = + "entity_management.v1.CanonicalGameplayRosterService/ReadSelectedPlayerCreatedCharacter"; public static final String RECOVERY_METHOD_NAME = "entity_management.v1.CanonicalGameplayRosterRecoveryService/RecoverOriginalSelection"; private static final Context.Key VERIFIED_GAME_SESSION_PEER = @@ -38,6 +42,8 @@ public ServerCall.Listener interceptCall( String methodName = call.getMethodDescriptor().getFullMethodName(); if (!METHOD_NAME.equals(methodName) && !SELECTED_ASSIGNMENT_METHOD_NAME.equals(methodName) + && !PLAYER_CREATED_METHOD_NAME.equals(methodName) + && !SELECTED_PLAYER_CREATED_METHOD_NAME.equals(methodName) && !RECOVERY_METHOD_NAME.equals(methodName)) { return next.startCall(call, headers); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java index b6563c59ca..e0998f9778 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java @@ -2,6 +2,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -10,6 +11,8 @@ import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterService; import net.firedevops.firemud.entitymanagement.security.CanonicalGameplayRosterPeerInterceptor; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; @@ -30,6 +33,10 @@ import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget.Builder; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.entitymanagement.validation.CanonicalEntitySourceValues; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; @@ -54,24 +61,84 @@ public final class CanonicalGameplayRosterGrpcAdapter "SELECTED_PRESEEDED_ASSIGNMENT_OWNER_TARGET_MISMATCH", "SELECTED_PRESEEDED_ASSIGNMENT_NOT_IN_EXPECTED_SNAPSHOT", "SELECTED_PRESEEDED_ASSIGNMENT_UNAVAILABLE", - "SELECTED_PRESEEDED_ASSIGNMENT_RECEIPT_MISMATCH"); + "SELECTED_PRESEEDED_ASSIGNMENT_RECEIPT_MISMATCH", + "CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED", + "CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED", + "CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT", + "CANONICAL_ROSTER_ORIGINAL_SELECTION_CHANGED", + "CANONICAL_ROSTER_SNAPSHOT_STALE"); private final CanonicalGameplayRosterService rosterService; private final CanonicalGameplayRosterSelectedAssignmentService selectedAssignmentService; + private final EntityPlayerCreatedRosterService playerCreatedRosterService; private final MeterRegistry meterRegistry; + public CanonicalGameplayRosterGrpcAdapter( + CanonicalGameplayRosterService rosterService, + CanonicalGameplayRosterSelectedAssignmentService selectedAssignmentService, + MeterRegistry meterRegistry) { + this(rosterService, selectedAssignmentService, null, meterRegistry); + } + @SuppressFBWarnings( value = "EI_EXPOSE_REP2", justification = "Injected services and meter registry remain internal to the gRPC adapter.") public CanonicalGameplayRosterGrpcAdapter( CanonicalGameplayRosterService rosterService, CanonicalGameplayRosterSelectedAssignmentService selectedAssignmentService, + EntityPlayerCreatedRosterService playerCreatedRosterService, MeterRegistry meterRegistry) { this.rosterService = rosterService; this.selectedAssignmentService = selectedAssignmentService; + this.playerCreatedRosterService = playerCreatedRosterService; this.meterRegistry = meterRegistry; } + @Override + @Timed(value = "entityGrpc.canonicalGameplayRoster.listPlayerCreated") + public void listPlayerCreatedRoster( + CanonicalPlayerCreatedRosterRequest request, + StreamObserver responseObserver) { + CanonicalPlayerCreatedRosterResponse response; + try { + requireTrustedPeer(); + CanonicalPlayerCreatedRosterEvidence.requireRequest(request); + if (playerCreatedRosterService == null) throw new PlayerCreatedRosterUnavailableException(); + response = + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, playerCreatedRosterService.list(request)); + } catch (Exception failure) { + responseObserver.onError( + toPlayerCreatedStatus(failure, "CanonicalGameplayRoster.ListPlayerCreatedRoster")); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + + @Override + @Timed(value = "entityGrpc.canonicalGameplayRoster.readSelectedPlayerCreated") + public void readSelectedPlayerCreatedCharacter( + CanonicalSelectedPlayerCreatedCharacterRequest request, + StreamObserver responseObserver) { + CanonicalSelectedPlayerCreatedCharacterResponse response; + try { + requireTrustedPeer(); + CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest(request); + if (playerCreatedRosterService == null) throw new PlayerCreatedRosterUnavailableException(); + response = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( + request, playerCreatedRosterService.selected(request)); + } catch (Exception failure) { + responseObserver.onError( + toPlayerCreatedStatus( + failure, "CanonicalGameplayRoster.ReadSelectedPlayerCreatedCharacter")); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + @Override @Timed(value = "entityGrpc.canonicalGameplayRoster.listPreseeded") public void listPreseededRoster( @@ -277,6 +344,11 @@ private RuntimeException toStatus(Exception failure, String operation) { .withDescription("Authenticated Game Session peer required") .asRuntimeException(); } + if (failure instanceof PlayerCreatedRosterUnavailableException) { + return Status.UNAVAILABLE + .withDescription("PLAYER_CREATED roster owner is unavailable") + .asRuntimeException(); + } if (failure instanceof AdminAuthorizationException) { return Status.PERMISSION_DENIED .withDescription("Trusted Game Session caller required") @@ -310,6 +382,31 @@ private RuntimeException toStatus(Exception failure, String operation) { return Status.INTERNAL.withDescription("Internal error").asRuntimeException(); } + private RuntimeException toPlayerCreatedStatus(Exception failure, String operation) { + if (failure instanceof StatusRuntimeException grpcFailure) { + return switch (grpcFailure.getStatus().getCode()) { + case INVALID_ARGUMENT -> + Status.INVALID_ARGUMENT + .withDescription("Request is malformed or inconsistent") + .asRuntimeException(); + case FAILED_PRECONDITION -> + Status.FAILED_PRECONDITION + .withDescription("Request precondition is not satisfied") + .asRuntimeException(); + case UNAVAILABLE -> + Status.UNAVAILABLE + .withDescription("Owner evidence is unavailable") + .asRuntimeException(); + case RESOURCE_EXHAUSTED -> + Status.RESOURCE_EXHAUSTED + .withDescription("PLAYER_CREATED roster exceeds its bounded size") + .asRuntimeException(); + default -> toStatus(failure, operation); + }; + } + return toStatus(failure, operation); + } + private CanonicalGameplayRosterResponse toResponse(CanonicalGameplayRosterSnapshot snapshot) { CanonicalGameplayRosterResponse.Builder response = CanonicalGameplayRosterResponse.newBuilder() @@ -388,4 +485,8 @@ static CanonicalGameplayRosterSelectedAssignmentResponse toSelectedAssignmentRes private static final class UnauthenticatedPeerException extends RuntimeException { private static final long serialVersionUID = 1L; } + + private static final class PlayerCreatedRosterUnavailableException extends RuntimeException { + private static final long serialVersionUID = 1L; + } } diff --git a/services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql b/services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql new file mode 100644 index 0000000000..e003c531eb --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql @@ -0,0 +1,214 @@ +-- New canonical creation stores the authored generic core. Legacy RPG values remain untouched. +ALTER TABLE characters ALTER COLUMN account_id DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN playable_state_key DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN level DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN experience DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN strength DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN agility DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN intelligence DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN stamina DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN health DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN mana DROP NOT NULL; +ALTER TABLE characters ALTER COLUMN body_layout_key DROP NOT NULL; +ALTER TABLE characters ADD COLUMN creation_target_namespace VARCHAR(63); +ALTER TABLE characters ADD COLUMN creation_operation_id UUID; +ALTER TABLE characters ADD COLUMN actor_entry_policy VARCHAR(32); +ALTER TABLE characters ADD COLUMN authored_initial_core_json TEXT; +ALTER TABLE characters ADD COLUMN creation_descriptor_json TEXT; +ALTER TABLE characters ADD COLUMN creation_descriptor_digest VARCHAR(71); + +CREATE TABLE entity_character_create_roster_guards ( + tenant_uuid UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + account_uuid UUID NOT NULL, + PRIMARY KEY (tenant_uuid, playable_state_namespace_id, account_uuid), + FOREIGN KEY (tenant_uuid, playable_state_namespace_id) + REFERENCES entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id) +); + +CREATE TABLE entity_character_create_operations ( + target_namespace VARCHAR(63) NOT NULL, + operation_id UUID NOT NULL, + create_character_request_id UUID NOT NULL, + mutation_digest VARCHAR(64) NOT NULL, + tenant_uuid UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(40) NOT NULL, + account_uuid UUID NOT NULL, + canonical_version_id UUID NOT NULL, + original_request BYTEA NOT NULL CHECK (octet_length(original_request) BETWEEN 1 AND 16384), + original_account BYTEA NOT NULL CHECK (octet_length(original_account) BETWEEN 1 AND 37748736), + original_account_protection BYTEA NOT NULL CHECK (octet_length(original_account_protection) BETWEEN 1 AND 41943040), + original_game_session_protection BYTEA NOT NULL CHECK (octet_length(original_game_session_protection) BETWEEN 1 AND 50331648), + original_world_protection BYTEA NOT NULL CHECK (octet_length(original_world_protection) BETWEEN 1 AND 50331648), + entity_source_receipt BYTEA NOT NULL CHECK (octet_length(entity_source_receipt) BETWEEN 1 AND 83886080), + status VARCHAR(16) NOT NULL DEFAULT 'PENDING', + terminal_bytes BYTEA, + character_uuid UUID, + PRIMARY KEY (target_namespace, operation_id), + UNIQUE (tenant_uuid, playable_state_namespace_id, account_uuid, create_character_request_id), + UNIQUE (character_uuid), + FOREIGN KEY (target_namespace, tenant_uuid, canonical_version_id) + REFERENCES entity_empty_selected_source_association + (target_namespace, canonical_tenant_id, canonical_version_id), + FOREIGN KEY (tenant_uuid, playable_state_namespace_id, playable_state_scope) + REFERENCES entity_playable_state_namespace_scopes + (tenant_uuid, playable_state_namespace_id, playable_state_scope), + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + CHECK (operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND create_character_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND account_uuid <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK ((status = 'PENDING' AND terminal_bytes IS NULL AND character_uuid IS NULL) + OR (status = 'COMMITTED' AND terminal_bytes IS NOT NULL + AND octet_length(terminal_bytes) BETWEEN 1 AND 201326592 AND character_uuid IS NOT NULL) + OR (status = 'ABORTED' AND terminal_bytes IS NOT NULL + AND octet_length(terminal_bytes) BETWEEN 1 AND 201326592 AND character_uuid IS NULL)) +); + +/* [jooq ignore start] */ +ALTER TABLE characters ADD CONSTRAINT fk_character_creation_operation + FOREIGN KEY (creation_target_namespace, creation_operation_id) + REFERENCES entity_character_create_operations (target_namespace, operation_id) + DEFERRABLE INITIALLY DEFERRED; +ALTER TABLE entity_character_create_operations ADD CONSTRAINT fk_creation_terminal_character + FOREIGN KEY (character_uuid) REFERENCES characters (character_uuid) + DEFERRABLE INITIALLY DEFERRED; + +ALTER TABLE characters ADD CONSTRAINT ck_character_created_core CHECK ( + (actor_entry_policy IS NULL AND creation_target_namespace IS NULL + AND creation_operation_id IS NULL AND authored_initial_core_json IS NULL + AND creation_descriptor_json IS NULL AND creation_descriptor_digest IS NULL + AND account_id IS NOT NULL AND playable_state_key IS NOT NULL + AND level IS NOT NULL AND experience IS NOT NULL AND strength IS NOT NULL + AND agility IS NOT NULL AND intelligence IS NOT NULL AND stamina IS NOT NULL + AND health IS NOT NULL AND mana IS NOT NULL AND body_layout_key IS NOT NULL) + OR (actor_entry_policy = 'PLAYER_CREATED' AND creation_target_namespace IS NOT NULL + AND creation_operation_id IS NOT NULL AND actor_identity_status = 'OWNER_RESOLVED' + AND account_id IS NULL AND playable_state_key IS NULL + AND level IS NULL AND experience IS NULL AND strength IS NULL AND agility IS NULL + AND intelligence IS NULL AND stamina IS NULL AND health IS NULL AND mana IS NULL + AND body_layout_key IS NULL AND authored_initial_core_json IS NOT NULL + AND creation_descriptor_json IS NOT NULL + AND creation_descriptor_digest IS NOT NULL + AND creation_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND name = authored_initial_core_json::JSONB ->> 'displayName') +); + +CREATE FUNCTION protect_entity_character_create_operation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.status <> 'PENDING' OR NEW.status NOT IN ('COMMITTED', 'ABORTED') + OR (to_jsonb(NEW) - 'status' - 'terminal_bytes' - 'character_uuid') + IS DISTINCT FROM (to_jsonb(OLD) - 'status' - 'terminal_bytes' - 'character_uuid') THEN + RAISE EXCEPTION 'CHARACTER_CREATE intent and terminal are immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_entity_character_create_operation_immutable + BEFORE UPDATE ON entity_character_create_operations FOR EACH ROW + EXECUTE FUNCTION protect_entity_character_create_operation(); +CREATE TRIGGER trg_entity_character_create_operation_no_removal + BEFORE DELETE OR TRUNCATE ON entity_character_create_operations FOR EACH STATEMENT + EXECUTE FUNCTION reject_entity_assignment_history_removal(); + +CREATE FUNCTION protect_entity_created_actor() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF OLD.actor_entry_policy = 'PLAYER_CREATED' THEN + RAISE EXCEPTION 'CHARACTER_CREATE committed actor is retained' USING ERRCODE = '23514'; + END IF; + RETURN OLD; + END IF; + IF OLD.actor_entry_policy = 'PLAYER_CREATED' AND + (NEW.character_uuid, NEW.account_uuid, NEW.tenant_uuid, NEW.tenant_id, NEW.playable_state_namespace_id, + NEW.playable_state_scope, NEW.creation_target_namespace, NEW.creation_operation_id, + NEW.actor_entry_policy, NEW.authored_initial_core_json, NEW.creation_descriptor_json, + NEW.creation_descriptor_digest, NEW.name) + IS DISTINCT FROM + (OLD.character_uuid, OLD.account_uuid, OLD.tenant_uuid, OLD.tenant_id, OLD.playable_state_namespace_id, + OLD.playable_state_scope, OLD.creation_target_namespace, OLD.creation_operation_id, + OLD.actor_entry_policy, OLD.authored_initial_core_json, OLD.creation_descriptor_json, + OLD.creation_descriptor_digest, OLD.name) THEN + RAISE EXCEPTION 'CHARACTER_CREATE authored identity/provenance is immutable' USING ERRCODE = '23514'; + END IF; + IF OLD.actor_entry_policy IS NULL AND NEW.actor_entry_policy IS NOT NULL THEN + RAISE EXCEPTION 'Retained actors cannot be relabelled PLAYER_CREATED' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_entity_created_actor_immutable BEFORE UPDATE OR DELETE ON characters + FOR EACH ROW EXECUTE FUNCTION protect_entity_created_actor(); +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +-- A terminal and its actor association must settle together, including direct SQL writers. +CREATE FUNCTION validate_entity_character_create_actor_terminal() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + operation_row entity_character_create_operations%ROWTYPE; + actor_row characters%ROWTYPE; +BEGIN + IF TG_TABLE_NAME = 'characters' THEN + IF NEW.actor_entry_policy IS DISTINCT FROM 'PLAYER_CREATED' THEN RETURN NEW; END IF; + SELECT * INTO operation_row FROM entity_character_create_operations + WHERE target_namespace = NEW.creation_target_namespace AND operation_id = NEW.creation_operation_id; + actor_row := NEW; + ELSE + SELECT * INTO operation_row FROM entity_character_create_operations + WHERE target_namespace = NEW.target_namespace AND operation_id = NEW.operation_id; + IF operation_row.status = 'PENDING' THEN + RAISE EXCEPTION 'CHARACTER_CREATE cannot commit a nonterminal operation' USING ERRCODE = '23514'; + END IF; + IF operation_row.status = 'ABORTED' THEN + IF EXISTS (SELECT 1 FROM characters WHERE creation_target_namespace = NEW.target_namespace + AND creation_operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'ABORTED CHARACTER_CREATE has an actor' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + SELECT * INTO actor_row FROM characters WHERE character_uuid = operation_row.character_uuid; + END IF; + IF operation_row.status IS DISTINCT FROM 'COMMITTED' + OR actor_row.actor_entry_policy IS DISTINCT FROM 'PLAYER_CREATED' + OR (actor_row.character_uuid, actor_row.tenant_uuid, actor_row.account_uuid, + actor_row.playable_state_namespace_id, actor_row.playable_state_scope, + actor_row.creation_target_namespace, actor_row.creation_operation_id) + IS DISTINCT FROM + (operation_row.character_uuid, operation_row.tenant_uuid, operation_row.account_uuid, + operation_row.playable_state_namespace_id, operation_row.playable_state_scope, + operation_row.target_namespace, operation_row.operation_id) THEN + RAISE EXCEPTION 'CHARACTER_CREATE terminal differs from its canonical actor association' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE CONSTRAINT TRIGGER trg_entity_created_actor_terminal + AFTER INSERT OR UPDATE ON characters DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION validate_entity_character_create_actor_terminal(); +CREATE CONSTRAINT TRIGGER trg_entity_creation_terminal_actor + AFTER INSERT OR UPDATE ON entity_character_create_operations DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION validate_entity_character_create_actor_terminal(); + +CREATE FUNCTION protect_entity_character_create_roster_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'CHARACTER_CREATE roster serialization identity is retained' + USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER trg_entity_creation_roster_guard_immutable + BEFORE UPDATE OR DELETE OR TRUNCATE ON entity_character_create_roster_guards + FOR EACH STATEMENT EXECUTE FUNCTION protect_entity_character_create_roster_guard(); + +CREATE FUNCTION protect_entity_created_actor_truncate() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM characters WHERE actor_entry_policy = 'PLAYER_CREATED') THEN + RAISE EXCEPTION 'CHARACTER_CREATE committed actors are retained' USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; +CREATE TRIGGER trg_entity_created_actor_no_truncate BEFORE TRUNCATE ON characters + FOR EACH STATEMENT EXECUTE FUNCTION protect_entity_created_actor_truncate(); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql b/services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql new file mode 100644 index 0000000000..1de806bf4d --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql @@ -0,0 +1,157 @@ +-- Extend the existing sealed-roster family; published preseeded migrations remain unchanged. +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD COLUMN canonical_player_created_source_identity BYTEA; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + DROP CONSTRAINT ck_entity_canonical_roster_policy; +ALTER TABLE entity_canonical_gameplay_roster_snapshots + ADD CONSTRAINT ck_entity_canonical_roster_policy CHECK ( + (entry_policy = 'PRESEEDED_ONLY' AND canonical_player_created_source_identity IS NULL) + OR (entry_policy = 'PLAYER_CREATED' AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' + AND publication_evidence_format = 'CANONICAL_UUID_V2' + AND canonical_player_created_source_identity IS NOT NULL + AND octet_length(canonical_player_created_source_identity) BETWEEN 1 AND 4096)); + +ALTER TABLE entity_canonical_roster_admissions + ADD COLUMN entry_policy VARCHAR(32) NOT NULL DEFAULT 'PRESEEDED_ONLY' + CHECK (entry_policy IN ('PRESEEDED_ONLY', 'PLAYER_CREATED')); +ALTER TABLE entity_canonical_roster_original_selections + ADD COLUMN entry_policy VARCHAR(32) NOT NULL DEFAULT 'PRESEEDED_ONLY' + CHECK (entry_policy IN ('PRESEEDED_ONLY', 'PLAYER_CREATED')); +ALTER TABLE entity_canonical_roster_original_selections + ADD COLUMN canonical_player_created_roster_receipt BYTEA; +ALTER TABLE entity_canonical_roster_original_selections + ALTER COLUMN canonical_roster_receipt DROP NOT NULL; +ALTER TABLE entity_canonical_roster_original_selections + ADD CONSTRAINT ck_entity_roster_original_policy_receipt CHECK ( + (entry_policy = 'PRESEEDED_ONLY' AND canonical_roster_receipt IS NOT NULL + AND canonical_player_created_roster_receipt IS NULL) + OR (entry_policy = 'PLAYER_CREATED' AND canonical_roster_receipt IS NULL + AND canonical_player_created_roster_receipt IS NOT NULL + AND octet_length(canonical_player_created_roster_receipt) BETWEEN 1 AND 67584)); +ALTER TABLE entity_canonical_roster_retention_lifecycle + ADD COLUMN entry_policy VARCHAR(32) NOT NULL DEFAULT 'PRESEEDED_ONLY' + CHECK (entry_policy IN ('PRESEEDED_ONLY', 'PLAYER_CREATED')); +ALTER TABLE entity_canonical_roster_retirement_transfers + ADD COLUMN entry_policy VARCHAR(32) NOT NULL DEFAULT 'PRESEEDED_ONLY' + CHECK (entry_policy IN ('PRESEEDED_ONLY', 'PLAYER_CREATED')); + +-- Replace only the old byte-budget checks. All existing lifecycle/state/identity guards remain. +/* [jooq ignore start] */ +DO $$ +DECLARE selected RECORD; +BEGIN + FOR selected IN + SELECT c.conname, c.conrelid::regclass AS relation + FROM pg_constraint c + WHERE c.contype = 'c' AND ( + (c.conrelid = 'entity_canonical_roster_retention_lifecycle'::regclass + AND pg_get_constraintdef(c.oid) LIKE '%octet_length(owner_retirement_proof)%') + OR (c.conrelid = 'entity_canonical_roster_admissions'::regclass + AND pg_get_constraintdef(c.oid) LIKE '%octet_length(recovery_acknowledgement)%') + OR (c.conrelid = 'entity_canonical_roster_retirement_transfers'::regclass + AND (pg_get_constraintdef(c.oid) LIKE '%octet_length(observed_retirement)%' + OR pg_get_constraintdef(c.oid) LIKE '%octet_length(acknowledgement_request)%'))) + LOOP + EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', selected.relation, selected.conname); + END LOOP; +END; +$$; +/* [jooq ignore stop] */ +ALTER TABLE entity_canonical_roster_retention_lifecycle + ADD CONSTRAINT ck_entity_roster_lifecycle_policy_proof CHECK ( + (lifecycle_state = 'PROTECTED' AND retirement_observed_at IS NULL) + OR (lifecycle_state IN ('RETIRED', 'DISPOSING') AND owner_target_fence_uuid IS NOT NULL + AND owner_retirement_uuid IS NOT NULL AND owner_retirement_proof_digest ~ '^[0-9a-f]{64}$' + AND octet_length(owner_retirement_proof) BETWEEN 1 + AND CASE WHEN entry_policy = 'PLAYER_CREATED' THEN 203423744 ELSE 100000 END + AND retirement_observed_at IS NOT NULL AND minimum_retention_millis > 0)); +ALTER TABLE entity_canonical_roster_admissions + ADD CONSTRAINT ck_entity_roster_admission_policy_acknowledgement CHECK ( + recovery_acknowledgement IS NULL OR octet_length(recovery_acknowledgement) BETWEEN 1 + AND CASE WHEN entry_policy = 'PLAYER_CREATED' THEN 203423744 ELSE 131072 END); +ALTER TABLE entity_canonical_roster_retirement_transfers + ADD CONSTRAINT ck_entity_roster_transfer_policy_proof CHECK ( + observed_retirement IS NULL OR octet_length(observed_retirement) BETWEEN 1 + AND CASE WHEN entry_policy = 'PLAYER_CREATED' THEN 203423744 ELSE 131072 END); +ALTER TABLE entity_canonical_roster_retirement_transfers + ADD CONSTRAINT ck_entity_roster_transfer_policy_request CHECK ( + acknowledgement_request IS NULL OR octet_length(acknowledgement_request) BETWEEN 1 + AND CASE WHEN entry_policy = 'PLAYER_CREATED' THEN 204472320 ELSE 131072 END); + +/* [jooq ignore start] */ +CREATE FUNCTION guard_entity_roster_created_source_identity() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.canonical_player_created_source_identity IS DISTINCT FROM OLD.canonical_player_created_source_identity THEN + RAISE EXCEPTION 'sealed roster source identity is immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_entity_roster_created_source_immutable + BEFORE UPDATE ON entity_canonical_gameplay_roster_snapshots + FOR EACH ROW EXECUTE FUNCTION guard_entity_roster_created_source_identity(); + +CREATE FUNCTION guard_entity_roster_policy_identity() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE snapshot_policy VARCHAR(32); admission_policy VARCHAR(32); +BEGIN + IF TG_OP = 'UPDATE' AND NEW.entry_policy IS DISTINCT FROM OLD.entry_policy THEN + RAISE EXCEPTION 'roster policy identity is immutable' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'entity_canonical_roster_retirement_transfers' THEN + IF TG_OP = 'INSERT' THEN + SELECT entry_policy INTO admission_policy FROM entity_canonical_roster_admissions + WHERE operation_uuid = NEW.operation_uuid AND admission_uuid = NEW.admission_uuid; + IF admission_policy IS DISTINCT FROM NEW.entry_policy THEN + RAISE EXCEPTION 'retirement transfer changed admission policy' USING ERRCODE = '23514'; + END IF; + END IF; + ELSIF NEW.snapshot_uuid IS NOT NULL THEN + SELECT entry_policy INTO snapshot_policy FROM entity_canonical_gameplay_roster_snapshots + WHERE snapshot_uuid = NEW.snapshot_uuid; + IF snapshot_policy IS DISTINCT FROM NEW.entry_policy THEN + RAISE EXCEPTION 'roster lineage changed sealed snapshot policy' USING ERRCODE = '23514'; + END IF; + IF TG_TABLE_NAME = 'entity_canonical_roster_original_selections' AND NEW.entry_policy = 'PLAYER_CREATED' THEN + SELECT entry_policy INTO admission_policy FROM entity_canonical_roster_admissions + WHERE operation_uuid = NEW.operation_uuid AND admission_state = 'OPEN'; + IF admission_policy IS DISTINCT FROM NEW.entry_policy THEN + RAISE EXCEPTION 'created original requires its existing admission nonce' USING ERRCODE = '23514'; + END IF; + END IF; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_entity_roster_admission_policy + BEFORE INSERT OR UPDATE ON entity_canonical_roster_admissions + FOR EACH ROW EXECUTE FUNCTION guard_entity_roster_policy_identity(); +CREATE TRIGGER trg_entity_roster_original_policy + BEFORE INSERT OR UPDATE ON entity_canonical_roster_original_selections + FOR EACH ROW EXECUTE FUNCTION guard_entity_roster_policy_identity(); +CREATE TRIGGER trg_entity_roster_lifecycle_policy + BEFORE INSERT OR UPDATE ON entity_canonical_roster_retention_lifecycle + FOR EACH ROW EXECUTE FUNCTION guard_entity_roster_policy_identity(); +CREATE TRIGGER trg_entity_roster_transfer_policy + BEFORE INSERT OR UPDATE ON entity_canonical_roster_retirement_transfers + FOR EACH ROW EXECUTE FUNCTION guard_entity_roster_policy_identity(); + +CREATE FUNCTION guard_entity_roster_actor_policy() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE snapshot_policy VARCHAR(32); actor_policy VARCHAR(32); +BEGIN + SELECT entry_policy INTO snapshot_policy FROM entity_canonical_gameplay_roster_snapshots + WHERE snapshot_uuid = NEW.snapshot_uuid; + SELECT actor_entry_policy INTO actor_policy FROM characters WHERE character_uuid = NEW.character_uuid; + IF (snapshot_policy = 'PLAYER_CREATED' AND actor_policy IS DISTINCT FROM 'PLAYER_CREATED') + OR (snapshot_policy = 'PRESEEDED_ONLY' AND actor_policy IS NOT NULL) THEN + RAISE EXCEPTION 'roster actor changed published policy branch' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER trg_entity_roster_actor_policy + BEFORE INSERT ON entity_canonical_gameplay_roster_snapshot_actors + FOR EACH ROW EXECUTE FUNCTION guard_entity_roster_actor_policy(); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index bdd0ebb256..63ce867c56 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -410,7 +410,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); assertThat(successorHistory) .extracting(AppliedMigration::version) - .containsExactly("1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014"); + .containsExactly( + "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -421,7 +422,9 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1010__canonical_roster_owner_counters.sql", "V1011__fresh_selected_empty_source_catalogue.sql", "V1012__canonical_roster_retention.sql", - "V1014__canonical_roster_retirement_observation.sql"); + "V1014__canonical_roster_retirement_observation.sql", + "V1015__entity_character_create_terminal.sql", + "V1016__player_created_roster_snapshot_receipts.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 04f8a0814a..b8252c3d65 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -642,7 +642,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .extracting(migration -> migration.getVersion().getVersion()) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014"); + "1010", "1011", "1012", "1014", "1015", "1016"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -661,9 +661,11 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1010__canonical_roster_owner_counters.sql", "V1011__fresh_selected_empty_source_catalogue.sql", "V1012__canonical_roster_retention.sql", - "V1014__canonical_roster_retirement_observation.sql"); + "V1014__canonical_roster_retirement_observation.sql", + "V1015__entity_character_create_terminal.sql", + "V1016__player_created_roster_snapshot_receipts.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1014")); + .isEqualTo(MigrationVersion.fromVersion("1016")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -736,7 +738,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .extracting(MigrationHistoryEntry::version) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014"); + "1010", "1011", "1012", "1014", "1015", "1016"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -754,7 +756,9 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1010__canonical_roster_owner_counters.sql", "V1011__fresh_selected_empty_source_catalogue.sql", "V1012__canonical_roster_retention.sql", - "V1014__canonical_roster_retirement_observation.sql"); + "V1014__canonical_roster_retirement_observation.sql", + "V1015__entity_character_create_terminal.sql", + "V1016__player_created_roster_snapshot_receipts.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1017,7 +1021,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1014")); + .isEqualTo(MigrationVersion.fromVersion("1016")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java new file mode 100644 index 0000000000..c831a5db95 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -0,0 +1,978 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.PublishedIdentity; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient.AuthenticatedSource; +import net.firedevops.firemud.entitymanagement.repository.EntityEmptySelectedSourceIntakePostgresFixture; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.test.TestContainerImages; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Physical owner-transaction proof using a controlled already-verified-proof double. It exercises + * the real Entity selected-source intake and schema, but does not qualify cross-owner authority. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class EntityCharacterCreatePostgresIntegrationTest { + private static final Instant NOW = Instant.parse("2026-10-11T12:36:00Z"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + private EntityCharacterCreateRepository repository; + private EntityEmptySelectedSourceIntakeReceipt source; + + @BeforeEach + void migrateAndRetainActualEmptySource() { + schema = "entity_create_" + UUID.randomUUID().toString().replace("-", ""); + var configuration = + Flyway.configure() + .dataSource(dataSource(schema)) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + configuration.load().migrate(); + dsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES); + repository = new EntityCharacterCreateRepository(dsl, Clock.fixed(NOW, ZoneOffset.UTC)); + source = retainControlledSource(dsl); + } + + @Test + void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { + String parentSchema = "entity_create_parent_" + UUID.randomUUID().toString().replace("-", ""); + try { + DriverManagerDataSource parentDataSource = dataSource(parentSchema); + migrate(parentDataSource, parentSchema, "1014"); + DSLContext parentDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); + List parentVersions = migrationVersions(parentDsl); + assertThat(parentVersions).contains("1014").doesNotContain("1013"); + + UUID tenant = UUID.randomUUID(); + UUID account = UUID.randomUUID(); + UUID namespace = UUID.randomUUID(); + UUID character = UUID.randomUUID(); + UUID snapshot = UUID.randomUUID(); + // Controlled SQL owner values prove retained storage only, not authentic upstream custody. + seedRetainedParentActorAndRoster(parentDsl, tenant, account, namespace, character, snapshot); + List retainedRows = retainedParentRows(parentDsl, character, snapshot); + List parentHistory = migrationHistory(parentDsl); + + migrate(parentDataSource, parentSchema, null); + DSLContext upgradedDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); + assertThat(migrationHistory(upgradedDsl).subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + assertThat(migrationVersions(upgradedDsl)).last().isEqualTo("1016"); + assertThat(retainedParentRows(upgradedDsl, character, snapshot)) + .containsExactlyElementsOf(retainedRows); + assertThat( + upgradedDsl + .fetchSingle( + "SELECT canonical_player_created_source_identity FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + snapshot) + .get("canonical_player_created_source_identity", byte[].class)) + .isNull(); + } finally { + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + parentSchema + "\" CASCADE"); + } + } + + @AfterEach + void removeIsolatedSchema() { + if (schema != null) + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA \"" + schema + "\" CASCADE"); + } + + @Test + void atomicallyPersistsAuthoredGenericActorAssociationAndExactReplay() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID()); + var terminal = repository.settle(proof, null); + assertThat(terminal.getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED); + assertThat(repository.replay(proof.request()).orElseThrow().toByteArray()) + .containsExactly(terminal.toByteArray()); + assertThat(repository.settle(proof, null).toByteArray()) + .containsExactly(terminal.toByteArray()); + var actor = + dsl.fetchOne( + "SELECT * FROM characters WHERE character_uuid = ?", + UUID.fromString(terminal.getCharacterId())); + assertThat(actor).isNotNull(); + assertThat(actor.get("account_uuid", UUID.class).toString()) + .isEqualTo(proof.action().target().accountId()); + assertThat(actor.get("name", String.class)).isEqualTo("Wayfarer"); + assertThat(actor.get("authored_initial_core_json", String.class)) + .isEqualTo(proof.action().mutation().authoredSource().core().canonicalJson()); + for (String field : + List.of( + "account_id", + "playable_state_key", + "level", + "experience", + "strength", + "agility", + "intelligence", + "stamina", + "health", + "mana", + "body_layout_key")) assertThat(actor.get(field)).as(field).isNull(); + assertThat(actor.get("actor_entry_policy", String.class)).isEqualTo("PLAYER_CREATED"); + assertThat(terminal.getEntityIntakeRequestId()).isEqualTo(source.intakeRequestId().toString()); + assertThat(terminal.getEntitySourceReceiptDigest()).isEqualTo(source.receiptDigest()); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_character_create_operations SET terminal_bytes = ?", + new byte[] {1})) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE characters SET name = 'substituted' WHERE character_uuid = ?", + UUID.fromString(terminal.getCharacterId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void actualWriterFeedsDeterministicReadWithoutChangingRetainedRows() throws Exception { + UUID account = UUID.randomUUID(); + var proof = proof(account, UUID.randomUUID()); + var terminal = repository.settle(proof, null); + UUID actorId = UUID.fromString(terminal.getCharacterId()); + var beforeActor = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ?", + actorId), + "created actor evidence"); + var beforeOperation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, original_request, terminal_bytes FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId())), + "created operation evidence"); + + assertThat( + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(account), published(proof))) + .containsExactly( + new net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor( + actorId, "Wayfarer")); + assertThat( + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(UUID.randomUUID()), published(proof))) + .isEmpty(); + + var afterActor = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ?", + actorId), + "post-read actor evidence"); + var afterOperation = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, original_request, terminal_bytes FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId())), + "post-read operation evidence"); + assertThat(afterActor.get("row_version", String.class)) + .isEqualTo(beforeActor.get("row_version", String.class)); + assertThat(afterActor.get("authored_initial_core_json", String.class)) + .isEqualTo(beforeActor.get("authored_initial_core_json", String.class)); + assertThat(afterActor.get("creation_descriptor_json", String.class)) + .isEqualTo(beforeActor.get("creation_descriptor_json", String.class)); + assertThat(afterActor.get("creation_descriptor_digest", String.class)) + .isEqualTo(beforeActor.get("creation_descriptor_digest", String.class)); + assertThat(afterOperation.get("row_version", String.class)) + .isEqualTo(beforeOperation.get("row_version", String.class)); + assertThat(afterOperation.get("original_request", byte[].class)) + .containsExactly(beforeOperation.get("original_request", byte[].class)); + assertThat(afterOperation.get("terminal_bytes", byte[].class)) + .containsExactly(beforeOperation.get("terminal_bytes", byte[].class)); + } + + @Test + void selectedReadReturnsExactCommittedTerminalAndRejectsOutOfRosterActors() throws Exception { + UUID accountId = UUID.randomUUID(); + var proof = proof(accountId, UUID.randomUUID()); + EntityCharacterCreateTerminal original = repository.settle(proof, null); + UUID characterId = UUID.fromString(original.getCharacterId()); + var account = new AuthenticatedAccountSelector(accountId); + var published = published(proof); + var actorBefore = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, name, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ?", + characterId)); + var operationBefore = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, operation_id, mutation_digest, original_request, terminal_bytes FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))); + int actorCountBefore = dsl.fetchCount(DSL.table("characters")); + + EntityCharacterCreateTerminal selected = + repository.readSelectedPlayerCreatedTerminal(account, published, characterId); + assertThat(selected.toByteArray()).containsExactly(original.toByteArray()); + assertThat(selected.getOriginalRequest().getOriginal().getOperationId()) + .isEqualTo(operationBefore.get("operation_id", UUID.class).toString()); + assertThat(selected.getAccountOriginal().getMutationDigest()) + .isEqualTo(operationBefore.get("mutation_digest", String.class)); + + assertSelectedActorUnavailable( + new AuthenticatedAccountSelector(UUID.randomUUID()), published, characterId); + assertSelectedActorUnavailable( + account, + new PublishedIdentity( + published.targetNamespace(), + published.tenantId(), + UUID.randomUUID(), + published.worldSlug(), + published.realmSlug(), + published.playableStateNamespaceId(), + published.canonicalVersionId(), + published.projection()), + characterId); + assertSelectedActorUnavailable( + account, + new PublishedIdentity( + published.targetNamespace(), + published.tenantId(), + published.realmId(), + published.worldSlug(), + published.realmSlug(), + UUID.randomUUID(), + published.canonicalVersionId(), + published.projection()), + characterId); + assertSelectedActorUnavailable(account, published, UUID.randomUUID()); + + var actorAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, name, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ?", + characterId)); + var operationAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, operation_id, mutation_digest, original_request, terminal_bytes FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))); + assertThat(actorAfter.intoMap()).isEqualTo(actorBefore.intoMap()); + assertThat(operationAfter.get("row_version", String.class)) + .isEqualTo(operationBefore.get("row_version", String.class)); + assertThat(operationAfter.get("operation_id", UUID.class)) + .isEqualTo(operationBefore.get("operation_id", UUID.class)); + assertThat(operationAfter.get("mutation_digest", String.class)) + .isEqualTo(operationBefore.get("mutation_digest", String.class)); + assertThat(operationAfter.get("original_request", byte[].class)) + .containsExactly(operationBefore.get("original_request", byte[].class)); + assertThat(operationAfter.get("terminal_bytes", byte[].class)) + .containsExactly(operationBefore.get("terminal_bytes", byte[].class)); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(actorCountBefore); + } + + @Test + void emptyDiscoveryAllocatesNothingAndOmitsLegacyQuarantinedDecoys() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID()); + var published = published(proof); + var account = + new AuthenticatedAccountSelector(UUID.fromString(proof.action().target().accountId())); + assertThat(repository.readPlayerCreatedRoster(account, published)).isEmpty(); + assertThat(dsl.fetchCount(DSL.table("characters"))).isZero(); + + var terminal = repository.settle(proof, null); + dsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_id, tenant_id, name) VALUES (?, ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 45, ?, 'quarantined decoy')", + UUID.randomUUID(), + account.accountId(), + published.tenantId(), + published.playableStateNamespaceId(), + 87654L); + assertThat(repository.readPlayerCreatedRoster(account, published)) + .containsExactly( + new net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor( + UUID.fromString(terminal.getCharacterId()), "Wayfarer")); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(2); + } + + @Test + void rejectsCurrentIdentityAndRetainedDescriptorProvenanceMismatch() throws Exception { + UUID account = UUID.randomUUID(); + var proof = proof(account, UUID.randomUUID()); + var terminal = repository.settle(proof, null); + var published = published(proof); + var changedRealm = + new PublishedIdentity( + published.targetNamespace(), + published.tenantId(), + UUID.randomUUID(), + published.worldSlug(), + published.realmSlug(), + published.playableStateNamespaceId(), + published.canonicalVersionId(), + published.projection()); + assertThatThrownBy( + () -> + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(account), changedRealm)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("DATA_LOSS"); + + dsl.execute("ALTER TABLE characters DISABLE TRIGGER trg_entity_created_actor_immutable"); + try { + dsl.execute( + "UPDATE characters SET creation_descriptor_json = '{}' WHERE character_uuid = ?", + UUID.fromString(terminal.getCharacterId())); + assertThatThrownBy( + () -> + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(account), published)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("DATA_LOSS"); + assertThatThrownBy( + () -> + repository.readSelectedPlayerCreatedTerminal( + new AuthenticatedAccountSelector(account), + published, + UUID.fromString(terminal.getCharacterId()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("DATA_LOSS"); + } finally { + dsl.execute("ALTER TABLE characters ENABLE TRIGGER trg_entity_created_actor_immutable"); + } + } + + private void assertSelectedActorUnavailable( + AuthenticatedAccountSelector account, PublishedIdentity published, UUID characterId) { + assertThatThrownBy( + () -> repository.readSelectedPlayerCreatedTerminal(account, published, characterId)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("FAILED_PRECONDITION") + .hasMessageContaining("Selected PLAYER_CREATED character is unavailable"); + } + + @Test + void explicitAbortPermanentlyWinsAgainstFutureCommitAndChangedDigestConflicts() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID()); + String abort = UUID.randomUUID().toString(); + var terminal = repository.settle(proof, abort); + assertThat(terminal.getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED); + assertThat(repository.settle(proof, null).toByteArray()) + .containsExactly(terminal.toByteArray()); + assertThat(dsl.fetchCount(DSL.table("characters"))).isZero(); + assertThatThrownBy( + () -> + repository.read( + proof.request().getOriginal().toBuilder() + .setMutationDigest("f".repeat(64)) + .build())) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("ALREADY_EXISTS"); + assertThatThrownBy(() -> dsl.execute("DELETE FROM entity_character_create_operations")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + + @Test + void expiredAuthorityAllocatesNothingButExplicitAbortRemainsDefinitive() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID()); + var expired = + new EntityCharacterCreateRepository( + dsl, Clock.fixed(Instant.parse("2026-10-12T00:00:00Z"), ZoneOffset.UTC)); + assertThatThrownBy(() -> expired.settle(proof, null)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("expired"); + assertThat(dsl.fetchCount(DSL.table("characters"))).isZero(); + assertThat(repository.read(proof.request().getOriginal())).isEmpty(); + assertThat(expired.settle(proof, UUID.randomUUID().toString()).getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED); + } + + @Test + void futureRemoteObservationAndAcquisitionsDoNotDenySolelyDueToClockSkew() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID(), true); + assertThat(proof.action().expectedVersion().evaluatedAt()).isAfter(NOW); + assertThat(Instant.parse(proof.account().getAcquiredAt())).isAfter(NOW); + assertThat(Instant.parse(proof.gameSession().acquiredAt())).isAfter(NOW); + assertThat(Instant.parse(proof.world().getAcquiredAt())).isAfter(NOW); + assertThat(repository.settle(proof, null).getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(1); + } + + @Test + void distinctRequestsCannotBothCrossTheSameZeroRoster() throws Exception { + UUID account = UUID.randomUUID(); + var first = proof(account, UUID.randomUUID()); + var second = proof(account, UUID.randomUUID()); + var results = race(() -> repository.settle(first, null), () -> repository.settle(second, null)); + assertThat(results.stream().filter(EntityCharacterCreateTerminal.class::isInstance).count()) + .isEqualTo(1L); + assertThat(results.stream().filter(io.grpc.StatusRuntimeException.class::isInstance).count()) + .isEqualTo(1L); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(1); + var loser = repository.read(first.request().getOriginal()).isEmpty() ? first : second; + assertThat(repository.settle(loser, UUID.randomUUID().toString()).getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(1); + } + + @Test + void commitAndAbortSerializeToOneImmutableTerminal() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID()); + String abort = UUID.randomUUID().toString(); + var results = race(() -> repository.settle(proof, null), () -> repository.settle(proof, abort)); + assertThat(results) + .allSatisfy(value -> assertThat(value).isInstanceOf(EntityCharacterCreateTerminal.class)); + var first = (EntityCharacterCreateTerminal) results.getFirst(); + var second = (EntityCharacterCreateTerminal) results.get(1); + assertThat(second.toByteArray()).containsExactly(first.toByteArray()); + assertThat(dsl.fetchCount(DSL.table("characters"))) + .isEqualTo(first.getCharacterId().isEmpty() ? 0 : 1); + } + + @Test + void legacyRowsKeepTheirConstraintsAndCannotBeRelabelled() { + dsl.execute( + "INSERT INTO characters (account_id, tenant_id, name) VALUES (76543, 87654, 'legacy')"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE characters SET actor_entry_policy = 'PLAYER_CREATED' WHERE name = 'legacy'")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO characters (account_id, tenant_id, name, level) VALUES (76544, 87654, 'invalid', NULL)")) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT actor_identity_status FROM characters WHERE name = 'legacy'")) + .get(0, String.class)) + .isEqualTo("QUARANTINED"); + } + + /** Retains the existing controlled source fixture in the caller's PostgreSQL schema. */ + static EntityEmptySelectedSourceIntakeReceipt retainControlledSource(DSLContext ownerDsl) { + var controlled = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + return retainControlledSource(ownerDsl, controlled); + } + + static EntityEmptySelectedSourceIntakeReceipt retainControlledSource( + DSLContext ownerDsl, DraftCommitBinding selectedCommit) { + var controlled = EntityEmptySelectedSourceIntakePostgresFixture.create("1", selectedCommit); + return retainControlledSource(ownerDsl, controlled); + } + + private static EntityEmptySelectedSourceIntakeReceipt retainControlledSource( + DSLContext ownerDsl, EntityEmptySelectedSourceIntakePostgresFixture.Fixture controlled) { + var inputs = controlled.inputs(); + String digest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + inputs.authorizationBinding().targetNamespace(), + inputs.authorizationBinding(), + inputs.worldInventoryReadEvidence().request().freezeEvidence()); + return new EntityEmptySelectedSourceIntakeRepository(ownerDsl).retainFresh(inputs, digest); + } + + private EntityCharacterCreateProofs proof(UUID accountId, UUID operationId) throws Exception { + return proof(accountId, operationId, false); + } + + private EntityCharacterCreateProofs proof( + UUID accountId, UUID operationId, boolean futureRemoteClocks) throws Exception { + return proof(source, accountId, operationId, futureRemoteClocks, null); + } + + /** Reuses the controlled owner-proof double while binding the actual mTLS published identity. */ + static EntityCharacterCreateProofs proofForRosterCapture( + EntityEmptySelectedSourceIntakeReceipt entitySource, + UUID accountId, + UUID operationId, + AuthenticatedSource rosterSource) + throws Exception { + return proof(entitySource, accountId, operationId, false, rosterSource); + } + + private static EntityCharacterCreateProofs proof( + EntityEmptySelectedSourceIntakeReceipt entitySource, + UUID accountId, + UUID operationId, + boolean futureRemoteClocks, + AuthenticatedSource rosterSource) + throws Exception { + String raw; + try (InputStream input = + Objects.requireNonNull( + EntityCharacterCreatePostgresIntegrationTest.class.getResourceAsStream( + "/charactercreate/entity-public-action.json"))) { + raw = new String(input.readAllBytes(), StandardCharsets.UTF_8).strip(); + } + raw = + raw.replace( + "\"targetNamespace\":\"firemud\"", + "\"targetNamespace\":\"" + entitySource.targetNamespace() + "\"") + .replace( + "a1000000-0000-4000-8000-000000000001", entitySource.canonicalTenantId().toString()) + .replace( + "a6000000-0000-4000-8000-000000000001", + entitySource.canonicalVersionId().toString()) + .replace("a4000000-0000-4000-8000-000000000001", accountId.toString()) + .replace( + "a9000000-0000-4000-8000-000000000001", entitySource.selectedCommitId().toString()) + .replace( + "sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a", + entitySource.authorizationBinding().selected().digest()) + .replace( + "a8000000-0000-4000-8000-000000000001", + entitySource + .inputs() + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .ownerScope() + .sourceOperationId() + .toString()) + .replace( + "sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263", + entitySource + .inputs() + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .ownerScope() + .sourceEvidenceDigest()); + if (futureRemoteClocks) + raw = raw.replace("2026-10-11T12:34:56.123456789Z", "2026-10-11T12:38:00Z"); + byte[] bytes = raw.getBytes(StandardCharsets.UTF_8); + CharacterCreateOperatorAction action = CharacterCreateOperatorActionCodec.decode(bytes); + if (rosterSource != null) { + action = requireRosterSourceAction(action, entitySource, accountId, rosterSource); + bytes = CharacterCreateOperatorActionCodec.encode(action); + } + Instant controlledOwnerReadsAt = + rosterSource == null ? null : action.expectedVersion().evaluatedAt().plusSeconds(1); + String accountAcquiredAt = + futureRemoteClocks + ? "2026-10-11T12:38:01Z" + : controlledOwnerReadsAt == null + ? "2026-10-11T12:35:00Z" + : controlledOwnerReadsAt.toString(); + String gameSessionAcquiredAt = + futureRemoteClocks + ? "2026-10-11T12:38:02Z" + : controlledOwnerReadsAt == null + ? "2026-10-11T12:35:01Z" + : controlledOwnerReadsAt.plusSeconds(1).toString(); + String worldAcquiredAt = + futureRemoteClocks + ? "2026-10-11T12:38:03Z" + : controlledOwnerReadsAt == null + ? "2026-10-11T12:35:02Z" + : controlledOwnerReadsAt.plusSeconds(2).toString(); + var original = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(entitySource.targetNamespace()) + .setOperationId(operationId.toString()) + .setCreateCharacterRequestId(UUID.randomUUID().toString()) + .setConnectScopeId("Issued.Scope-Exact_Opaque.mixedCase-01") + .setAuthenticatedAccountId(accountId.toString()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(bytes)) + .setMutationDigest(CharacterCreateOperatorActionCodec.mutationDigest(action)) + .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-repository-source")) + .build(); + var reference = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(entitySource.targetNamespace()) + .setOperationId(operationId.toString()) + .setMutationDigest(original.getMutationDigest()) + .build(); + var accountRef = protection(); + var gsRef = protection(); + var worldRef = protection(); + var request = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(reference) + .setAccountProtection(accountRef) + .setGameSessionProtection(gsRef) + .setWorldProtection(worldRef) + .build(); + var account = + ReadOriginalCharacterCreateProtectionResponse.newBuilder() + .setOriginal(original) + .setAccountProtectionId(accountRef.getProtectionId()) + .setAccountProtectionFence(1L) + .setAcquiredAt(accountAcquiredAt) + .setOriginalMembershipSnapshot(ByteString.copyFromUtf8("controlled-membership")) + .setOriginalEntitlementSnapshot(ByteString.copyFromUtf8("controlled-entitlement")) + .build(); + var gs = + new GameSessionCharacterCreateProtectionReader.Readback( + account, + gsRef, + gameSessionAcquiredAt, + ByteString.copyFromUtf8("controlled-GS-repository-proof")); + var world = + WorldCharacterCreateLifecycleProtection.newBuilder() + .setAccountProtection(account) + .setWorldProtectionId(worldRef.getProtectionId()) + .setWorldProtectionFence(1L) + .setAcquiredAt(worldAcquiredAt) + .setOriginalLifecycleEvidence( + ByteString.copyFromUtf8("controlled-World-repository-proof")) + .build(); + var proof = mock(EntityCharacterCreateProofs.class); + when(proof.request()).thenReturn(request); + when(proof.original()).thenReturn(original); + when(proof.action()).thenReturn(action); + when(proof.account()).thenReturn(account); + when(proof.gameSession()).thenReturn(gs); + when(proof.world()).thenReturn(world); + when(proof.entitySource()).thenReturn(entitySource); + return proof; + } + + private static CharacterCreateOperatorAction requireRosterSourceAction( + CharacterCreateOperatorAction original, + EntityEmptySelectedSourceIntakeReceipt entitySource, + UUID accountId, + AuthenticatedSource source) { + var target = source.target(); + var request = source.response().getRequest(); + var catalog = source.response().getCatalog(); + var pointer = source.response().getPointer(); + var projection = source.authored().projections().getFirst(); + if (!entitySource.targetNamespace().equals(request.getTargetNamespace()) + || !entitySource.canonicalTenantId().equals(target.tenantUuid()) + || !entitySource.canonicalVersionId().equals(target.canonicalVersionUuid()) + || !entitySource.selectedCommitId().equals(projection.selectedCommitId())) { + throw new IllegalArgumentException( + "Controlled Entity writer fixture does not match the authenticated publication source"); + } + var authored = authoredSource(projection); + return new CharacterCreateOperatorAction( + new CharacterCreateOperatorAction.Scope( + request.getTargetNamespace(), + target.tenantUuid().toString(), + target.playableStateNamespaceId().toString(), + CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + new CharacterCreateOperatorAction.Target( + accountId.toString(), + target.realmUuid().toString(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.canonicalVersionUuid().toString()), + new CharacterCreateOperatorAction.ExpectedVersion( + Long.toString(target.catalogRevision()), + Long.toString(target.pointerVersion()), + Long.toString(target.activeWorldEpoch()), + EntityCharacterCreateBindings.instant(pointer.getUpdatedAt()).plusSeconds(1), + EntityCharacterCreateBindings.instant(pointer.getUpdatedAt()).plusSeconds(301)), + new CharacterCreateOperatorAction.Mutation( + original.mutation().purpose(), + original.mutation().entryPolicy(), + new CharacterCreateOperatorAction.Catalog( + target.tenantUuid().toString(), + catalog.getTenantSlug(), + target.worldSlug(), + catalog.getWorldDisplayName(), + target.realmUuid().toString(), + target.realmSlug(), + catalog.getRealmDisplayName(), + catalog.getVisible(), + catalog.getPublicProduction(), + catalog.getStateScope(), + target.playableStateNamespaceId().toString(), + catalog.getCharacterCreationPolicy(), + Long.toString(target.catalogRevision())), + new CharacterCreateOperatorAction.Pointer( + target.tenantUuid().toString(), + target.realmUuid().toString(), + target.worldSlug(), + target.realmSlug(), + pointer.getAdmissionState(), + target.gameInstanceUuid().toString(), + Long.toString(target.pointerVersion()), + Long.toString(target.catalogRevision()), + EntityCharacterCreateBindings.instant(pointer.getUpdatedAt())), + authored, + original.mutation().canonicalCreationInput()), + original.auditReason()); + } + + private static CharacterCreateOperatorAction.AuthoredSource authoredSource( + AuthoredInitialActorCoreProjection projection) { + var policy = projection.policy(); + return new CharacterCreateOperatorAction.AuthoredSource( + AuthoredInitialActorCoreProjection.SCHEMA, + projection.bindingId().toString(), + projection.bindingDigest(), + projection.canonicalTenantId().toString(), + projection.canonicalVersionId().toString(), + projection.worldSourceOperationId().toString(), + projection.worldSourceEvidenceDigest(), + projection.worldSlug(), + projection.publicationWorkflowId(), + projection.selectedCommitId().toString(), + projection.selectedCommitDigest(), + new CharacterCreateOperatorAction.Policy( + policy.commitId().toString(), + policy.revisionId().toString(), + policy.logicalRevisionId(), + policy.canonicalJson(), + policy.contentDigest()), + new CharacterCreateOperatorAction.Core(projection.core().canonicalJson()), + new CharacterCreateOperatorAction.Descriptor( + projection.descriptor().canonicalJson(), projection.descriptor().digest()), + authoredRule(projection.disposition()), + authoredRule(projection.safeFeedback())); + } + + private static CharacterCreateOperatorAction.Rule authoredRule( + AuthoredInitialActorCoreProjection.RuleDefinition rule) { + return new CharacterCreateOperatorAction.Rule( + rule.key(), + rule.definitionJson(), + rule.definitionDigest(), + rule.sourceCommitId().toString(), + rule.sourceCommitDigest(), + rule.revisionId().toString(), + rule.revisionOrder()); + } + + private static PublishedIdentity published(EntityCharacterCreateProofs proof) throws Exception { + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + var root = json.readTree(proof.original().getOriginalAction().toByteArray()); + var action = proof.action(); + var authored = action.mutation().authoredSource(); + var projectionNode = + (tools.jackson.databind.node.ObjectNode) root.get("mutation").get("authoredSource"); + projectionNode.put("publicationWorkflowId", authored.publicationWorkflowId()); + ((tools.jackson.databind.node.ObjectNode) projectionNode.get("policy")) + .put("logicalRevisionId", authored.policy().logicalRevisionId()) + .put("canonicalPolicyJson", authored.policy().canonicalPolicyJson()); + ((tools.jackson.databind.node.ObjectNode) projectionNode.get("core")) + .put("canonicalJson", authored.core().canonicalJson()); + ((tools.jackson.databind.node.ObjectNode) projectionNode.get("descriptor")) + .put("canonicalJson", authored.descriptor().canonicalJson()); + ((tools.jackson.databind.node.ObjectNode) projectionNode.get("disposition")) + .put("definitionJson", authored.disposition().definitionJson()); + ((tools.jackson.databind.node.ObjectNode) projectionNode.get("safeFeedback")) + .put("definitionJson", authored.safeFeedback().definitionJson()); + byte[] projectionBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(json.writeValueAsString(projectionNode)); + var projection = + AuthoredInitialActorCoreProjection.fromStored( + projectionBytes, CommandSource.sha256(projectionBytes)); + return new PublishedIdentity( + action.scope().targetNamespace(), + UUID.fromString(action.scope().tenantId()), + UUID.fromString(action.target().realmId()), + action.target().worldSlug(), + action.target().realmSlug(), + UUID.fromString(action.scope().playableStateNamespaceId()), + UUID.fromString(action.target().versionId()), + projection); + } + + private static CharacterCreateProtectionReference protection() { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(UUID.randomUUID().toString()) + .setProtectionFence(1L) + .build(); + } + + private static List race( + Callable first, Callable second) + throws Exception { + try (var workers = Executors.newFixedThreadPool(2)) { + var barrier = new CyclicBarrier(2); + Callable a = + () -> { + barrier.await(10, TimeUnit.SECONDS); + try { + return first.call(); + } catch (io.grpc.StatusRuntimeException failed) { + return failed; + } + }; + Callable b = + () -> { + barrier.await(10, TimeUnit.SECONDS); + try { + return second.call(); + } catch (io.grpc.StatusRuntimeException failed) { + return failed; + } + }; + var fa = workers.submit(a); + var fb = workers.submit(b); + return List.of(fa.get(30, TimeUnit.SECONDS), fb.get(30, TimeUnit.SECONDS)); + } + } + + private static DriverManagerDataSource dataSource(String schema) { + String url = postgres.getJdbcUrl(); + if (schema != null) url += (url.contains("?") ? "&" : "?") + "currentSchema=" + schema; + return new DriverManagerDataSource(url, postgres.getUsername(), postgres.getPassword()); + } + + private static void migrate(DriverManagerDataSource dataSource, String schema, String target) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + if (target != null) configuration.target(target); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + configuration.load().migrate(); + } + + private static List migrationHistory(DSLContext source) { + return source + .fetch( + "SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank") + .getValues(0, String.class); + } + + private static List migrationVersions(DSLContext source) { + return source + .fetch( + "SELECT version FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class); + } + + private static void seedRetainedParentActorAndRoster( + DSLContext source, UUID tenant, UUID account, UUID namespace, UUID character, UUID snapshot) { + source.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)", tenant); + Long tenantRow = + source + .fetchSingle( + "SELECT entity_tenant_row_id FROM entity_tenant_identities WHERE canonical_tenant_uuid = ?", + tenant) + .get("entity_tenant_row_id", Long.class); + source.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, 'PLAYABLE_STATE_SCOPE_SHARED')", + tenant, + namespace); + source.execute( + "INSERT INTO characters (character_uuid, account_id, tenant_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason) VALUES (?, 101, ?, 'shared-live', 'Retained actor', 1, 0, 10, 10, 10, 10, 100, 100, 'legacy-body', ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 'OWNER_RESOLVED', NULL)", + character, + tenantRow, + account, + tenant, + namespace); + source.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshots (snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, canonical_version_uuid, publication_evidence_format, pointer_version, active_world_epoch, published_policy_digest, published_release_bundle_ref, admission_pointer_snapshot_digest, published_owner_proof_digest, playable_state_namespace_uuid, playable_state_scope, entry_policy, roster_count) VALUES (?, ?, ?, ?, ?, 'world', 'realm', ?, 1, ?, 'CANONICAL_UUID_V2', 1, 1, ?, 'retained-release', ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 'PRESEEDED_ONLY', 1)", + snapshot, + "a".repeat(64), + account, + tenant, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "b".repeat(64), + "c".repeat(64), + "d".repeat(64), + namespace); + source.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshot_actors (snapshot_uuid, ordinal_position, character_uuid, display_name, actor_kind) VALUES (?, 0, ?, 'Retained actor', 'PLAYER')", + snapshot, + character); + source.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET construction_state = 'SEALED' WHERE snapshot_uuid = ?", + snapshot); + } + + private static List retainedParentRows(DSLContext source, UUID character, UUID snapshot) { + return List.of( + source + .fetchSingle( + "SELECT (to_jsonb(t) - ARRAY['creation_target_namespace', 'creation_operation_id', 'actor_entry_policy', 'authored_initial_core_json', 'creation_descriptor_json', 'creation_descriptor_digest'])::TEXT || ':' || t.xmin::TEXT FROM characters t WHERE character_uuid = ?", + character) + .get(0, String.class), + source + .fetchSingle( + "SELECT (to_jsonb(t) - 'canonical_player_created_source_identity')::TEXT || ':' || t.xmin::TEXT FROM entity_canonical_gameplay_roster_snapshots t WHERE snapshot_uuid = ?", + snapshot) + .get(0, String.class), + source + .fetchSingle( + "SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM entity_canonical_gameplay_roster_snapshot_actors t WHERE snapshot_uuid = ?", + snapshot) + .get(0, String.class)); + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java new file mode 100644 index 0000000000..2e5c14737f --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java @@ -0,0 +1,765 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.PublishedIdentity; +import net.firedevops.firemud.entitymanagement.repository.CanonicalGameplayRosterRetentionRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRetentionPolicy; +import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture; +import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture.WireFixture; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +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; + +/** + * Physical PostgreSQL proof using the real initialized Entity mTLS source client and controlled + * owner-shaped publication and original-reference fixtures. The source stub and original owner + * response do not prove production Game Session custody or genuine publication. The created-actor + * case uses the actual Entity SQL writer with its existing controlled upstream-proof fixture. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DriverManagerDataSource dataSource; + private DSLContext dsl; + private DataSourceTransactionManager transactionManager; + private TransactionTemplate transaction; + + @TempDir Path certificateDirectory; + + @BeforeEach + void migrateCurrentEntitySchema() { + schema = "entity_created_roster_" + UUID.randomUUID().toString().replace("-", ""); + dataSource = dataSource(schema); + var configuration = migrationConfiguration(dataSource, schema); + configuration.load().migrate(); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + transactionManager = new DataSourceTransactionManager(dataSource); + transaction = new TransactionTemplate(transactionManager); + } + + @AfterEach + void removeOwnedSchema() { + if (schema != null) { + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + + @Test + void sealedEmptyCreatedSnapshotRetainsImmutableSourceIdentity() { + UUID tenant = UUID.randomUUID(); + UUID namespace = UUID.randomUUID(); + UUID snapshot = UUID.randomUUID(); + byte[] source = sourceIdentity().toByteArray(); + enroll(tenant, namespace); + + insertBuildingSnapshot(snapshot, tenant, namespace, source); + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET construction_state = 'SEALED' WHERE snapshot_uuid = ?", + snapshot); + + var stored = + dsl.fetchOne( + "SELECT entry_policy, playable_state_scope, roster_count, construction_state, canonical_player_created_source_identity FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + snapshot); + assertThat(stored.get("entry_policy", String.class)).isEqualTo("PLAYER_CREATED"); + assertThat(stored.get("playable_state_scope", String.class)) + .isEqualTo("PLAYABLE_STATE_SCOPE_SHARED"); + assertThat(stored.get("roster_count", Short.class)).isZero(); + assertThat(stored.get("construction_state", String.class)).isEqualTo("SEALED"); + assertThat(stored.get("canonical_player_created_source_identity", byte[].class)) + .containsExactly(source); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshot_actors"))) + .isZero(); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + sourceIdentity().toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .build() + .toByteArray(), + snapshot)) + .isInstanceOf(DataAccessException.class); + } + + @Test + void createdSnapshotCannotOmitSourceIdentity() { + UUID tenant = UUID.randomUUID(); + UUID namespace = UUID.randomUUID(); + enroll(tenant, namespace); + + assertThatThrownBy(() -> insertBuildingSnapshot(UUID.randomUUID(), tenant, namespace, null)) + .isInstanceOf(DataAccessException.class); + } + + @Test + void captureRejectsAnAmbientReadOnlyTransactionBeforeAcceptingAnySourceValue() { + var transactionManager = new DataSourceTransactionManager(dataSource); + var capture = new EntityPlayerCreatedRosterSnapshotRepository(dsl, transactionManager); + var outerReadOnly = new TransactionTemplate(transactionManager); + outerReadOnly.setReadOnly(true); + + assertThatThrownBy( + () -> outerReadOnly.execute(ignored -> capture.capture(null, null, null, null))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("short Entity transactions"); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshots"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_admissions"))).isZero(); + } + + @Test + void actualConfiguredMtlsSourceCapturesAndReplaysAnEmptyRosterAtomically() throws Exception { + var inputs = authenticatedCaptureInputs(); + UUID admission = reserveAdmission(inputs.request()); + var repository = new EntityPlayerCreatedRosterSnapshotRepository(dsl, transactionManager); + + var first = repository.capture(inputs.request(), inputs.source(), inputs.original(), admission); + var replay = + repository.capture(inputs.request(), inputs.source(), inputs.original(), admission); + + assertThat(replay.toByteArray()).containsExactly(first.toByteArray()); + assertThat(first.getRoster().getActorsList()).isEmpty(); + assertThat(first.getRoster().getSnapshotDigest()) + .isEqualTo( + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + inputs.request().getCanonicalAccountUuid(), + inputs.request().getExpectedTarget(), + inputs.request().getExpectedSource(), + first.getRoster().getActorsList())); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshots"))) + .isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshot_actors"))) + .isZero(); + + var snapshot = + dsl.fetchSingle( + "SELECT entry_policy, roster_count, construction_state, canonical_player_created_source_identity FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + UUID.fromString(first.getRoster().getSnapshotUuid())); + assertThat(snapshot.get("entry_policy", String.class)).isEqualTo("PLAYER_CREATED"); + assertThat(snapshot.get("roster_count", Short.class)).isZero(); + assertThat(snapshot.get("construction_state", String.class)).isEqualTo("SEALED"); + assertThat(snapshot.get("canonical_player_created_source_identity", byte[].class)) + .containsExactly(inputs.request().getExpectedSource().toByteArray()); + + var retained = + dsl.fetchSingle( + "SELECT owner_request, owner_fence, owner_target_fence_uuid, canonical_player_created_roster_receipt FROM entity_canonical_roster_original_selections WHERE operation_uuid = ?", + UUID.fromString(inputs.request().getRequestUuid())); + assertThat(retained.get("owner_request", byte[].class)) + .containsExactly(inputs.original().getRequest().toByteArray()); + assertThat(retained.get("owner_fence", Long.class)) + .isEqualTo(inputs.original().getOwnerFence()); + assertThat(retained.get("owner_target_fence_uuid", UUID.class)) + .isEqualTo(UUID.fromString(inputs.original().getTargetFenceUuid())); + assertThat(retained.get("canonical_player_created_roster_receipt", byte[].class)) + .containsExactly(first.toByteArray()); + assertThat( + dsl.fetchSingle( + "SELECT snapshot_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ? AND admission_uuid = ?", + UUID.fromString(inputs.request().getRequestUuid()), + admission) + .get(0, UUID.class)) + .isEqualTo(UUID.fromString(first.getRoster().getSnapshotUuid())); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + sourceIdentity().toByteArray(), + UUID.fromString(first.getRoster().getSnapshotUuid()))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws Exception { + UUID accountId = UUID.randomUUID(); + var inputs = authenticatedCaptureInputs(accountId, null); + DraftCommitBinding selectedCommit = + GameDesignPublicationOperationBinding.fromStored( + inputs.source().publishedPolicySet().operationBytes()) + .account() + .input() + .selection() + .selectedCommit(); + var projection = inputs.source().authored().projections().getFirst(); + assertThat(selectedCommit.target().canonicalTenantId()) + .isEqualTo(inputs.source().target().tenantUuid()); + assertThat(selectedCommit.target().canonicalVersionId()) + .isEqualTo(inputs.source().target().canonicalVersionUuid()); + assertThat(projection.selectedCommitId()).isEqualTo(selectedCommit.commitId()); + assertThat(projection.selectedCommitDigest()).isEqualTo(selectedCommit.digest()); + var entitySource = + EntityCharacterCreatePostgresIntegrationTest.retainControlledSource(dsl, selectedCommit); + var proof = + EntityCharacterCreatePostgresIntegrationTest.proofForRosterCapture( + entitySource, accountId, UUID.randomUUID(), inputs.source()); + var writer = + new EntityCharacterCreateRepository( + dsl, Clock.fixed(Instant.parse("2026-10-24T00:01:00Z"), ZoneOffset.UTC)); + + var terminal = writer.settle(proof, null); + UUID actorId = UUID.fromString(terminal.getCharacterId()); + var published = PublishedIdentity.from(inputs.source()); + var selected = + writer.readSelectedPlayerCreatedTerminal( + new AuthenticatedAccountSelector(accountId), published, actorId); + assertThat(terminal.getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED); + assertThat(selected.toByteArray()).containsExactly(terminal.toByteArray()); + assertThat(terminal.getOriginalRequest().getOriginal().getTargetNamespace()) + .isEqualTo(inputs.source().response().getRequest().getTargetNamespace()); + assertThat(terminal.getAccountOriginal().getMutationDigest()) + .isEqualTo(proof.original().getMutationDigest()); + + UUID admission = reserveAdmission(inputs.request()); + var snapshotRepository = + new EntityPlayerCreatedRosterSnapshotRepository(dsl, transactionManager); + var snapshot = + snapshotRepository.capture(inputs.request(), inputs.source(), inputs.original(), admission); + + var selectedOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + inputs.original().getRequest(), + inputs.original().getOwnerFence(), + UUID.fromString(inputs.original().getTargetFenceUuid()), + snapshot) + .toBuilder() + .setSelectedCharacterUuid(actorId.toString()) + .setSelectionInput( + CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("controlled-test-selection")) + .build(); + var selectedRequest = + CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest( + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(inputs.request().getRequestUuid()) + .setCanonicalAccountUuid(inputs.request().getCanonicalAccountUuid()) + .setSelectedCharacterUuid(actorId.toString()) + .setExpectedTarget(inputs.request().getExpectedTarget()) + .setExpectedSnapshot( + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(snapshot.getRoster().getSnapshotUuid()) + .setSnapshotDigest(snapshot.getRoster().getSnapshotDigest())) + .setExpectedSource(inputs.request().getExpectedSource()) + .setPlayerExecutionContext( + inputs.request().getPlayerExecutionContext().toBuilder() + .setCharacterId(actorId.toString())) + .build()); + var beforeSelectedRead = + dsl.fetchSingle( + "SELECT (SELECT count(*) FROM entity_canonical_gameplay_roster_snapshots) AS snapshots, (SELECT count(*) FROM entity_canonical_gameplay_roster_snapshot_actors) AS actors, (SELECT count(*) FROM entity_canonical_roster_original_selections) AS originals"); + var selectedReceipt = + snapshotRepository.readSelected(selectedRequest, inputs.source(), selectedOriginal); + assertThat(selectedReceipt.getTerminal().toByteArray()).containsExactly(terminal.toByteArray()); + assertThat(selectedReceipt.getCreationOperationUuid()) + .isEqualTo(proof.original().getOperationId()); + assertThat(selectedReceipt.getMutationDigest()).isEqualTo(proof.original().getMutationDigest()); + var afterSelectedRead = + dsl.fetchSingle( + "SELECT (SELECT count(*) FROM entity_canonical_gameplay_roster_snapshots) AS snapshots, (SELECT count(*) FROM entity_canonical_gameplay_roster_snapshot_actors) AS actors, (SELECT count(*) FROM entity_canonical_roster_original_selections) AS originals"); + assertThat(afterSelectedRead.get("snapshots", Long.class)) + .isEqualTo(beforeSelectedRead.get("snapshots", Long.class)); + assertThat(afterSelectedRead.get("actors", Long.class)) + .isEqualTo(beforeSelectedRead.get("actors", Long.class)); + assertThat(afterSelectedRead.get("originals", Long.class)) + .isEqualTo(beforeSelectedRead.get("originals", Long.class)); + + UUID wrongActorId = UUID.randomUUID(); + var wrongActor = + selectedRequest.toBuilder() + .setSelectedCharacterUuid(wrongActorId.toString()) + .setPlayerExecutionContext( + selectedRequest.getPlayerExecutionContext().toBuilder() + .setCharacterId(wrongActorId.toString())) + .build(); + assertThatThrownBy( + () -> snapshotRepository.readSelected(wrongActor, inputs.source(), selectedOriginal)) + .isInstanceOf(IllegalStateException.class); + var wrongSnapshot = + selectedRequest.toBuilder() + .setExpectedSnapshot( + selectedRequest.getExpectedSnapshot().toBuilder().setSnapshotDigest("f".repeat(64))) + .build(); + assertThatThrownBy( + () -> snapshotRepository.readSelected(wrongSnapshot, inputs.source(), selectedOriginal)) + .isInstanceOf(IllegalStateException.class); + var substitutedSource = + selectedRequest.toBuilder() + .setExpectedSource( + inputs.request().getExpectedSource().toBuilder() + .setDescriptorUuid(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> + snapshotRepository.readSelected( + substitutedSource, inputs.source(), selectedOriginal)) + .isInstanceOf(IllegalArgumentException.class); + UUID otherAccount = UUID.randomUUID(); + var substitutedAccount = + selectedRequest.toBuilder() + .setCanonicalAccountUuid(otherAccount.toString()) + .setPlayerExecutionContext( + selectedRequest.getPlayerExecutionContext().toBuilder() + .setAccountId(otherAccount.toString())) + .build(); + assertThatThrownBy( + () -> + snapshotRepository.readSelected( + substitutedAccount, inputs.source(), selectedOriginal)) + .isInstanceOf(IllegalArgumentException.class); + var wrongNamespaceRequest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(inputs.request().getRequestUuid()), + UUID.fromString(inputs.request().getCanonicalAccountUuid()), + UUID.fromString(inputs.request().getPlayerExecutionContext().getSessionId()), + "other", + inputs.request().getExpectedTarget(), + inputs.request().getExpectedSource()); + var wrongNamespaceOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + wrongNamespaceRequest, + selectedOriginal.getOwnerFence(), + UUID.fromString(selectedOriginal.getTargetFenceUuid()), + snapshot); + assertThatThrownBy( + () -> + snapshotRepository.readSelected( + selectedRequest, inputs.source(), wrongNamespaceOriginal)) + .isInstanceOf(IllegalArgumentException.class); + + UUID recoveryId = UUID.randomUUID(); + var recoveryRequest = + CanonicalGameplayRosterRecoveryRequest.newBuilder() + .setSchemaVersion(1) + .setRecoveryUuid(recoveryId.toString()) + .setOriginalSelection(selectedOriginal.getRequest()) + .build(); + var recoveryOwner = selectedOriginal.toBuilder().setRecoveryUuid(recoveryId.toString()).build(); + var retentionRepository = new CanonicalGameplayRosterRetentionRepository(dsl); + transaction.executeWithoutResult( + ignored -> + retentionRepository.closeAdmission( + recoveryRequest, + recoveryOwner, + new CanonicalGameplayRosterRetentionPolicy( + Duration.ofHours(1), + Duration.ofHours(1), + Duration.ofHours(1), + Duration.ofMinutes(1), + 2))); + assertThatThrownBy( + () -> + snapshotRepository.readSelected(selectedRequest, inputs.source(), selectedOriginal)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + + UUID missingOperation = UUID.randomUUID(); + UUID missingSession = UUID.randomUUID(); + var missingRequest = + selectedRequest.toBuilder() + .setRequestUuid(missingOperation.toString()) + .setPlayerExecutionContext( + selectedRequest.getPlayerExecutionContext().toBuilder() + .setRequestId(missingOperation.toString()) + .setSessionId(missingSession.toString())) + .build(); + var missingOwnerRequest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + missingOperation, + UUID.fromString(inputs.request().getCanonicalAccountUuid()), + missingSession, + inputs.source().response().getRequest().getTargetNamespace(), + inputs.request().getExpectedTarget(), + inputs.request().getExpectedSource()); + var missingOwner = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + missingOwnerRequest, + selectedOriginal.getOwnerFence(), + UUID.fromString(selectedOriginal.getTargetFenceUuid()), + snapshot) + .toBuilder() + .setSelectedCharacterUuid(actorId.toString()) + .setSelectionInput( + CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("controlled-test-selection")) + .build(); + assertThatThrownBy( + () -> snapshotRepository.readSelected(missingRequest, inputs.source(), missingOwner)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + + assertThat(snapshot.getRoster().getActorsList()) + .containsExactly( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(actorId.toString()) + .setDisplayName("Wayfarer") + .setActorKind( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind + .CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()); + assertThat(snapshot.getRoster().getSnapshotDigest()) + .isEqualTo( + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + inputs.request().getCanonicalAccountUuid(), + inputs.request().getExpectedTarget(), + inputs.request().getExpectedSource(), + snapshot.getRoster().getActorsList())); + var persistedActor = + dsl.fetchSingle( + "SELECT character_uuid, actor_entry_policy, creation_descriptor_json, creation_descriptor_digest, authored_initial_core_json FROM characters WHERE character_uuid = ?", + actorId); + assertThat(persistedActor.get("actor_entry_policy", String.class)).isEqualTo("PLAYER_CREATED"); + assertThat(persistedActor.get("creation_descriptor_json", String.class)) + .isEqualTo(inputs.source().creationDescriptor().canonicalJson()); + assertThat(persistedActor.get("creation_descriptor_digest", String.class)) + .isEqualTo(inputs.source().creationDescriptor().digest()); + assertThat(persistedActor.get("authored_initial_core_json", String.class)) + .isEqualTo(inputs.source().authored().projections().getFirst().core().canonicalJson()); + assertThat(proof.action().mutation().authoredSource().bindingId()) + .isEqualTo(inputs.source().authored().projections().getFirst().bindingId().toString()); + assertThat(proof.action().mutation().authoredSource().bindingDigest()) + .isEqualTo(inputs.source().authored().projections().getFirst().bindingDigest()); + assertThat( + dsl.fetchSingle( + "SELECT canonical_player_created_source_identity FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + UUID.fromString(snapshot.getRoster().getSnapshotUuid())) + .get("canonical_player_created_source_identity", byte[].class)) + .containsExactly(inputs.request().getExpectedSource().toByteArray()); + assertThat( + dsl.fetchSingle( + "SELECT terminal_bytes FROM entity_character_create_operations WHERE operation_id = ?", + UUID.fromString(proof.original().getOperationId())) + .get("terminal_bytes", byte[].class)) + .containsExactly(terminal.toByteArray()); + } + + @Test + void substitutedSourceAccountSessionAndOriginalNamespaceRefuseBeforeSnapshotWrites() + throws Exception { + var inputs = authenticatedCaptureInputs(); + UUID admission = reserveAdmission(inputs.request()); + var repository = new EntityPlayerCreatedRosterSnapshotRepository(dsl, transactionManager); + + var changedSource = + inputs.request().getExpectedSource().toBuilder() + .setDescriptorUuid(UUID.randomUUID().toString()) + .build(); + var sourceSubstitution = + request( + inputs.source(), + UUID.fromString(inputs.request().getRequestUuid()), + UUID.fromString(inputs.request().getCanonicalAccountUuid()), + UUID.fromString(inputs.request().getPlayerExecutionContext().getSessionId()), + changedSource); + assertThatThrownBy( + () -> + repository.capture( + sourceSubstitution, inputs.source(), inputs.original(), admission)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source identity changed"); + + UUID otherAccount = UUID.randomUUID(); + var accountSubstitution = + request( + inputs.source(), + UUID.fromString(inputs.request().getRequestUuid()), + otherAccount, + UUID.fromString(inputs.request().getPlayerExecutionContext().getSessionId()), + inputs.request().getExpectedSource()); + assertThatThrownBy( + () -> + repository.capture( + accountSubstitution, inputs.source(), inputs.original(), admission)) + .isInstanceOf(IllegalArgumentException.class); + + UUID otherSession = UUID.randomUUID(); + var sessionSubstitution = + request( + inputs.source(), + UUID.fromString(inputs.request().getRequestUuid()), + UUID.fromString(inputs.request().getCanonicalAccountUuid()), + otherSession, + inputs.request().getExpectedSource()); + assertThatThrownBy( + () -> + repository.capture( + sessionSubstitution, inputs.source(), inputs.original(), admission)) + .isInstanceOf(IllegalArgumentException.class); + + var wrongNamespaceRequest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(inputs.request().getRequestUuid()), + UUID.fromString(inputs.request().getCanonicalAccountUuid()), + UUID.fromString(inputs.request().getPlayerExecutionContext().getSessionId()), + "other", + inputs.request().getExpectedTarget(), + inputs.request().getExpectedSource()); + var wrongNamespaceOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + wrongNamespaceRequest, + inputs.original().getOwnerFence(), + UUID.fromString(inputs.original().getTargetFenceUuid()), + null); + assertThatThrownBy( + () -> + repository.capture( + inputs.request(), inputs.source(), wrongNamespaceOriginal, admission)) + .isInstanceOf(IllegalArgumentException.class); + + var isolatedTarget = + inputs.request().getExpectedTarget().toBuilder() + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_ISOLATED) + .build(); + var isolatedRequest = + inputs.request().toBuilder() + .setExpectedTarget(isolatedTarget) + .setPlayerExecutionContext( + inputs.request().getPlayerExecutionContext().toBuilder() + .setPlayableStateScope("ISOLATED")) + .build(); + assertThatThrownBy( + () -> + repository.capture(isolatedRequest, inputs.source(), inputs.original(), admission)) + .isInstanceOf(IllegalArgumentException.class); + + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshots"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_original_selections"))).isZero(); + var localAdmission = + dsl.fetchSingle( + "SELECT snapshot_uuid, admission_state FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", + UUID.fromString(inputs.request().getRequestUuid())); + assertThat(localAdmission.get("snapshot_uuid", UUID.class)).isNull(); + assertThat(localAdmission.get("admission_state", String.class)).isEqualTo("OPEN"); + } + + @Test + void failedOriginalBindRollsBackTheSnapshotAndAdmissionBinding() throws Exception { + var inputs = authenticatedCaptureInputs(); + UUID admission = reserveAdmission(inputs.request()); + dsl.execute( + "CREATE FUNCTION fail_player_created_original_bind() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'controlled original bind failure'; END $$"); + dsl.execute( + "CREATE TRIGGER fail_player_created_original_bind BEFORE INSERT ON entity_canonical_roster_original_selections FOR EACH ROW EXECUTE FUNCTION fail_player_created_original_bind()"); + var repository = new EntityPlayerCreatedRosterSnapshotRepository(dsl, transactionManager); + + assertThatThrownBy( + () -> + repository.capture(inputs.request(), inputs.source(), inputs.original(), admission)) + .isInstanceOf(DataAccessException.class); + + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshots"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshot_actors"))) + .isZero(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retention_lifecycle"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_original_selections"))).isZero(); + var localAdmission = + dsl.fetchSingle( + "SELECT snapshot_uuid, admission_state FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", + UUID.fromString(inputs.request().getRequestUuid())); + assertThat(localAdmission.get("snapshot_uuid", UUID.class)).isNull(); + assertThat(localAdmission.get("admission_state", String.class)).isEqualTo("OPEN"); + } + + private void enroll(UUID tenant, UUID namespace) { + dsl.execute("INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)", tenant); + dsl.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, 'PLAYABLE_STATE_SCOPE_SHARED')", + tenant, + namespace); + } + + private void insertBuildingSnapshot(UUID snapshot, UUID tenant, UUID namespace, byte[] source) { + dsl.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshots (snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, canonical_version_uuid, pointer_version, active_world_epoch, published_policy_digest, published_release_bundle_ref, admission_pointer_snapshot_digest, published_owner_proof_digest, playable_state_namespace_uuid, playable_state_scope, entry_policy, publication_evidence_format, canonical_player_created_source_identity, roster_count, construction_state) VALUES (?, ?, ?, ?, ?, 'world', 'realm', ?, 3, ?, 5, 7, ?, 'published-release', ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 'PLAYER_CREATED', 'CANONICAL_UUID_V2', ?, 0, 'BUILDING')", + snapshot, + UUID.randomUUID().toString().replace("-", "").repeat(2), + UUID.randomUUID(), + tenant, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + "b".repeat(64), + "c".repeat(64), + namespace, + source); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity() { + return CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(UUID.randomUUID().toString()) + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .setDescriptorDigest("sha256:" + "1".repeat(64)) + .setAuthoredBindingUuid(UUID.randomUUID().toString()) + .setAuthoredBindingDigest("sha256:" + "2".repeat(64)) + .build(); + } + + private CaptureInputs authenticatedCaptureInputs() throws Exception { + return authenticatedCaptureInputs(UUID.randomUUID(), null); + } + + private CaptureInputs authenticatedCaptureInputs(UUID account, UUID selectedCommitId) + throws Exception { + var controlled = new ControlledPlayerCreatedRosterSourceFixture(certificateDirectory); + WireFixture wire = + selectedCommitId == null + ? controlled.wireFixture() + : controlled.wireFixture("canonical-instance-launch-descriptor", selectedCommitId); + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { + owner.respondWith(wire.response()); + client.init(); + var source = client.read(wire.request()); + assertThat(owner.receivedRequests()).containsExactly(wire.request()); + assertThat(owner.observedPeerUri()) + .isEqualTo("spiffe://firemud/ns/test/sa/entity-management-service"); + return inputs(source, account); + } + } + + private static CaptureInputs inputs( + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source, UUID account) { + UUID operation = UUID.randomUUID(); + UUID session = UUID.randomUUID(); + var sourceIdentity = sourceIdentity(source); + var request = request(source, operation, account, session, sourceIdentity); + var originalRequest = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + operation, + account, + session, + source.response().getRequest().getTargetNamespace(), + source.target().toWire(), + sourceIdentity); + var original = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + originalRequest, 1L, UUID.randomUUID(), null); + return new CaptureInputs(request, source, original); + } + + private static CanonicalPlayerCreatedRosterRequest request( + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source, + UUID operation, + UUID account, + UUID session, + CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity) { + var target = source.target().toWire(); + return CanonicalPlayerCreatedRosterEvidence.requireRequest( + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(operation.toString()) + .setCanonicalAccountUuid(account.toString()) + .setExpectedTarget(target) + .setExpectedSource(sourceIdentity) + .setPlayerExecutionContext( + PlayerExecutionContext.newBuilder() + .setRequestId(operation.toString()) + .setAccountId(account.toString()) + .setSessionId(session.toString()) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setPlayableStateScope("SHARED")) + .build()); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity( + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source) { + var descriptor = source.creationDescriptor(); + var projection = source.authored().projections().getFirst(); + return CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(projection.bindingId().toString()) + .setAuthoredBindingDigest(projection.bindingDigest()) + .build()); + } + + private UUID reserveAdmission(CanonicalPlayerCreatedRosterRequest request) { + var retention = new CanonicalGameplayRosterRetentionRepository(dsl); + return transaction.execute(ignored -> retention.reserveAdmission(request)); + } + + private record CaptureInputs( + CanonicalPlayerCreatedRosterRequest request, + EntityPlayerCreatedRosterSourceClient.AuthenticatedSource source, + GetCanonicalGameplayRosterReferenceResponse original) {} + + private static DriverManagerDataSource dataSource(String schema) { + String url = postgres.getJdbcUrl(); + if (schema != null) url += (url.contains("?") ? "&" : "?") + "currentSchema=" + schema; + return new DriverManagerDataSource(url, postgres.getUsername(), postgres.getPassword()); + } + + private static org.flywaydb.core.api.configuration.FluentConfiguration migrationConfiguration( + DriverManagerDataSource dataSource, String schema) { + var configuration = + Flyway.configure() + .dataSource(dataSource) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(), + "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + configuration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + return configuration; + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java index 655ff874e9..929692169c 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java @@ -15,6 +15,7 @@ import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.entitymanagement.repository.CanonicalGameplayRosterRetentionRepository.ReferenceKind; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; @@ -30,6 +31,9 @@ import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; import net.firedevops.firemud.test.TestContainerImages; @@ -66,6 +70,8 @@ class CanonicalGameplayRosterRetentionPostgresIntegrationTest { private TransactionTemplate transaction; private CanonicalGameplayRosterRetentionRepository repository; private CanonicalGameplayRosterRetentionBinding binding; + private List installed1015History; + private List retained1015Rows; @BeforeEach void upgradeRetainedV1011ActorReceiptAndSealedSnapshot() { @@ -84,6 +90,14 @@ void upgradeRetainedV1011ActorReceiptAndSealedSnapshot() { List retained = retainedRows(); migrate(dataSource, "1014"); assertThat(retainedRows()).containsExactlyElementsOf(retained); + migrate(dataSource, "1015"); + dsl.execute( + "INSERT INTO entity_canonical_roster_retention_lifecycle (snapshot_uuid, snapshot_digest) VALUES (?, ?)", + binding.snapshot().snapshotUuid(), + binding.snapshot().snapshotDigest()); + installed1015History = migrationHistory(); + retained1015Rows = retainedBeforeCreatedExtension(); + migrate(dataSource, "1016"); } @AfterEach @@ -94,6 +108,484 @@ void dropOwnedFixture() { } } + @Test + void forward1015To1016PreservesInstalledHistoryRetainedRowsAndOldSnapshotGuards() { + var history = migrationHistory(); + assertThat(history.subList(0, installed1015History.size())) + .containsExactlyElementsOf(installed1015History); + assertThat(history).hasSize(installed1015History.size() + 1); + assertThat(history.getLast()) + .contains("1016", "V1016__player_created_roster_snapshot_receipts.sql"); + assertThat(retainedBeforeCreatedExtension()).containsExactlyElementsOf(retained1015Rows); + var row = + dsl.fetchSingle( + "SELECT entry_policy, canonical_player_created_source_identity FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid()); + assertThat(row.get("entry_policy", String.class)).isEqualTo("PRESEEDED_ONLY"); + assertThat(row.get("canonical_player_created_source_identity", byte[].class)).isNull(); + assertThat( + dsl.fetchSingle( + "SELECT entry_policy FROM entity_canonical_roster_retention_lifecycle WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid()) + .get(0, String.class)) + .isEqualTo("PRESEEDED_ONLY"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + new byte[] {1}, + binding.snapshot().snapshotUuid())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE entity_canonical_gameplay_roster_snapshots CASCADE")) + .isInstanceOf(DataAccessException.class); + } + + @Test + void createdAdmissionAndOriginalRecoveryKeepExactSourceAndDistinctReceiptBranch() { + var request = createdRequest(); + UUID nonce = transaction.execute(ignored -> repository.reserveAdmission(request)); + assertThat(transaction.execute(ignored -> repository.reserveAdmission(request))) + .isEqualTo(nonce); + var changed = + request.toBuilder() + .setExpectedSource( + request.getExpectedSource().toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy(() -> transaction.execute(ignored -> repository.reserveAdmission(changed))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT"); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> repository.requireAdmission(changed, nonce))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + var invalidPolicy = request.toBuilder().setExpectedTarget(binding.target().toWire()).build(); + assertThatThrownBy( + () -> transaction.execute(ignored -> repository.reserveAdmission(invalidPolicy))) + .isInstanceOf(IllegalArgumentException.class); + var original = createdOriginal(request); + var owner = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 1, UUID.randomUUID(), null); + var receipt = createdReceipt(request); + transaction.executeWithoutResult( + ignored -> { + assertThat(repository.originalPlayerCreatedReceipt(owner)).isEmpty(); + seedCreatedSnapshot(receipt, 0); + repository.requireAdmission(request, nonce); + repository.bindPlayerCreatedOriginal(owner, receipt); + repository.bindAdmission( + UUID.fromString(request.getRequestUuid()), + nonce, + UUID.fromString(receipt.getRoster().getSnapshotUuid())); + assertThat(repository.originalPlayerCreatedReceipt(owner)).contains(receipt); + }); + assertThatThrownBy(() -> transaction.execute(ignored -> repository.originalReceipt(owner))) + .isInstanceOf(IllegalArgumentException.class); + var wrongSourceOwner = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + createdOriginal(changed), 1, UUID.fromString(owner.getTargetFenceUuid()), null); + assertThatThrownBy( + () -> + transaction.execute( + ignored -> repository.originalPlayerCreatedReceipt(wrongSourceOwner))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT"); + var recovery = + CanonicalGameplayRosterRecoveryRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(original) + .setRecoveryUuid(UUID.randomUUID().toString()) + .build(); + var recovering = owner.toBuilder().setRecoveryUuid(recovery.getRecoveryUuid()).build(); + var closed = + transaction.execute( + ignored -> + repository.closeAdmission(recovery, recovering, policy(Duration.ofHours(1)))); + assertThat(closed.getAdmissionUuid()).isEqualTo(nonce.toString()); + assertThat(closed.getCanonicalRosterReceipt()).isEmpty(); + assertThat(closed.getCanonicalPlayerCreatedRosterReceipt()).isEqualTo(receipt.toByteString()); + var replay = + transaction.execute( + ignored -> + repository.closeAdmission(recovery, recovering, policy(Duration.ofHours(2)))); + assertThat(replay).isEqualTo(closed); + var stored = + dsl.fetchSingle( + "SELECT entry_policy, canonical_roster_receipt, canonical_player_created_roster_receipt FROM entity_canonical_roster_original_selections WHERE operation_uuid = ?", + UUID.fromString(request.getRequestUuid())); + assertThat(stored.get("entry_policy", String.class)).isEqualTo("PLAYER_CREATED"); + assertThat(stored.get("canonical_roster_receipt", byte[].class)).isNull(); + assertThat(stored.get("canonical_player_created_roster_receipt", byte[].class)) + .isEqualTo(receipt.toByteArray()); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + changed.getExpectedSource().toByteArray(), + UUID.fromString(receipt.getRoster().getSnapshotUuid()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET entry_policy = 'PRESEEDED_ONLY' WHERE operation_uuid = ?", + UUID.fromString(request.getRequestUuid()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_canonical_roster_original_selections SET canonical_roster_receipt = ? WHERE operation_uuid = ?", + receipt.getRoster().toByteArray(), + UUID.fromString(request.getRequestUuid()))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void createdSnapshotRequiresSharedSourceAndRejectsPreseededActorSubstitution() { + var request = createdRequest(); + var receipt = createdReceipt(request); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> + seedCreatedSnapshot(receipt.toBuilder().clearSourceIdentity().build(), 0))) + .isInstanceOf(DataAccessException.class); + var oversized = + receipt.toBuilder() + .setSourceIdentity( + receipt.getSourceIdentity().toBuilder().setDescriptorDigest("x".repeat(4097))) + .build(); + assertThatThrownBy( + () -> transaction.executeWithoutResult(ignored -> seedCreatedSnapshot(oversized, 0))) + .isInstanceOf(DataAccessException.class); + var isolated = + receipt.toBuilder() + .setRoster( + receipt.getRoster().toBuilder() + .setTarget( + request.getExpectedTarget().toBuilder() + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED))) + .build(); + assertThatThrownBy( + () -> transaction.executeWithoutResult(ignored -> seedCreatedSnapshot(isolated, 0))) + .isInstanceOf(DataAccessException.class); + transaction.executeWithoutResult(ignored -> seedCreatedSnapshot(receipt, 1)); + UUID actor = + dsl.fetchSingle( + "SELECT character_uuid FROM entity_canonical_gameplay_roster_snapshot_actors WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid()) + .get(0, UUID.class); + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshot_actors (snapshot_uuid, ordinal_position, character_uuid, display_name, actor_kind) VALUES (?, 0, ?, 'Retained Actor', 'PLAYER')", + UUID.fromString(receipt.getRoster().getSnapshotUuid()), + actor)) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET construction_state = 'SEALED' WHERE snapshot_uuid = ?", + UUID.fromString(receipt.getRoster().getSnapshotUuid()))) + .isInstanceOf(DataAccessException.class); + } + + @Test + void createdRetirementPreservesFullSourceThroughOutboxAndKeepsPreseededFamilyProtected() { + var request = createdRequest(); + var original = createdOriginal(request); + var owner = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 1, UUID.randomUUID(), null); + var receipt = createdReceipt(request); + UUID nonce = transaction.execute(ignored -> repository.reserveAdmission(request)); + transaction.executeWithoutResult( + ignored -> { + seedCreatedSnapshot(receipt, 0); + repository.requireAdmission(request, nonce); + repository.bindPlayerCreatedOriginal(owner, receipt); + repository.bindAdmission( + UUID.fromString(request.getRequestUuid()), + nonce, + UUID.fromString(receipt.getRoster().getSnapshotUuid())); + }); + var recorded = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 1, UUID.fromString(owner.getTargetFenceUuid()), receipt); + var proof = retirement(recorded, null); + var candidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); + transaction.executeWithoutResult( + ignored -> + assertThat(repository.observeRetirement(candidate, proof, policy(Duration.ofMillis(1)))) + .isTrue()); + var transfer = + transaction.execute(ignored -> repository.retirementTransfers(null, 1)).getFirst(); + assertThat(transfer.acknowledgementRequest().getObservedRetirement()).isEqualTo(proof); + assertThat( + transfer.acknowledgementRequest().getObservedRetirement().getCanonicalRosterReceipt()) + .isEmpty(); + assertThat( + transfer + .acknowledgementRequest() + .getObservedRetirement() + .getCanonicalPlayerCreatedRosterReceipt()) + .isEqualTo(receipt.toByteString()); + assertThat( + transfer + .acknowledgementRequest() + .getOriginalSelection() + .getCanonicalPlayerCreatedSourceIdentity()) + .isEqualTo(request.getExpectedSource().toByteString()); + assertThat( + dsl.fetchSingle( + "SELECT entry_policy FROM entity_canonical_roster_retirement_transfers WHERE observation_uuid = ?", + transfer.observationUuid()) + .get(0, String.class)) + .isEqualTo("PLAYER_CREATED"); + assertThatThrownBy(() -> transaction.execute(ignored -> repository.reserveAdmission(request))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + assertThatThrownBy( + () -> dsl.execute("DELETE FROM entity_canonical_roster_retirement_transfers")) + .isInstanceOf(DataAccessException.class); + transaction.executeWithoutResult( + ignored -> assertThat(repository.protection(binding).disposalEligible()).isFalse()); + dsl.fetch("SELECT pg_sleep(0.02)"); + var retiredCandidate = + transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); + assertThat(transaction.execute(ignored -> repository.dispose(retiredCandidate))) + .isTrue(); + var retainedTransfer = + transaction.execute(ignored -> repository.retirementTransfers(null, 1)).getFirst(); + assertThat(retainedTransfer).isEqualTo(transfer); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshots"))) + .isEqualTo(1); + assertThat( + dsl.fetchSingle("SELECT snapshot_uuid FROM entity_canonical_gameplay_roster_snapshots") + .get(0, UUID.class)) + .isEqualTo(binding.snapshot().snapshotUuid()); + } + + @Test + void createdOutboxStorageBudgetDoesNotWidenPreseededOrAuthenticateOpaqueBytes() { + var created = createdRequest(); + var createdOriginal = createdOriginal(created); + var createdRecovery = + CanonicalGameplayRosterRecoveryRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(createdOriginal) + .setRecoveryUuid(UUID.randomUUID().toString()) + .build(); + var createdOwner = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + createdOriginal, 1, UUID.randomUUID(), null) + .toBuilder() + .setRecoveryUuid(createdRecovery.getRecoveryUuid()) + .build(); + transaction.executeWithoutResult( + ignored -> + repository.closeAdmission(createdRecovery, createdOwner, policy(Duration.ofHours(1)))); + var preseeded = localRequest(); + var preseededRecovery = recovery(preseeded); + var preseededOwner = recoveryOwner(preseededRecovery); + transaction.executeWithoutResult( + ignored -> + repository.closeAdmission( + preseededRecovery, preseededOwner, policy(Duration.ofHours(1)))); + byte[] rawRequest = new byte[128 * 1024 + 1]; + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> + insertRawTransferForBudget( + preseeded.requestUuid(), retirement(preseededOwner, null), rawRequest))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("ck_entity_roster_transfer_policy_request"); + // Raw SQL tests only the policy-specific byte budget. Opaque request bytes remain invalid + // to the repository's value parser and never become authenticated acknowledgement authority. + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> { + insertRawTransferForBudget( + UUID.fromString(created.getRequestUuid()), + retirement(createdOwner, null), + rawRequest); + assertThat( + dsl.fetchCount( + DSL.table("entity_canonical_roster_retirement_transfers"))) + .isEqualTo(1); + assertThatThrownBy(() -> repository.retirementTransfers(null, 1)) + .isInstanceOf(IllegalStateException.class); + throw new IllegalStateException("controlled byte-budget rollback"); + })) + .hasMessage("controlled byte-budget rollback"); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))).isZero(); + } + + private void insertRawTransferForBudget( + UUID operation, GetCanonicalGameplayRosterReferenceResponse proof, byte[] request) { + dsl.execute( + "INSERT INTO entity_canonical_roster_retirement_transfers " + + "(observation_uuid, operation_uuid, original_request, admission_uuid, closed_admission_receipt, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state, observed_retirement, acknowledgement_request, request_digest, entry_policy) " + + "SELECT ?, operation_uuid, recovery_owner_request, admission_uuid, recovery_response, recovery_owner_fence, recovery_target_fence_uuid, minimum_retention_millis, 'PENDING_ACK', ?, ?, ?, entry_policy FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", + UUID.randomUUID(), + proof.toByteArray(), + request, + "a".repeat(64), + operation); + } + + private List migrationHistory() { + return dsl.fetch( + "SELECT to_jsonb(t)::TEXT || ':' || xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank") + .getValues(0, String.class); + } + + private List retainedBeforeCreatedExtension() { + return List.of( + "characters", + "entity_preseeded_actor_assignment_operations", + "entity_canonical_gameplay_roster_snapshots", + "entity_canonical_gameplay_roster_snapshot_actors", + "entity_canonical_roster_retention_lifecycle") + .stream() + .flatMap( + table -> { + String projection = + table.equals("entity_canonical_gameplay_roster_snapshots") + ? "to_jsonb(t) - 'canonical_player_created_source_identity'" + : table.equals("entity_canonical_roster_retention_lifecycle") + ? "to_jsonb(t) - 'entry_policy'" + : "to_jsonb(t)"; + return dsl + .fetch( + "SELECT (" + + projection + + ")::TEXT || ':' || xmin::TEXT FROM " + + table + + " t ORDER BY (" + + projection + + ")::TEXT") + .getValues(0, String.class) + .stream(); + }) + .toList(); + } + + // Pure source values and empty persisted snapshots are controlled storage fixtures, not + // authority. + private CanonicalPlayerCreatedRosterRequest createdRequest() { + var target = + binding.target().toWire().toBuilder() + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .build(); + var source = + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(UUID.randomUUID().toString()) + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .setDescriptorDigest("sha256:" + "a".repeat(64)) + .setAuthoredBindingUuid(UUID.randomUUID().toString()) + .setAuthoredBindingDigest("sha256:" + "b".repeat(64)) + .build(); + UUID operation = UUID.randomUUID(); + return CanonicalPlayerCreatedRosterEvidence.requireRequest( + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(operation.toString()) + .setCanonicalAccountUuid(binding.canonicalAccountUuid().toString()) + .setExpectedTarget(target) + .setExpectedSource(source) + .setPlayerExecutionContext( + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setRequestId(operation.toString()) + .setAccountId(binding.canonicalAccountUuid().toString()) + .setSessionId(UUID.randomUUID().toString()) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setPlayableStateScope("SHARED")) + .build()); + } + + private static net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest + createdOriginal(CanonicalPlayerCreatedRosterRequest request) { + return CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), + "gameplay", + request.getExpectedTarget(), + request.getExpectedSource()); + } + + private static CanonicalPlayerCreatedRosterResponse createdReceipt( + CanonicalPlayerCreatedRosterRequest request) { + return CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(request.getExpectedSource()) + .setRoster( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse + .newBuilder() + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(UUID.randomUUID().toString()) + .setSnapshotDigest( + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), + request.getExpectedTarget(), + request.getExpectedSource(), + List.of()))) + .build()); + } + + private void seedCreatedSnapshot(CanonicalPlayerCreatedRosterResponse receipt, int count) { + var roster = receipt.getRoster(); + var target = roster.getTarget(); + dsl.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshots " + + "(snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, canonical_version_uuid, pointer_version, active_world_epoch, published_policy_digest, published_release_bundle_ref, admission_pointer_snapshot_digest, published_owner_proof_digest, playable_state_namespace_uuid, playable_state_scope, entry_policy, canonical_player_created_source_identity, roster_count) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PLAYER_CREATED', ?, ?)", + UUID.fromString(roster.getSnapshotUuid()), + roster.getSnapshotDigest(), + UUID.fromString(roster.getCanonicalAccountUuid()), + UUID.fromString(target.getTenantUuid()), + UUID.fromString(target.getRealmUuid()), + target.getWorldSlug(), + target.getRealmSlug(), + UUID.fromString(target.getGameInstanceUuid()), + target.getCatalogRevision(), + UUID.fromString(target.getCanonicalVersionUuid()), + target.getPointerVersion(), + target.getActiveWorldEpoch(), + target.getPublishedPolicyDigest(), + target.getPublishedReleaseBundleRef(), + target.getAdmissionPointerSnapshotDigest(), + target.getPublishedOwnerProofDigest(), + UUID.fromString(target.getPlayableStateNamespaceUuid()), + target.getPlayableStateScope().name(), + receipt.hasSourceIdentity() ? receipt.getSourceIdentity().toByteArray() : null, + count); + if (count == 0) + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET construction_state = 'SEALED' WHERE snapshot_uuid = ?", + UUID.fromString(roster.getSnapshotUuid())); + } + @Test void immutableAcquireReleaseAndHoldOutcomesNeverGrantTerminality() { UUID acquireOperation = UUID.randomUUID(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index d245106fa0..2b20f86c87 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -99,13 +99,22 @@ void seedLegacyRowsBeforeV1011() { flywayConfiguration.load().migrate(); dsl = DSL.using(dataSource, SQLDialect.POSTGRES); assertThat(retainedParentRows(dsl)).isEqualTo(parentRows); + assertThat( + dsl.fetch( + "SELECT creation_target_namespace, creation_operation_id, actor_entry_policy, " + + "authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters")) + .allSatisfy(row -> assertThat(row.intoArray()).containsOnlyNulls()); + assertThat( + dsl.fetch( + "SELECT canonical_player_created_source_identity FROM entity_canonical_gameplay_roster_snapshots WHERE entry_policy = 'PRESEEDED_ONLY'")) + .allSatisfy(row -> assertThat(row.get(0, byte[].class)).isNull()); assertThat(history(dsl).subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); assertThat( dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1014"); + .isEqualTo("1016"); } @AfterEach @@ -236,13 +245,26 @@ private static Map> retainedParentRows(DSLContext source) { "entity_canonical_gameplay_roster_snapshot_actors", "saga_instance", "saga_step")) { + String retainedProjection = + switch (table) { + case "characters" -> + "to_jsonb(t) - 'creation_target_namespace' - 'creation_operation_id' - 'actor_entry_policy' " + + "- 'authored_initial_core_json' - 'creation_descriptor_json' - 'creation_descriptor_digest'"; + case "entity_canonical_gameplay_roster_snapshots" -> + "to_jsonb(t) - 'canonical_player_created_source_identity'"; + default -> "to_jsonb(t)"; + }; rows.put( table, source .fetch( - "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + "SELECT jsonb_build_object('row', " + + retainedProjection + + ", 'xmin', t.xmin::TEXT)::TEXT FROM " + table - + " t ORDER BY to_jsonb(t)::TEXT") + + " t ORDER BY (" + + retainedProjection + + ")::TEXT") .getValues(0, String.class)); } return rows; diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java index b776b87265..1b3b353c46 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java @@ -6,6 +6,7 @@ import java.time.OffsetDateTime; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; @@ -78,7 +79,11 @@ public final class EntityEmptySelectedSourceIntakePostgresFixture { private EntityEmptySelectedSourceIntakePostgresFixture() {} public static Fixture create(String sourceEpoch) { - DraftCommitBinding selected = selected(); + return create(sourceEpoch, selected(id("44444444-4444-4444-8444-444444444444"))); + } + + public static Fixture create(String sourceEpoch, DraftCommitBinding selected) { + Objects.requireNonNull(selected, "selected"); var scope = new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( Owner.ENTITY_MANAGEMENT, NAMESPACE, OPERATION, FENCE, INTAKE_REQUEST, ACTOR, selected); @@ -133,7 +138,7 @@ private static TemplateConfigSourceSnapshot templateSnapshot( + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); String declarationPayload = TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration); - DraftCommitBinding authored = authoredBinding(declarationPayload); + DraftCommitBinding authored = authoredBinding(declarationPayload, selected.target()); TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = TemplateConfigSourceValues.mutations(authored).stream() .filter( @@ -152,9 +157,9 @@ private static TemplateConfigSourceSnapshot templateSnapshot( List.of(ownerDeclaration)); } - private static DraftCommitBinding authoredBinding(String payload) { + private static DraftCommitBinding authoredBinding(String payload, TargetProof target) { return DraftCommitBinding.create( - target(), + target, id("51515151-5151-4151-8151-515151515151"), id("52525252-5252-4252-8252-525252525252"), "base-commit-0", @@ -246,11 +251,11 @@ private static SourceEvidence source(SourceKind kind, String scope, String marke kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); } - private static DraftCommitBinding selected() { + private static DraftCommitBinding selected(UUID selectedCommitId) { return DraftCommitBinding.create( target(), id("33333333-3333-4333-8333-333333333333"), - id("44444444-4444-4444-8444-444444444444"), + selectedCommitId, "base-commit-0", List.of( new RevisionPayload( diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java new file mode 100644 index 0000000000..fbb4b93ad9 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import java.io.InputStream; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import org.junit.jupiter.api.Test; + +/** Controlled byte-contract proof only; fixture source bytes do not authenticate an owner. */ +class EntityCharacterCreateBindingsTest { + @Test + void strictOriginalPreservesEmptyInputAndAuthoredGenericCore() throws Exception { + var original = original(); + var action = EntityCharacterCreateBindings.requireOriginal(reference(original), original); + assertThat(action.mutation().canonicalCreationInput()).isEqualTo("{}"); + assertThat(action.mutation().authoredSource().core().canonicalJson()).contains("Wayfarer"); + assertThatThrownBy( + () -> + EntityCharacterCreateBindings.requireOriginal( + reference(original), + original.toBuilder() + .setAuthenticatedAccountId(UUID.randomUUID().toString()) + .build())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy( + () -> + EntityCharacterCreateBindings.requireOriginal( + reference(original), + original.toBuilder().setOriginalSourceReadback(ByteString.EMPTY).build())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + + @Test + void protectionRequiresExactOriginalOperationSourceAndFence() throws Exception { + var original = original(); + var accountRef = protection(); + var request = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(reference(original)) + .setAccountProtection(accountRef) + .setGameSessionProtection(protection()) + .setWorldProtection(protection()) + .build(); + var proof = + ReadOriginalCharacterCreateProtectionResponse.newBuilder() + .setOriginal(original) + .setAccountProtectionId(accountRef.getProtectionId()) + .setAccountProtectionFence(accountRef.getProtectionFence()) + .setAcquiredAt("2026-10-11T12:35:00Z") + .setOriginalMembershipSnapshot(ByteString.copyFromUtf8("fixture-membership")) + .setOriginalEntitlementSnapshot(ByteString.copyFromUtf8("fixture-entitlement")) + .build(); + EntityCharacterCreateBindings.requireAccountProtection(request, original, proof); + assertThatThrownBy( + () -> + EntityCharacterCreateBindings.requireAccountProtection( + request, + original, + proof.toBuilder() + .setOriginal( + original.toBuilder() + .setOriginalSourceReadback( + ByteString.copyFromUtf8("different-source"))) + .build())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy( + () -> + EntityCharacterCreateBindings.requireAccountProtection( + request, original, proof.toBuilder().setAccountProtectionFence(2L).build())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + + @Test + void unavailableGameSessionCreationAuthorityCannotBecomePositiveRosterEvidence() { + assertThatThrownBy( + () -> + GameSessionCharacterCreateProtectionReader.unavailable() + .readOriginal( + ReadOriginalCharacterCreateProtectionResponse.getDefaultInstance(), + protection())) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("UNAVAILABLE"); + } + + @Test + void allThreePositiveCanonicalReferencesAreRequired() throws Exception { + var request = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(reference(original())) + .setAccountProtection(protection()) + .setGameSessionProtection(protection()) + .setWorldProtection(protection()) + .build(); + EntityCharacterCreateBindings.requireRequest(request); + assertThatThrownBy( + () -> + EntityCharacterCreateBindings.requireRequest( + request.toBuilder().clearWorldProtection().build())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy( + () -> + EntityCharacterCreateBindings.requireRequest( + request.toBuilder() + .setGameSessionProtection( + request.getGameSessionProtection().toBuilder().setProtectionFence(0L)) + .build())) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } + + private static ReadOriginalCharacterCreateResponse original() throws Exception { + byte[] bytes; + try (InputStream input = + Objects.requireNonNull( + EntityCharacterCreateBindingsTest.class.getResourceAsStream( + "/charactercreate/entity-public-action.json"))) { + bytes = + new String(input.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8) + .strip() + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + return ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace("firemud") + .setOperationId(UUID.randomUUID().toString()) + .setCreateCharacterRequestId(UUID.randomUUID().toString()) + .setConnectScopeId("Issued.Scope-Exact_Opaque.mixedCase-01") + .setAuthenticatedAccountId("a4000000-0000-4000-8000-000000000001") + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(bytes)) + .setMutationDigest(CharacterCreateOperatorActionCodec.mutationDigest(bytes)) + .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-source")) + .build(); + } + + private static ReadOriginalCharacterCreateRequest reference( + ReadOriginalCharacterCreateResponse original) { + return ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(original.getTargetNamespace()) + .setOperationId(original.getOperationId()) + .setMutationDigest(original.getMutationDigest()) + .build(); + } + + private static CharacterCreateProtectionReference protection() { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(UUID.randomUUID().toString()) + .setProtectionFence(1L) + .build(); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java new file mode 100644 index 0000000000..83cb5ccb47 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java @@ -0,0 +1,169 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +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.when; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.client.AccountCharacterCreateSourceClient; +import net.firedevops.firemud.entitymanagement.client.WorldCharacterCreateLifecycleClient; +import net.firedevops.firemud.entitymanagement.v1.AbortProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadEntityCharacterCreateTerminalRequest; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Native incoming identity proof only. Owner storage and creation dependencies deliberately deny. + */ +class EntityCharacterCreateMtlsTest { + @TempDir Path directory; + + @Test + void ownerCertificatesHaveDistinctReadAndMutationPermissions() throws Exception { + var pki = + LoopbackMtlsTestPki.create( + directory, + "Entity creation proof CA", + identity("entity", "firemud", "entity-management-service", true), + identity("account", "firemud", "account-service", false), + identity("game-session", "firemud", "game-session-service", false), + identity("world", "firemud", "world-management-service", false), + identity("other-namespace", "other", "account-service", false), + identity("other-service", "firemud", "game-design-service", false)); + var repository = mock(EntityCharacterCreateRepository.class); + when(repository.read(any())).thenReturn(Optional.empty()); + when(repository.replay(any())).thenReturn(Optional.empty()); + var account = mock(AccountCharacterCreateSourceClient.class); + when(account.readOriginal(any())) + .thenThrow( + Status.UNAVAILABLE + .withDescription("Controlled missing Account authority") + .asRuntimeException()); + var service = + new EntityCharacterCreateService( + "firemud", + account, + GameSessionCharacterCreateProtectionReader.unavailable(), + mock(WorldCharacterCreateLifecycleClient.class), + mock(EntityCharacterCreateSource.class), + repository); + var entity = pki.identity("entity"); + Server server = + NettyServerBuilder.forPort(0) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(entity.privateKey(), entity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new EntityCharacterCreateGrpcService(service), + new EntityCharacterCreatePeerInterceptor("firemud"))) + .build() + .start(); + try { + var original = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace("firemud") + .setOperationId(UUID.randomUUID().toString()) + .setMutationDigest("a".repeat(64)) + .build(); + var read = + ReadEntityCharacterCreateTerminalRequest.newBuilder().setOriginal(original).build(); + var commit = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(original) + .setAccountProtection(reference()) + .setGameSessionProtection(reference()) + .setWorldProtection(reference()) + .build(); + var abort = + AbortProtectedCharacterCreateRequest.newBuilder() + .setCreation(commit) + .setAbortRequestId(UUID.randomUUID().toString()) + .build(); + for (String alias : + new String[] {"account", "game-session", "world", "other-namespace", "other-service"}) { + ManagedChannel channel = channel(server.getPort(), pki, alias); + try { + var stub = + EntityCharacterCreateServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS); + boolean owner = + alias.equals("account") || alias.equals("game-session") || alias.equals("world"); + assertThatThrownBy(() -> stub.readEntityCharacterCreateTerminal(read)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining(owner ? "NOT_FOUND" : "PERMISSION_DENIED"); + assertThatThrownBy(() -> stub.commitProtectedCharacterCreate(commit)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining(alias.equals("account") ? "UNAVAILABLE" : "PERMISSION_DENIED"); + assertThatThrownBy(() -> stub.abortProtectedCharacterCreate(abort)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining(alias.equals("account") ? "UNAVAILABLE" : "PERMISSION_DENIED"); + } finally { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + ManagedChannel noCertificate = + NettyChannelBuilder.forAddress("localhost", server.getPort()) + .sslContext(GrpcSslContexts.forClient().trustManager(pki.caCertificate()).build()) + .build(); + try { + assertThatThrownBy( + () -> + EntityCharacterCreateServiceGrpc.newBlockingStub(noCertificate) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readEntityCharacterCreateTerminal(read)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + } finally { + noCertificate.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static ManagedChannel channel(int port, LoopbackMtlsTestPki.Pki pki, String alias) + throws Exception { + var identity = pki.identity(alias); + return NettyChannelBuilder.forAddress("localhost", port) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(identity.privateKey(), identity.certificate(), pki.caCertificate()) + .build()) + .build(); + } + + private static IdentitySpec identity( + String alias, String namespace, String service, boolean server) { + return new IdentitySpec(alias, "spiffe://firemud/ns/" + namespace + "/sa/" + service, server); + } + + private static CharacterCreateProtectionReference reference() { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(UUID.randomUUID().toString()) + .setProtectionFence(1L) + .build(); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java new file mode 100644 index 0000000000..e5f6c9fb29 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java @@ -0,0 +1,118 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.UUID; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.PublishedIdentity; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Order-only unit proof; authenticated source custody is exercised by the loopback mTLS test. */ +class EntityPlayerCreatedRosterReadServiceTest { + @AfterEach + void clearTransactionMarker() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsNilAuthenticatedAccountSelector() { + assertThatThrownBy(() -> new AuthenticatedAccountSelector(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void refusesAmbientSqlBeforeCallingTheSourceOwner() { + var repository = mock(EntityCharacterCreateRepository.class); + var source = mock(EntityPlayerCreatedRosterSourceClient.class); + var service = new EntityPlayerCreatedRosterReadService(repository, source); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy( + () -> + service.read( + new AuthenticatedAccountSelector(UUID.randomUUID()), + ReadPlayerCreatedRosterSourceRequest.getDefaultInstance())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("short Entity transactions"); + verifyNoInteractions(source, repository); + } + + @Test + void selectedReadCallsSourceBeforeRepositoryWhenSourceFails() { + var repository = mock(EntityCharacterCreateRepository.class); + var source = mock(EntityPlayerCreatedRosterSourceClient.class); + var service = new EntityPlayerCreatedRosterReadService(repository, source); + var account = new AuthenticatedAccountSelector(UUID.randomUUID()); + UUID characterId = UUID.randomUUID(); + var request = ReadPlayerCreatedRosterSourceRequest.getDefaultInstance(); + var sourceFailure = new IllegalStateException("controlled source read failure"); + when(source.read(request)).thenThrow(sourceFailure); + + assertThatThrownBy(() -> service.readSelectedTerminal(account, characterId, request)) + .isSameAs(sourceFailure); + + verify(source).read(request); + verifyNoInteractions(repository); + } + + @Test + void selectedReadDispatchesExactAccountSourceAndCharacterToRepository() { + var repository = mock(EntityCharacterCreateRepository.class); + var source = mock(EntityPlayerCreatedRosterSourceClient.class); + var service = new EntityPlayerCreatedRosterReadService(repository, source); + var account = new AuthenticatedAccountSelector(UUID.randomUUID()); + UUID characterId = UUID.randomUUID(); + var published = + new PublishedIdentity( + "entity-test", + UUID.randomUUID(), + UUID.randomUUID(), + "world", + "realm", + UUID.randomUUID(), + UUID.randomUUID(), + null); + var terminal = EntityCharacterCreateTerminal.getDefaultInstance(); + when(repository.readSelectedPlayerCreatedTerminal(account, published, characterId)) + .thenReturn(terminal); + + // This internal wiring check supplies a value object directly; it makes no authentication + // claim. + assertThat(service.readSelectedTerminal(account, characterId, published)).isSameAs(terminal); + + verify(repository).readSelectedPlayerCreatedTerminal(account, published, characterId); + verifyNoInteractions(source); + } + + @Test + void selectedReadRejectsNilCharacterBeforeCallingSource() { + var repository = mock(EntityCharacterCreateRepository.class); + var source = mock(EntityPlayerCreatedRosterSourceClient.class); + var service = new EntityPlayerCreatedRosterReadService(repository, source); + + assertThatThrownBy( + () -> + service.readSelectedTerminal( + new AuthenticatedAccountSelector(UUID.randomUUID()), + new UUID(0L, 0L), + ReadPlayerCreatedRosterSourceRequest.getDefaultInstance())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); + + verifyNoInteractions(source, repository); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java new file mode 100644 index 0000000000..bd0109a365 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java @@ -0,0 +1,145 @@ +package unit.net.firedevops.firemud.entitymanagement.charactercreate; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.UUID; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterService; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSnapshotRepository; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CanonicalGameplayRosterRetentionRepository; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionOperations; + +/** These unit cases cover closed-wire rejection only; they establish no owner or custody proof. */ +class EntityPlayerCreatedRosterServiceTest { + @Test + void rejectsMalformedRosterBeforeAdmissionOrOwnerTransport() { + var source = mock(EntityPlayerCreatedRosterSourceClient.class); + var owner = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var snapshots = mock(EntityPlayerCreatedRosterSnapshotRepository.class); + var retention = mock(CanonicalGameplayRosterRetentionRepository.class); + var transactions = mock(TransactionOperations.class); + var service = + new EntityPlayerCreatedRosterService( + "gameplay", source, owner, snapshots, retention, transactions); + + assertThatThrownBy(() -> service.list(CanonicalPlayerCreatedRosterRequest.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(source, owner, snapshots, retention, transactions); + } + + @Test + void rejectsMalformedSelectedRequestBeforeEitherOwnerTransport() { + var source = mock(EntityPlayerCreatedRosterSourceClient.class); + var owner = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var snapshots = mock(EntityPlayerCreatedRosterSnapshotRepository.class); + var retention = mock(CanonicalGameplayRosterRetentionRepository.class); + var transactions = mock(TransactionOperations.class); + var service = + new EntityPlayerCreatedRosterService( + "gameplay", source, owner, snapshots, retention, transactions); + + assertThatThrownBy( + () -> + service.selected( + CanonicalSelectedPlayerCreatedCharacterRequest.getDefaultInstance())) + .isInstanceOf(IllegalArgumentException.class); + + verifyNoInteractions(source, owner, snapshots, retention, transactions); + } + + @Test + void selectedSourceFailureStopsBeforeOriginalOwnerOrLocalStorage() { + var source = mock(EntityPlayerCreatedRosterSourceClient.class); + var owner = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); + var snapshots = mock(EntityPlayerCreatedRosterSnapshotRepository.class); + var retention = mock(CanonicalGameplayRosterRetentionRepository.class); + var transactions = mock(TransactionOperations.class); + var service = + new EntityPlayerCreatedRosterService( + "gameplay", source, owner, snapshots, retention, transactions); + when(source.read(any())).thenThrow(new IllegalStateException("controlled source unavailable")); + + assertThatThrownBy(() -> service.selected(selectedRequest())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("controlled source unavailable"); + + verify(source).read(any()); + verifyNoInteractions(owner, snapshots, retention, transactions); + } + + private static CanonicalSelectedPlayerCreatedCharacterRequest selectedRequest() { + UUID operation = UUID.randomUUID(); + UUID account = UUID.randomUUID(); + UUID character = UUID.randomUUID(); + var target = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(UUID.randomUUID().toString()) + .setRealmUuid(UUID.randomUUID().toString()) + .setWorldSlug("world") + .setRealmSlug("realm") + .setGameInstanceUuid(UUID.randomUUID().toString()) + .setCatalogRevision(3) + .setCanonicalVersionUuid(UUID.randomUUID().toString()) + .setPointerVersion(5) + .setActiveWorldEpoch(7) + .setPublishedPolicyDigest("1".repeat(64)) + .setPublishedReleaseBundleRef("release:test") + .setAdmissionPointerSnapshotDigest("2".repeat(64)) + .setPublishedOwnerProofDigest("3".repeat(64)) + .setPlayableStateNamespaceUuid(UUID.randomUUID().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .build(); + var source = + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(UUID.randomUUID().toString()) + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .setDescriptorDigest("sha256:" + "a".repeat(64)) + .setAuthoredBindingUuid(UUID.randomUUID().toString()) + .setAuthoredBindingDigest("sha256:" + "b".repeat(64)) + .build()); + return CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest( + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(operation.toString()) + .setCanonicalAccountUuid(account.toString()) + .setSelectedCharacterUuid(character.toString()) + .setExpectedTarget(target) + .setExpectedSnapshot( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference + .newBuilder() + .setSnapshotUuid(UUID.randomUUID().toString()) + .setSnapshotDigest("c".repeat(64))) + .setExpectedSource(source) + .setPlayerExecutionContext( + PlayerExecutionContext.newBuilder() + .setRequestId(operation.toString()) + .setAccountId(account.toString()) + .setSessionId(UUID.randomUUID().toString()) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setPlayableStateScope("SHARED") + .setCharacterId(character.toString())) + .build()); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java index d46f84d686..6b51306dd9 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java @@ -2,26 +2,18 @@ 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.when; import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; -import io.grpc.Server; -import io.grpc.ServerInterceptors; import io.grpc.StatusRuntimeException; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; -import io.grpc.stub.StreamObserver; import java.io.IOException; -import java.net.InetSocketAddress; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; @@ -31,10 +23,7 @@ import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.CommandSource; -import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; @@ -49,35 +38,20 @@ import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; -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.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; -import net.firedevops.firemud.common.testing.AuthoringFixtures; import net.firedevops.firemud.common.testing.PlayerCreatedPublishedPolicyFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; -import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture; +import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture.WireFixture; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; -import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; -import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicCatalog; -import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicPointer; -import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; -import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; -import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse; -import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; -import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -96,34 +70,23 @@ class EntityPlayerCreatedRosterSourceClientMtlsTest { private static final UUID FIXTURE_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); private static final String NAMESPACE = "test"; @TempDir static Path directory; - private static LoopbackMtlsTestPki.Pki pki; - private static Fixture fixture; + private static ControlledPlayerCreatedRosterSourceFixture controlled; + private static WireFixture fixture; @BeforeAll static void setUp() throws Exception { - pki = - LoopbackMtlsTestPki.create( - directory, - "Entity roster source test CA", - new LoopbackMtlsTestPki.IdentitySpec( - "entity", "spiffe://firemud/ns/test/sa/entity-management-service", false), - new LoopbackMtlsTestPki.IdentitySpec( - "server", "spiffe://firemud/ns/test/sa/game-session-service", true), - new LoopbackMtlsTestPki.IdentitySpec( - "wrong-service", "spiffe://firemud/ns/test/sa/social-groups-service", true), - new LoopbackMtlsTestPki.IdentitySpec( - "wrong-namespace", "spiffe://firemud/ns/other/sa/game-session-service", true)); - fixture = fixture(); + controlled = new ControlledPlayerCreatedRosterSourceFixture(directory); + fixture = controlled.wireFixture(); } @Test void actualInitializedClientPreservesExactRequestAndCompleteTypedOwnerSources() throws Exception { - try (var owner = owner("server"); - var client = client(owner)) { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { client.init(); var result = client.read(fixture.request()); - assertThat(owner.received).containsExactly(fixture.request()); - assertThat(owner.observedPeer.get()) + assertThat(owner.receivedRequests()).containsExactly(fixture.request()); + assertThat(owner.observedPeerUri()) .isEqualTo("spiffe://firemud/ns/test/sa/entity-management-service"); assertThat(result.publishedPolicySet().canonicalBytes()) .containsExactly(fixture.policySet().canonicalBytes()); @@ -160,6 +123,37 @@ void actualInitializedClientPreservesExactRequestAndCompleteTypedOwnerSources() } } + @Test + void actualClientSourceComposesBeforeTheLocalRosterRead() throws Exception { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { + client.init(); + var repository = mock(EntityCharacterCreateRepository.class); + when(repository.readPlayerCreatedRoster(any(), any())) + .thenAnswer( + invocation -> { + assertThat(owner.receivedRequests()).containsExactly(fixture.request()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var published = + invocation.getArgument( + 1, EntityPlayerCreatedRosterReadService.PublishedIdentity.class); + assertThat(published.tenantId()) + .isEqualTo(fixture.world().request().canonicalTenantId()); + assertThat(published.projection().canonicalBytes()) + .containsExactly(fixture.authored().projections().getFirst().canonicalBytes()); + return List.of(); + }); + var service = new EntityPlayerCreatedRosterReadService(repository, client); + + assertThat( + service.read( + new EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector( + UUID.randomUUID()), + fixture.request())) + .isEmpty(); + } + } + @Test void constructionRequiresFileBackedMtlsAndCanonicalNamespace() throws Exception { var endpoints = new ServiceEndpointsProperties(); @@ -169,7 +163,7 @@ void constructionRequiresFileBackedMtlsAndCanonicalNamespace() throws Exception new EntityPlayerCreatedRosterSourceClient( endpoints, new CommonGrpcClientProperties(), channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - var plaintext = pki.clientProperties(directory, pki.identity("entity")); + var plaintext = controlled.clientProperties("entity"); plaintext.setPlaintext(true); assertThatThrownBy( () -> @@ -179,30 +173,27 @@ endpoints, new CommonGrpcClientProperties(), channels, NAMESPACE)) assertThatThrownBy( () -> new EntityPlayerCreatedRosterSourceClient( - endpoints, - pki.clientProperties(directory, pki.identity("entity")), - channels, - "Other")) + endpoints, controlled.clientProperties("entity"), channels, "Other")) .isInstanceOf(RuntimeException.class); } @Test void wrongServerServiceAndNamespaceAreRejectedBeforeAnyReceivedRpc() throws Exception { for (String identity : List.of("wrong-service", "wrong-namespace")) { - try (var owner = owner(identity); - var client = client(owner)) { + try (var owner = controlled.owner(identity); + var client = controlled.client(owner)) { client.init(); assertThatThrownBy(() -> client.read(fixture.request())) .isInstanceOf(StatusRuntimeException.class); - assertThat(owner.received).isEmpty(); + assertThat(owner.receivedRequests()).isEmpty(); } } } @Test void absentInitializationAndAmbientSqlRefuseBeforeAnyReceivedRpc() throws Exception { - try (var owner = owner("server"); - var client = client(owner)) { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { assertThatThrownBy(() -> client.read(fixture.request())) .isInstanceOf(IllegalStateException.class); client.init(); @@ -220,15 +211,15 @@ void absentInitializationAndAmbientSqlRefuseBeforeAnyReceivedRpc() throws Except } finally { TransactionSynchronizationManager.setActualTransactionActive(false); } - assertThat(owner.received).isEmpty(); + assertThat(owner.receivedRequests()).isEmpty(); } } @Test void malformedAndChangedRequestSelectorsRefuseBeforeAnyReceivedRpc() throws Exception { var request = fixture.request(); - try (var owner = owner("server"); - var client = client(owner)) { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { client.init(); for (var changed : List.of( @@ -246,7 +237,7 @@ void malformedAndChangedRequestSelectorsRefuseBeforeAnyReceivedRpc() throws Exce request.toBuilder().setPointerVersion(0).build())) { assertThatThrownBy(() -> client.read(changed)).isInstanceOf(RuntimeException.class); } - assertThat(owner.received).isEmpty(); + assertThat(owner.receivedRequests()).isEmpty(); } } @@ -267,7 +258,7 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws world.graphSha256(), world.preparationInputDigest(), world.operationalRegionAssignments()); - var otherLaunch = fixture("other-authored-launch-descriptor").world(); + var otherLaunch = controlled.wireFixture("other-authored-launch-descriptor").world(); var authored = fixture.authored(); var noProjections = AuthoredInitialActorCoreReadGrpcCodec.toResponse( @@ -356,8 +347,8 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws authored.descriptor(), List.of(changedProjection)))); } - try (var owner = owner("server"); - var client = client(owner)) { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { client.init(); for (var changed : List.of( @@ -484,22 +475,22 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws good.toBuilder().clearPointer().build(), good.toBuilder().setOriginalControlPlaneRequestId("x".repeat(129)).build(), good.toBuilder().setUnknownFields(unknown()).build())) { - owner.response.set(changed); + owner.respondWith(changed); assertThatThrownBy(() -> client.read(fixture.request())) .isInstanceOf(RuntimeException.class); } - assertThat(owner.received).isNotEmpty().allMatch(fixture.request()::equals); - owner.response.set(good); + assertThat(owner.receivedRequests()).isNotEmpty().allMatch(fixture.request()::equals); + owner.respondWith(good); assertThat(client.read(fixture.request()).response()).isEqualTo(good); } } @Test void inboundTransportRejectsResponseBeyond32MiBBeforeSourceDecoding() throws Exception { - try (var owner = owner("server"); - var client = client(owner)) { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { client.init(); - owner.response.set( + owner.respondWith( fixture.response().toBuilder() .setWorldLifecycleEvidence( ByteString.copyFrom( @@ -511,7 +502,7 @@ void inboundTransportRejectsResponseBeyond32MiBBeforeSourceDecoding() throws Exc failure -> assertThat(failure.getStatus().getCode()) .isEqualTo(io.grpc.Status.Code.RESOURCE_EXHAUSTED)); - assertThat(owner.received).containsExactly(fixture.request()); + assertThat(owner.receivedRequests()).containsExactly(fixture.request()); } } @@ -521,383 +512,6 @@ private static UnknownFieldSet unknown() { .build(); } - private static EntityPlayerCreatedRosterSourceClient client(Owner owner) throws Exception { - var endpoints = new ServiceEndpointsProperties(); - endpoints.setGameSessionService("127.0.0.1:" + owner.server.getPort()); - return new EntityPlayerCreatedRosterSourceClient( - endpoints, - pki.clientProperties(directory, pki.identity("entity")), - new GrpcChannelFactory(), - NAMESPACE); - } - - private static Owner owner(String name) throws Exception { - var response = new AtomicReference<>(fixture.response()); - var received = new CopyOnWriteArrayList(); - var observedPeer = new AtomicReference(); - var identity = pki.identity(name); - Server server = - NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) - .trustManager(pki.caCertificate()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService( - ServerInterceptors.intercept( - new CharacterCreatePublicSourceServiceGrpc - .CharacterCreatePublicSourceServiceImplBase() { - @Override - public void readPlayerCreatedRosterSource( - ReadPlayerCreatedRosterSourceRequest request, - StreamObserver observer) { - observedPeer.set(GrpcPeerIdentity.current().uri()); - received.add(request); - observer.onNext(response.get()); - observer.onCompleted(); - } - }, - new GrpcPeerIdentityInterceptor())) - .build() - .start(); - return new Owner(server, response, received, observedPeer); - } - - private record Owner( - Server server, - AtomicReference response, - List received, - AtomicReference observedPeer) - implements AutoCloseable { - @Override - public void close() throws InterruptedException { - server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); - } - } - - private record Fixture( - ReadPlayerCreatedRosterSourceRequest request, - ReadPlayerCreatedRosterSourceResponse response, - AuthoredInitialActorCoreReadEvidence.ReadResult authored, - WorldCanonicalInstanceLifecycleEvidence world, - PublishedRealmEntryPolicySetEvidence policySet) {} - - // Common's authored-core fixture lives in its private unit-test source and is not exported. - // Build only the owner-shaped values needed here, using the exported World fixture and real - // codecs. - private static Fixture fixture() throws Exception { - return fixture("canonical-instance-launch-descriptor"); - } - - private static Fixture fixture(String descriptorId) throws Exception { - var originalWorld = AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); - var originalDescriptor = originalWorld.launchBinding().descriptor(); - var selector = originalWorld.launchBinding().releaseAttestation().worldStartLocationEvidence(); - var tenant = originalWorld.request().canonicalTenantId(); - var version = originalWorld.request().canonicalVersionId(); - var intakeId = UUID.randomUUID(); - var operationId = UUID.randomUUID(); - String requestDigest = - AuthoredWorldSourceDigest.requestDigest( - NAMESPACE, intakeId, tenant, "tenant-key", "synthetic-world", "Synthetic World"); - String evidenceDigest = - AuthoredWorldSourceDigest.evidenceDigest( - NAMESPACE, - intakeId, - originalDescriptor.authoredWorldSourceOperationId(), - requestDigest, - tenant, - "tenant-key", - "synthetic-world", - "Synthetic World", - 42L, - "tenant-key", - "NEW_GAME_ROW"); - var source = - new AuthoredWorldSourceEvidence( - 1, - NAMESPACE, - intakeId, - originalDescriptor.authoredWorldSourceOperationId(), - requestDigest, - tenant, - "tenant-key", - "synthetic-world", - "Synthetic World", - 42L, - "tenant-key", - "NEW_GAME_ROW", - evidenceDigest); - var intake = - new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( - 1, - NAMESPACE, - intakeId, - tenant, - "synthetic-world", - source.operationId(), - evidenceDigest); - var receipt = - new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( - 1, - NAMESPACE, - intakeId, - operationId, - tenant, - "synthetic-world", - source.operationId(), - evidenceDigest, - WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), - digest('e'), - source); - var descriptorRequest = - new AuthoredWorldLaunchDescriptorEvidence.Request( - NAMESPACE, - "world-lifecycle-control-request", - tenant, - "synthetic-world", - source.operationId(), - evidenceDigest, - 19L, - false, - null, - false, - null, - false, - null, - true, - "{}"); - var descriptor = - AuthoredWorldLaunchDescriptorEvidence.create( - descriptorRequest, - descriptorId, - 42L, - false, - null, - "{}", - originalDescriptor.generationConfigRevision(), - 9L, - 7L, - originalDescriptor.publishedReleaseBundleRef(), - false, - null); - var oldRelease = originalWorld.launchBinding().releaseAttestation(); - var association = - new StartSessionTemplateAssociationReadEvidence.Association( - tenant, - 19L, - version, - UUID.fromString(selector.request().appliedCommitId()), - selector.request().publishWorkflowId(), - digest('c'), - digest('a'), - NAMESPACE, - intakeId, - operationId, - source.operationId(), - descriptor.worldSlug(), - evidenceDigest, - new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( - 1, NAMESPACE, FIXTURE_ID, intakeId, tenant), - receipt); - var prepared = - PlayerCreatedPublishedPolicyFixtures.prepare( - sourceBinding(association, association.sourceOperationId()).selectedCommit()); - selector = prepared.world(); - var release = - AuthoredWorldReleaseAttestationEvidence.create( - NAMESPACE, - descriptor.resultDigest(), - tenant, - version, - descriptor.worldSlug(), - source.operationId(), - evidenceDigest, - descriptor.launchDescriptorId(), - descriptor.publishedReleaseBundleRef(), - descriptor.versionStateEpoch(), - selector.request().publishWorkflowId(), - selector.request().appliedCommitId(), - oldRelease.participantDigests(), - oldRelease.manifestHash(), - oldRelease.manifestSchemaVersion(), - oldRelease.requiredManifestAssetKeys(), - oldRelease.artifactDigests(), - oldRelease.commandDefinitions(), - oldRelease.generationConfigRevision(), - selector); - var lifecycleRequest = - new WorldCanonicalInstanceLifecycleEvidence.Request( - 1, - FIXTURE_ID, - NAMESPACE, - tenant, - descriptor.worldSlug(), - originalWorld.request().canonicalGameInstanceId(), - originalWorld.request().playableStateNamespaceId(), - "SHARED", - true, - descriptor.controlPlaneRequestId(), - version, - descriptor.requestDigest(), - descriptor.resultDigest(), - release.evidenceDigest()); - var world = - new WorldCanonicalInstanceLifecycleEvidence( - lifecycleRequest, - new CompleteLaunchBindingEvidence(descriptor, release), - originalWorld.startLocation(), - originalWorld.runtimeRoomInstanceId(), - "ACTIVE", - 7L, - originalWorld.rowVersion(), - originalWorld.captureId(), - WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) - .graphDigest() - .substring(7), - originalWorld.preparationInputDigest(), - originalWorld.operationalRegionAssignments()); - association = - new StartSessionTemplateAssociationReadEvidence.Association( - tenant, - 19L, - version, - UUID.fromString(selector.request().appliedCommitId()), - selector.request().publishWorkflowId(), - digest('c'), - digest('a'), - NAMESPACE, - intakeId, - operationId, - source.operationId(), - descriptor.worldSlug(), - evidenceDigest, - new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( - 1, NAMESPACE, FIXTURE_ID, intakeId, tenant), - receipt); - var readRequest = - new StartSessionTemplateAssociationReadEvidence.Request( - 1, - NAMESPACE, - FIXTURE_ID, - postTuple(tenant, NAMESPACE).canonicalBytes(), - FIXTURE_ID, - 8L, - new StartSessionTemplateAssociationReadEvidence.ExactReplay( - version, - association.selectedCommitId(), - association.publishWorkflowId(), - association.associationDigest())); - var bundle = - PublishedReleaseBundle.newBuilder() - .setId(7L) - .setVersionId(42L) - .setVersionNumber(1) - .setAttestationSchemaVersion("v2") - .setPublishWorkflowId(release.publishWorkflowId()) - .setManifestHash(release.manifestHash()) - .setManifestSchemaVersion(release.manifestSchemaVersion()) - .addAllRequiredManifestAssetKeys(release.requiredManifestAssetKeys()) - .setGenerationConfigRevision(release.generationConfigRevision()) - .setPublishedReleaseBundleRef(release.publishedReleaseBundleRef()) - .setCanonicalTenantId(tenant.toString()) - .setCanonicalVersionId(version.toString()) - .addAllCommandDefinitions(release.commandDefinitions()); - for (var participant : release.participantDigests()) { - var item = - ParticipantDigest.newBuilder() - .setParticipantKey(participant.participantKey()) - .setScopeValue(participant.scopeValue()) - .setAppliedCommitId(participant.appliedCommitId()) - .setContentDigest(participant.contentDigest()) - .setDigestSchemaVersion(participant.digestSchemaVersion()); - if (participant.abilitySchemaDigestPresent()) - item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); - bundle.addParticipantDigests(item); - } - var authored = - new AuthoredInitialActorCoreReadEvidence.ReadResult( - readRequest, - new StartSessionTemplateAssociationReadEvidence.Result( - readRequest, association, bundle.build(), selector, 23L), - descriptor, - List.of( - AuthoredInitialActorCoreProjection.fromValidatedBinding( - FIXTURE_ID, sourceBinding(association, association.sourceOperationId())))); - var releaseContent = - StartSessionTemplateAssociationReadEvidence.releaseContent(bundle.build(), selector); - var policySet = - PlayerCreatedPublishedPolicyFixtures.seal( - prepared, - IsolatedWorldPublicationInventoryFixtures.stipulated( - prepared.account(), prepared.world()), - releaseContent, - authored.projections().getFirst()); - var request = - ReadPlayerCreatedRosterSourceRequest.newBuilder() - .setSchemaVersion(1) - .setReadRequestId(FIXTURE_ID.toString()) - .setTargetNamespace(NAMESPACE) - .setCanonicalTenantId(tenant.toString()) - .setRealmId(FIXTURE_ID.toString()) - .setWorldSlug(descriptor.worldSlug()) - .setRealmSlug("realm") - .setPlayableStateNamespaceId(lifecycleRequest.playableStateNamespaceId().toString()) - .setPlayableStateScope("SHARED") - .setCanonicalGameInstanceId(lifecycleRequest.canonicalGameInstanceId().toString()) - .setCatalogRevision(3L) - .setPointerVersion(5L) - .setExpectedCanonicalVersionId(version.toString()) - .setActiveWorldEpoch(7L) - .build(); - var response = - ReadPlayerCreatedRosterSourceResponse.newBuilder() - .setSchemaVersion(1) - .setRequest(request) - .setCatalog( - CharacterCreatePublicCatalog.newBuilder() - .setTenantId(tenant.toString()) - .setTenantSlug("tenant") - .setWorldSlug(request.getWorldSlug()) - .setWorldDisplayName("Synthetic World") - .setRealmId(request.getRealmId()) - .setRealmSlug("realm") - .setRealmDisplayName("Realm") - .setVisible(true) - .setPublicProduction(true) - .setStateScope("SHARED") - .setPlayableStateNamespaceId(request.getPlayableStateNamespaceId()) - .setCharacterCreationPolicy("PLAYER_CREATED") - .setCatalogRevision(3L) - .setCreationRequestId(FIXTURE_ID.toString()) - .setReceiptDigest(digest('a'))) - .setPointer( - CharacterCreatePublicPointer.newBuilder() - .setTenantId(tenant.toString()) - .setRealmId(request.getRealmId()) - .setWorldSlug(request.getWorldSlug()) - .setRealmSlug("realm") - .setAdmissionState("OPEN") - .setAdmissibleGameInstanceId(request.getCanonicalGameInstanceId()) - .setPointerVersion(5L) - .setCatalogRevision(3L) - .setUpdatedAt("2026-10-24T00:00:00.123456789Z") - .setInitialAdmissionRequestId("initial-admission") - .setInitialAdmissionOwnerProofDigest(digest('b')) - .setAdmissionPointerSnapshotDigest("c".repeat(64))) - .setCanonicalVersionId(version.toString()) - .setActiveLifecycleEpoch(7L) - .setOriginalControlPlaneRequestId(descriptor.controlPlaneRequestId()) - .setOriginalOwnerAttemptId(FIXTURE_ID.toString()) - .setOriginalOwnerFence(8L) - .setAuthoredSource(AuthoredInitialActorCoreReadGrpcCodec.toResponse(authored)) - .setPublishedPolicySetEvidence(ByteString.copyFrom(policySet.canonicalBytes())) - .setWorldLifecycleEvidence(ByteString.copyFrom(world.canonicalBytes())) - .build(); - return new Fixture(request, response, authored, world, policySet); - } - private static StartSessionPostAuthorizationExecutionTuple postTuple( UUID tenant, String namespace) { StartSessionPreAuthorizationReservationTuple pre = diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java index 4e24dac64d..f304892834 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; @@ -224,7 +225,89 @@ void authenticatedRetirementTransferUsesExactBytesAndNoAmbientClaims() throws Ex } } + @Test + void createdOriginalAndRetirementPreserveCompleteTerminalAboveDefaultReceiveLimit() + throws Exception { + // Controlled foreign proofs; actual file-backed Entity client and socket mTLS only. + var fixture = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection(NAMESPACE); + int defaultReceiveLimit = 4 * 1024 * 1024; + assertThat(fixture.selected().getTerminal().getOriginalAccountProtection().size()) + .isEqualTo(5 * 1024 * 1024); + assertThat(fixture.selected().getTerminal().getSerializedSize()) + .isGreaterThan(defaultReceiveLimit); + assertThat(fixture.original().getSerializedSize()).isGreaterThan(defaultReceiveLimit); + assertThat(fixture.acknowledgementRequest().getSerializedSize()) + .isGreaterThan(defaultReceiveLimit); + assertThat(fixture.confirmation().getSerializedSize()).isGreaterThan(defaultReceiveLimit); + start( + "server", + fixture, + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + SessionContext.setContext( + UUID.randomUUID().toString(), + List.of("platformAdmin"), + Map.of(), + true, + "account-service", + "ambient-instance"); + try (var client = client()) { + client.init(); + // The production client selects its 194 MiB receive bound from this created request. + var original = client.getCanonicalGameplayRosterReference(fixture.originalRequest()); + assertThat(original).isEqualTo(fixture.original()); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + original) + .getTerminal() + .toByteString()) + .isEqualTo(fixture.selected().getTerminal().toByteString()); + assertThat(observedRequest.get()).isEqualTo(fixture.originalRequest()); + assertThat(authorization.get()).isNull(); + var acknowledgement = + client.acknowledgeCanonicalGameplayRosterRetirement(fixture.acknowledgementRequest()); + assertThat(acknowledgement).isEqualTo(fixture.acknowledgement()); + assertThat(observedAcknowledgement.get()).isEqualTo(fixture.acknowledgementRequest()); + assertThat( + observedAcknowledgement + .get() + .getObservedRetirement() + .getCanonicalSelectedPlayerCreatedCharacterReceipt()) + .isEqualTo(fixture.selected().toByteString()); + assertThat(authorization.get()).isNull(); + assertThat( + client.confirmCanonicalGameplayRosterRetirementAcknowledgement( + fixture.confirmation())) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence.confirmationResponse( + fixture.confirmation())); + assertThat(observedConfirmation.get()).isEqualTo(fixture.confirmation()); + assertThat( + observedConfirmation + .get() + .getAcknowledgementRequest() + .getObservedRetirement() + .getCanonicalSelectedPlayerCreatedCharacterReceipt()) + .isEqualTo(fixture.selected().toByteString()); + assertThat(authorization.get()).isNull(); + assertThat(callerUri.get()).isEqualTo(ENTITY_URI); + assertThat(receivedCalls.get()).isEqualTo(3); + assertThat(handlerReads.get()).isEqualTo(3); + assertThat(SessionContext.getServiceName()).isEqualTo("account-service"); + } finally { + SessionContext.clear(); + } + } + private void start(String alias) throws Exception { + start(alias, null, 0); + } + + private void start( + String alias, + ControlledPlayerCreatedRosterTerminalFixtures.Bundle controlled, + int maxInboundBytes) + throws Exception { var identity = pki.identity(alias); var service = new CanonicalGameplayRosterOwnerReadServiceGrpc @@ -237,8 +320,10 @@ public void getCanonicalGameplayRosterReference( observedRequest.set(request); callerUri.set(GrpcPeerIdentity.current().uri()); responseObserver.onNext( - CanonicalGameplayRosterReferenceEvidence.response( - request, 1L, UUID.fromString("12121212-1212-4212-8212-121212121212"), null)); + controlled == null + ? CanonicalGameplayRosterReferenceEvidence.response( + request, 1L, UUID.fromString("12121212-1212-4212-8212-121212121212"), null) + : controlled.original()); responseObserver.onCompleted(); } @@ -250,8 +335,10 @@ public void acknowledgeCanonicalGameplayRosterRetirement( observedAcknowledgement.set(request); callerUri.set(GrpcPeerIdentity.current().uri()); observer.onNext( - CanonicalGameplayRosterRetirementEvidence.response( - request, UUID.fromString("34343434-3434-4434-8434-343434343434"), 1000)); + controlled == null + ? CanonicalGameplayRosterRetirementEvidence.response( + request, UUID.fromString("34343434-3434-4434-8434-343434343434"), 1000) + : controlled.acknowledgement()); observer.onCompleted(); } @@ -286,8 +373,10 @@ public ServerCall.Listener interceptCall( return next.startCall(call, headers); } }; + var serverBuilder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)); + if (maxInboundBytes > 0) serverBuilder.maxInboundMessageSize(maxInboundBytes); server = - NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + serverBuilder .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java index 1195f4faab..942c462678 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java @@ -27,9 +27,11 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadGrpcCodec; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; @@ -298,6 +300,32 @@ void retirementCallsUseExactRequestDeadlineAndActualResponseBinding() throws Exc .isInstanceOf(IllegalArgumentException.class); } + @Test + void onlyCreatedOriginalReferenceCallsWidenTheStubInboundLimit() throws Exception { + var created = createdOriginalRequest(); + var createdResponse = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + created, 1L, UUID.randomUUID(), null); + var preseeded = + CanonicalGameplayRosterReferenceEvidence.request( + REQUEST_UUID, ACCOUNT_UUID, UUID.randomUUID(), NAMESPACE, target(false)); + var preseededResponse = + CanonicalGameplayRosterReferenceEvidence.response(preseeded, 1L, UUID.randomUUID(), null); + var stub = mockStub(); + when(stub.getCanonicalGameplayRosterReference(created)).thenReturn(createdResponse); + when(stub.getCanonicalGameplayRosterReference(preseeded)).thenReturn(preseededResponse); + var client = newClient(stub); + + assertThat(client.getCanonicalGameplayRosterReference(created)).isEqualTo(createdResponse); + verify(stub) + .withMaxInboundMessageSize( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES); + assertThat(client.getCanonicalGameplayRosterReference(preseeded)).isEqualTo(preseededResponse); + verify(stub, times(1)) + .withMaxInboundMessageSize( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES); + } + @Test void retirementRejectsNamespaceMalformedInputAndAmbientTransactionsBeforeTransport() throws Exception { @@ -407,6 +435,50 @@ private static CanonicalGameplayRosterRetirementAcknowledgementRequest retiremen .build()); } + private static net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest + createdOriginalRequest() { + var target = target(true); + return CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + REQUEST_UUID, + ACCOUNT_UUID, + UUID.randomUUID(), + NAMESPACE, + target, + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(UUID.randomUUID().toString()) + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .setDescriptorDigest("sha256:" + "1".repeat(64)) + .setAuthoredBindingUuid(UUID.randomUUID().toString()) + .setAuthoredBindingDigest("sha256:" + "2".repeat(64)) + .build())); + } + + private static CanonicalGameplayRosterTarget target(boolean created) { + return CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(TENANT_UUID.toString()) + .setRealmUuid(REALM_UUID.toString()) + .setGameInstanceUuid(INSTANCE_UUID.toString()) + .setCanonicalVersionUuid(VERSION_UUID.toString()) + .setPlayableStateNamespaceUuid(NAMESPACE_UUID.toString()) + .setWorldSlug("earth") + .setRealmSlug("main") + .setCatalogRevision(71) + .setPointerVersion(73) + .setActiveWorldEpoch(82) + .setPublishedPolicyDigest("a".repeat(64)) + .setPublishedOwnerProofDigest("b".repeat(64)) + .setAdmissionPointerSnapshotDigest("c".repeat(64)) + .setPublishedReleaseBundleRef("release:exact") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + created + ? CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED + : CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build(); + } + private static GameSessionCanonicalGameplayRosterOwnerReadClient newClient( CanonicalGameplayRosterOwnerReadServiceGrpc .CanonicalGameplayRosterOwnerReadServiceBlockingStub @@ -448,6 +520,9 @@ private static GameSessionCanonicalGameplayRosterOwnerReadClient newClientWithou CanonicalGameplayRosterOwnerReadServiceGrpc .CanonicalGameplayRosterOwnerReadServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withMaxInboundMessageSize( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES)) + .thenReturn(stub); return stub; } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java index a6a77e91d9..59fda990f9 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java @@ -122,6 +122,52 @@ void selectedAssignmentMethodUsesTheSameNamespaceAndEndUserContextGuard() { verify(endUserNext, never()).startCall(any(), any()); } + @Test + void bothCreatedRosterMethodsUseTheSameCertificateNamespaceAndEndUserGuard() { + var interceptor = new CanonicalGameplayRosterPeerInterceptor(WORKLOAD_NAMESPACE); + for (String method : + List.of( + CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, + CanonicalGameplayRosterPeerInterceptor.SELECTED_PLAYER_CREATED_METHOD_NAME)) { + var trusted = + callFor(method, peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); + ServerCallHandler trustedNext = mock(ServerCallHandler.class); + when(trustedNext.startCall(any(), any())) + .thenAnswer( + invocation -> { + assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()) + .isNotNull(); + return new ServerCall.Listener<>() {}; + }); + interceptor.interceptCall(trusted, new Metadata(), trustedNext); + verify(trustedNext).startCall(any(), any()); + + var foreign = + callFor(method, peerSession("spiffe://firemud/ns/other/sa/game-session-service")); + ServerCallHandler foreignNext = mock(ServerCallHandler.class); + interceptor.interceptCall(foreign, new Metadata(), foreignNext); + verify(foreign) + .close( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == Status.Code.PERMISSION_DENIED), + any(Metadata.class)); + verify(foreignNext, never()).startCall(any(), any()); + + SessionContext.setContext("player-claim", List.of(), java.util.Map.of()); + var endUser = + callFor(method, peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); + ServerCallHandler endUserNext = mock(ServerCallHandler.class); + interceptor.interceptCall(endUser, new Metadata(), endUserNext); + verify(endUser) + .close( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == Status.Code.PERMISSION_DENIED), + any(Metadata.class)); + verify(endUserNext, never()).startCall(any(), any()); + SessionContext.clear(); + } + } + @Test void recoveryMethodRequiresTheExactGameSessionCertificateAndNoEndUserContext() { var interceptor = new CanonicalGameplayRosterPeerInterceptor(WORKLOAD_NAMESPACE); @@ -177,6 +223,8 @@ void applicationYamlKeepsRosterMethodsOutsideJwtBypassAllowlist() { .doesNotContain( CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME, + CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, + CanonicalGameplayRosterPeerInterceptor.SELECTED_PLAYER_CREATED_METHOD_NAME, CanonicalGameplayRosterPeerInterceptor.RECOVERY_METHOD_NAME); assertThat(publicMethods).noneMatch(method -> method.contains("*")); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java index 6126636564..41dacccf2e 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java @@ -27,6 +27,8 @@ import javax.net.ssl.SSLSession; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterService; import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.security.CanonicalGameplayRosterPeerInterceptor; @@ -41,6 +43,9 @@ import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.AfterEach; @@ -422,6 +427,71 @@ void rpcErrorsUseCanonicalStatusesWithoutPartialResponses() { assertOnlyStatus(unauthenticatedObserver, Status.Code.UNAUTHENTICATED); } + @Test + void legacyConstructorReturnsUnavailableForBothUnregisteredCreatedMethods() { + var adapter = + new CanonicalGameplayRosterGrpcAdapter( + mock(CanonicalGameplayRosterService.class), + mock(CanonicalGameplayRosterSelectedAssignmentService.class), + new SimpleMeterRegistry()); + var listObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse>(); + withTrustedPeer( + "entity_management.v1.CanonicalGameplayRosterService/ListPlayerCreatedRoster", + () -> adapter.listPlayerCreatedRoster(playerCreatedRequest(), listObserver)); + assertOnlyStatus(listObserver, Status.Code.UNAVAILABLE); + + var selectedObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1 + .CanonicalSelectedPlayerCreatedCharacterResponse>(); + withTrustedPeer( + "entity_management.v1.CanonicalGameplayRosterService/ReadSelectedPlayerCreatedCharacter", + () -> + adapter.readSelectedPlayerCreatedCharacter(selectedCreatedRequest(), selectedObserver)); + assertOnlyStatus(selectedObserver, Status.Code.UNAVAILABLE); + } + + @Test + void createdMethodsValidateFullServiceResponsesBeforeReturningThem() { + var createdService = mock(EntityPlayerCreatedRosterService.class); + var adapter = + new CanonicalGameplayRosterGrpcAdapter( + mock(CanonicalGameplayRosterService.class), + mock(CanonicalGameplayRosterSelectedAssignmentService.class), + createdService, + new SimpleMeterRegistry()); + var request = playerCreatedRequest(); + when(createdService.list(request)) + .thenReturn( + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse + .getDefaultInstance()); + var listObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, + () -> adapter.listPlayerCreatedRoster(request, listObserver)); + assertOnlyStatus(listObserver, Status.Code.INVALID_ARGUMENT); + verify(createdService).list(request); + + var selectedRequest = selectedCreatedRequest(); + when(createdService.selected(selectedRequest)) + .thenReturn( + net.firedevops.firemud.entitymanagement.v1 + .CanonicalSelectedPlayerCreatedCharacterResponse.getDefaultInstance()); + var selectedObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1 + .CanonicalSelectedPlayerCreatedCharacterResponse>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.SELECTED_PLAYER_CREATED_METHOD_NAME, + () -> adapter.readSelectedPlayerCreatedCharacter(selectedRequest, selectedObserver)); + assertOnlyStatus(selectedObserver, Status.Code.INVALID_ARGUMENT); + verify(createdService).selected(selectedRequest); + } + @Test void unexpectedIllegalStateExceptionReturnsInternalAndRecordsInternalMetric() { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -579,6 +649,60 @@ private static CanonicalGameplayRosterRequest request(CanonicalGameplayRosterTar .build(); } + private static CanonicalPlayerCreatedRosterRequest playerCreatedRequest() { + UUID requestUuid = UUID.randomUUID(); + UUID accountUuid = UUID.randomUUID(); + var target = playerCreatedTarget(); + return CanonicalPlayerCreatedRosterEvidence.requireRequest( + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(requestUuid.toString()) + .setCanonicalAccountUuid(accountUuid.toString()) + .setExpectedTarget(target) + .setExpectedSource(playerCreatedSource()) + .setPlayerExecutionContext(executionContext(target, requestUuid, accountUuid, null)) + .build()); + } + + private static CanonicalSelectedPlayerCreatedCharacterRequest selectedCreatedRequest() { + var list = playerCreatedRequest(); + UUID selected = UUID.randomUUID(); + return CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest( + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(list.getRequestUuid()) + .setCanonicalAccountUuid(list.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(selected.toString()) + .setExpectedTarget(list.getExpectedTarget()) + .setExpectedSnapshot( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference + .newBuilder() + .setSnapshotUuid(UUID.randomUUID().toString()) + .setSnapshotDigest("a".repeat(64))) + .setExpectedSource(list.getExpectedSource()) + .setPlayerExecutionContext( + list.getPlayerExecutionContext().toBuilder().setCharacterId(selected.toString())) + .build()); + } + + private static CanonicalGameplayRosterTarget playerCreatedTarget() { + return target().toBuilder() + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .build(); + } + + private static CanonicalPlayerCreatedRosterSourceIdentity playerCreatedSource() { + return CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(UUID.randomUUID().toString()) + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .setDescriptorDigest("sha256:" + "1".repeat(64)) + .setAuthoredBindingUuid(UUID.randomUUID().toString()) + .setAuthoredBindingDigest("sha256:" + "2".repeat(64)) + .build()); + } + private static CanonicalGameplayRosterSelectedAssignmentRequest selectedAssignmentRequest( CanonicalGameplayRosterTarget target) { UUID requestUuid = UUID.randomUUID(); diff --git a/services/entity-management-service/src/test/resources/charactercreate/entity-public-action.json b/services/entity-management-service/src/test/resources/charactercreate/entity-public-action.json new file mode 100644 index 0000000000..a63aa694c7 --- /dev/null +++ b/services/entity-management-service/src/test/resources/charactercreate/entity-public-action.json @@ -0,0 +1 @@ +{"actionFamilySchemaId":"firemud.entity.create-character","actionFamilySchemaVersion":"1","scope":{"targetNamespace":"firemud","tenantId":"a1000000-0000-4000-8000-000000000001","playableStateNamespaceId":"a3000000-0000-4000-8000-000000000001","playableStateScope":"PLAYABLE_STATE_SCOPE_SHARED"},"target":{"accountId":"a4000000-0000-4000-8000-000000000001","realmId":"a2000000-0000-4000-8000-000000000001","worldSlug":"ember-vale","realmSlug":"salt-harbor","gameInstanceId":"a5000000-0000-4000-8000-000000000001","versionId":"a6000000-0000-4000-8000-000000000001"},"expectedVersion":{"catalogRevision":"17","pointerVersion":"23","activeLifecycleEpoch":"31","evaluatedAt":"2026-10-11T12:34:56.123456789Z","connectScopeExpiresAt":"2026-10-11T12:39:56.987654321Z"},"mutation":{"purpose":"CHARACTER_CREATE","entryPolicy":"PLAYER_CREATED","catalog":{"tenantId":"a1000000-0000-4000-8000-000000000001","tenantSlug":"tideward","worldSlug":"ember-vale","worldDisplayName":{"encoding":"utf8-base64url-unpadded","bytes":"RW1iZXIgUmVhY2g"},"realmId":"a2000000-0000-4000-8000-000000000001","realmSlug":"salt-harbor","realmDisplayName":{"encoding":"utf8-base64url-unpadded","bytes":"U2FsdCBIYXJib3I"},"visible":true,"publicProduction":true,"stateScope":"SHARED","playableStateNamespaceId":"a3000000-0000-4000-8000-000000000001","characterCreationPolicy":"PLAYER_CREATED","catalogRevision":"17"},"pointer":{"tenantId":"a1000000-0000-4000-8000-000000000001","realmId":"a2000000-0000-4000-8000-000000000001","worldSlug":"ember-vale","realmSlug":"salt-harbor","admissionState":"OPEN","admissibleGameInstanceId":"a5000000-0000-4000-8000-000000000001","pointerVersion":"23","catalogRevision":"17","updatedAt":"2026-10-11T12:30:01.012345678Z"},"authoredSource":{"schema":"game-design-authored-initial-actor-core-projection/v1","bindingId":"a7000000-0000-4000-8000-000000000001","bindingDigest":"sha256:e70f02bed77058455e908732d7b33617827b6e328468913bf107d990e26afb4a","canonicalTenantId":"a1000000-0000-4000-8000-000000000001","canonicalVersionId":"a6000000-0000-4000-8000-000000000001","worldSourceOperationId":"a8000000-0000-4000-8000-000000000001","worldSourceEvidenceDigest":"sha256:01e3d2f5ca1c0f6c6a17db5546729a7e4971e5b4972602b81f0556f2e5462263","worldSlug":"ember-vale","publicationWorkflowId":{"encoding":"utf8-base64url-unpadded","bytes":"cHVibGlzaGVkLWVtYmVyLXdvcmtmbG93LTIwMjYtMTAtMTE"},"selectedCommitId":"a9000000-0000-4000-8000-000000000001","selectedCommitDigest":"sha256:e4da1526c7e4896ea8a951fb8e0bc9af6306d0a2ce8199eb877be5927c731c3a","policy":{"commitId":"aa000000-0000-4000-8000-000000000001","revisionId":"ab000000-0000-4000-8000-000000000001","logicalRevisionId":{"encoding":"utf8-base64url-unpadded","bytes":"cG9saWN5LWxvZ2ljYWwtZW1iZXItcjQ"},"canonicalPolicyJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJjcmVhdGlvbkRlc2NyaXB0b3IiOnsiZGVwZW5kZW5jaWVzIjpbXSwiZGVzY3JpcHRvcklkIjoiYWMwMDAwMDAtMDAwMC00MDAwLTgwMDAtMDAwMDAwMDAwMDAxIiwiZGVzY3JpcHRvclJldmlzaW9uSWQiOiJhZDAwMDAwMC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDEiLCJpbnB1dEtpbmQiOiJFTVBUWV9PQkpFQ1QiLCJzY2hlbWFWZXJzaW9uIjoxfSwiZW50cnlQb2xpY3kiOiJQTEFZRVJfQ1JFQVRFRCIsImluaXRpYWxBY3RvckNvcmUiOnsiZGlzcGxheU5hbWUiOiJXYXlmYXJlciIsImRpc3Bvc2l0aW9uS2V5IjoibmV3Y29tZXIifSwicHVibGljUHJvZHVjdGlvbiI6dHJ1ZSwicmVhbG1EaXNwbGF5TmFtZSI6IlNhbHQgSGFyYm9yIiwicmVhbG1TbHVnIjoic2FsdC1oYXJib3IiLCJzY2hlbWFWZXJzaW9uIjozLCJzdGF0ZVNjb3BlIjoiU0hBUkVEIiwidmlzaWJsZSI6dHJ1ZSwid29ybGREaXNwbGF5TmFtZSI6IkVtYmVyIFJlYWNoIiwid29ybGRTbHVnIjoiZW1iZXItdmFsZSJ9"},"contentDigest":"sha256:39d36dc77fa62069acf4cb6dec2a9ded18e409039a24da46d326f297d9e889a1"},"core":{"canonicalJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJkaXNwbGF5TmFtZSI6IldheWZhcmVyIiwiZGlzcG9zaXRpb25LZXkiOiJuZXdjb21lciJ9"}},"descriptor":{"canonicalJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJkZXBlbmRlbmNpZXMiOltdLCJkZXNjcmlwdG9ySWQiOiJhYzAwMDAwMC0wMDAwLTQwMDAtODAwMC0wMDAwMDAwMDAwMDEiLCJkZXNjcmlwdG9yUmV2aXNpb25JZCI6ImFkMDAwMDAwLTAwMDAtNDAwMC04MDAwLTAwMDAwMDAwMDAwMSIsImlucHV0S2luZCI6IkVNUFRZX09CSkVDVCIsInNjaGVtYVZlcnNpb24iOjF9"},"digest":"sha256:80fec9b6669a9786a676c6877fbdd9497f0643bf947504866d3f5a0dfaaee415"},"disposition":{"key":"newcomer","definitionJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJkZW5pZWRBZG1pc3Npb25UYWdzIjpbXSwiZGlzcG9zaXRpb25LZXkiOiJuZXdjb21lciIsInNhZmVGZWVkYmFja0tleSI6IndlbGNvbWUifQ"},"definitionDigest":"sha256:aa17d1d6463a644913ec98c2137fb44acffcd6cc7c9786a6648fd0971826c41b","sourceCommitId":"ae000000-0000-4000-8000-000000000001","sourceCommitDigest":"sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2","revisionId":"af000000-0000-4000-8000-000000000001","revisionOrder":"41"},"safeFeedback":{"key":"welcome","definitionJson":{"encoding":"utf8-base64url-unpadded","bytes":"eyJhcmd1bWVudHMiOltdLCJhdWRpZW5jZSI6IlNPVVJDRV9BQ1RPUiIsImZlZWRiYWNrS2V5Ijoid2VsY29tZSIsIm1lc3NhZ2VLZXkiOiJ3ZWxjb21lX21lc3NhZ2UiLCJtZXNzYWdlVGVtcGxhdGUiOiJXZWxjb21lLCB0cmF2ZWxlci4iLCJvdXRjb21lRXZlbnQiOiJhY3Rvcl9jcmVhdGVkIiwicmVwbGF5UG9saWN5IjoiRUZGRUNUX0lERU1QT1RFTlQiLCJ2aXNpYmlsaXR5IjoiUFVCTElDIn0"},"definitionDigest":"sha256:8cf61d25d83637199e3d3386e43906f888fe477c3deb8e685a0a2494debfe871","sourceCommitId":"ae000000-0000-4000-8000-000000000001","sourceCommitDigest":"sha256:dbaa3b603d70a2b0518d679b6b41bf7d3acec7027b0c77df5857f8b30c0ed1f2","revisionId":"b0000000-0000-4000-8000-000000000001","revisionOrder":"42"}},"canonicalCreationInput":"{}"}} diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java new file mode 100644 index 0000000000..98f49c6f34 --- /dev/null +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java @@ -0,0 +1,798 @@ +package net.firedevops.firemud.entitymanagement.testing; + +import com.google.protobuf.ByteString; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +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.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.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.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.testing.AuthoringFixtures; +import net.firedevops.firemud.common.testing.PlayerCreatedPublishedPolicyFixtures; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicCatalog; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicPointer; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; + +/** + * Shared controlled wire fixture and real configured loopback mTLS source owner. It never creates + * Entity's AuthenticatedSource capability; callers must initialize the returned client and call + * read against the running owner. + */ +public final class ControlledPlayerCreatedRosterSourceFixture { + public static final String NAMESPACE = "test"; + private static final UUID FIXTURE_ID = UUID.fromString("01111111-1111-4111-8111-111111111111"); + + private final Path directory; + private final LoopbackMtlsTestPki.Pki pki; + private final WireFixture fixture; + + public ControlledPlayerCreatedRosterSourceFixture(Path directory) throws Exception { + this.directory = Objects.requireNonNull(directory, "directory"); + pki = + LoopbackMtlsTestPki.create( + directory, + "Entity roster source test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "entity", "spiffe://firemud/ns/test/sa/entity-management-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "server", "spiffe://firemud/ns/test/sa/game-session-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/social-groups-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/game-session-service", true)); + fixture = buildWireFixture("canonical-instance-launch-descriptor", null); + } + + public WireFixture wireFixture() { + return fixture; + } + + public WireFixture wireFixture(String descriptorId) throws Exception { + return buildWireFixture(descriptorId, null); + } + + /** Builds the same controlled publication with a chosen selected-commit identity. */ + public WireFixture wireFixture(String descriptorId, UUID selectedCommitId) throws Exception { + return buildWireFixture(descriptorId, Objects.requireNonNull(selectedCommitId)); + } + + public CommonGrpcClientProperties clientProperties(String identityName) + throws IOException, CertificateEncodingException { + return pki.clientProperties(directory, pki.identity(identityName)); + } + + public Owner owner(String identityName) throws Exception { + var response = new AtomicReference<>(fixture.response()); + var received = new CopyOnWriteArrayList(); + var observedPeer = new AtomicReference(); + var identity = pki.identity(identityName); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new CharacterCreatePublicSourceServiceGrpc + .CharacterCreatePublicSourceServiceImplBase() { + @Override + public void readPlayerCreatedRosterSource( + ReadPlayerCreatedRosterSourceRequest request, + StreamObserver observer) { + observedPeer.set(GrpcPeerIdentity.current().uri()); + received.add(request); + observer.onNext(response.get()); + observer.onCompleted(); + } + }, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new Owner(server, response, received, observedPeer); + } + + public EntityPlayerCreatedRosterSourceClient client(Owner owner) throws Exception { + Objects.requireNonNull(owner, "owner"); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + owner.server.getPort()); + return new EntityPlayerCreatedRosterSourceClient( + endpoints, clientProperties("entity"), new GrpcChannelFactory(), NAMESPACE); + } + + public static final class Owner implements AutoCloseable { + private final Server server; + private final AtomicReference response; + private final List received; + private final AtomicReference observedPeer; + + private Owner( + Server server, + AtomicReference response, + List received, + AtomicReference observedPeer) { + this.server = server; + this.response = response; + this.received = received; + this.observedPeer = observedPeer; + } + + public List receivedRequests() { + return List.copyOf(received); + } + + public String observedPeerUri() { + return observedPeer.get(); + } + + public void respondWith(ReadPlayerCreatedRosterSourceResponse nextResponse) { + response.set(Objects.requireNonNull(nextResponse, "nextResponse")); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The retained generated protobuf request and response messages are immutable.") + public record WireFixture( + ReadPlayerCreatedRosterSourceRequest request, + ReadPlayerCreatedRosterSourceResponse response, + AuthoredInitialActorCoreReadEvidence.ReadResult authored, + WorldCanonicalInstanceLifecycleEvidence world, + PublishedRealmEntryPolicySetEvidence policySet) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The retained generated protobuf request and response messages are immutable.") + public WireFixture {} + } + + private static WireFixture buildWireFixture(String descriptorId, UUID selectedCommitId) + throws Exception { + var originalWorld = AuthoringFixtures.lifecycleEvidence("ACTIVE", 7L); + var originalDescriptor = originalWorld.launchBinding().descriptor(); + var selector = originalWorld.launchBinding().releaseAttestation().worldStartLocationEvidence(); + var tenant = originalWorld.request().canonicalTenantId(); + var version = originalWorld.request().canonicalVersionId(); + var intakeId = UUID.randomUUID(); + var operationId = UUID.randomUUID(); + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, intakeId, tenant, "tenant-key", "synthetic-world", "Synthetic World"); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + intakeId, + originalDescriptor.authoredWorldSourceOperationId(), + requestDigest, + tenant, + "tenant-key", + "synthetic-world", + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var source = + new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + intakeId, + originalDescriptor.authoredWorldSourceOperationId(), + requestDigest, + tenant, + "tenant-key", + "synthetic-world", + "Synthetic World", + 42L, + "tenant-key", + "NEW_GAME_ROW", + evidenceDigest); + var intake = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + NAMESPACE, + intakeId, + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest); + var receipt = + new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + NAMESPACE, + intakeId, + operationId, + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest, + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(intake), + digest('e'), + source); + var descriptorRequest = + new AuthoredWorldLaunchDescriptorEvidence.Request( + NAMESPACE, + "world-lifecycle-control-request", + tenant, + "synthetic-world", + source.operationId(), + evidenceDigest, + 19L, + false, + null, + false, + null, + false, + null, + true, + "{}"); + var descriptor = + AuthoredWorldLaunchDescriptorEvidence.create( + descriptorRequest, + descriptorId, + 42L, + false, + null, + "{}", + originalDescriptor.generationConfigRevision(), + 9L, + 7L, + originalDescriptor.publishedReleaseBundleRef(), + false, + null); + var oldRelease = originalWorld.launchBinding().releaseAttestation(); + var association = + new StartSessionTemplateAssociationReadEvidence.Association( + tenant, + 19L, + version, + selectedCommitId == null + ? UUID.fromString(selector.request().appliedCommitId()) + : selectedCommitId, + selector.request().publishWorkflowId(), + digest('c'), + digest('a'), + NAMESPACE, + intakeId, + operationId, + source.operationId(), + descriptor.worldSlug(), + evidenceDigest, + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, NAMESPACE, FIXTURE_ID, intakeId, tenant), + receipt); + var prepared = + PlayerCreatedPublishedPolicyFixtures.prepare( + sourceBinding(association, association.sourceOperationId()).selectedCommit()); + selector = prepared.world(); + var release = + AuthoredWorldReleaseAttestationEvidence.create( + NAMESPACE, + descriptor.resultDigest(), + tenant, + version, + descriptor.worldSlug(), + source.operationId(), + evidenceDigest, + descriptor.launchDescriptorId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + selector.request().publishWorkflowId(), + selector.request().appliedCommitId(), + oldRelease.participantDigests(), + oldRelease.manifestHash(), + oldRelease.manifestSchemaVersion(), + oldRelease.requiredManifestAssetKeys(), + oldRelease.artifactDigests(), + oldRelease.commandDefinitions(), + oldRelease.generationConfigRevision(), + selector); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + FIXTURE_ID, + NAMESPACE, + tenant, + descriptor.worldSlug(), + originalWorld.request().canonicalGameInstanceId(), + originalWorld.request().playableStateNamespaceId(), + "SHARED", + true, + descriptor.controlPlaneRequestId(), + version, + descriptor.requestDigest(), + descriptor.resultDigest(), + release.evidenceDigest()); + var world = + new WorldCanonicalInstanceLifecycleEvidence( + lifecycleRequest, + new CompleteLaunchBindingEvidence(descriptor, release), + originalWorld.startLocation(), + originalWorld.runtimeRoomInstanceId(), + "ACTIVE", + 7L, + originalWorld.rowVersion(), + originalWorld.captureId(), + WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()) + .graphDigest() + .substring(7), + originalWorld.preparationInputDigest(), + originalWorld.operationalRegionAssignments()); + association = + new StartSessionTemplateAssociationReadEvidence.Association( + tenant, + 19L, + version, + UUID.fromString(selector.request().appliedCommitId()), + selector.request().publishWorkflowId(), + digest('c'), + digest('a'), + NAMESPACE, + intakeId, + operationId, + source.operationId(), + descriptor.worldSlug(), + evidenceDigest, + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, NAMESPACE, FIXTURE_ID, intakeId, tenant), + receipt); + var readRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + NAMESPACE, + FIXTURE_ID, + postTuple(tenant, NAMESPACE).canonicalBytes(), + FIXTURE_ID, + 8L, + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + version, + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest())); + var bundle = + PublishedReleaseBundle.newBuilder() + .setId(7L) + .setVersionId(42L) + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setPublishWorkflowId(release.publishWorkflowId()) + .setManifestHash(release.manifestHash()) + .setManifestSchemaVersion(release.manifestSchemaVersion()) + .addAllRequiredManifestAssetKeys(release.requiredManifestAssetKeys()) + .setGenerationConfigRevision(release.generationConfigRevision()) + .setPublishedReleaseBundleRef(release.publishedReleaseBundleRef()) + .setCanonicalTenantId(tenant.toString()) + .setCanonicalVersionId(version.toString()) + .addAllCommandDefinitions(release.commandDefinitions()); + for (var participant : release.participantDigests()) { + var item = + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigestPresent()) + item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + bundle.addParticipantDigests(item); + } + var authored = + new AuthoredInitialActorCoreReadEvidence.ReadResult( + readRequest, + new StartSessionTemplateAssociationReadEvidence.Result( + readRequest, association, bundle.build(), selector, 23L), + descriptor, + List.of( + AuthoredInitialActorCoreProjection.fromValidatedBinding( + FIXTURE_ID, sourceBinding(association, association.sourceOperationId())))); + var releaseContent = + StartSessionTemplateAssociationReadEvidence.releaseContent(bundle.build(), selector); + var policySet = + PlayerCreatedPublishedPolicyFixtures.seal( + prepared, + IsolatedWorldPublicationInventoryFixtures.stipulated( + prepared.account(), prepared.world()), + releaseContent, + authored.projections().getFirst()); + var request = + ReadPlayerCreatedRosterSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(FIXTURE_ID.toString()) + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(tenant.toString()) + .setRealmId(FIXTURE_ID.toString()) + .setWorldSlug(descriptor.worldSlug()) + .setRealmSlug("realm") + .setPlayableStateNamespaceId(lifecycleRequest.playableStateNamespaceId().toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceId(lifecycleRequest.canonicalGameInstanceId().toString()) + .setCatalogRevision(3L) + .setPointerVersion(5L) + .setExpectedCanonicalVersionId(version.toString()) + .setActiveWorldEpoch(7L) + .build(); + var response = + ReadPlayerCreatedRosterSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setCatalog( + CharacterCreatePublicCatalog.newBuilder() + .setTenantId(tenant.toString()) + .setTenantSlug("tenant") + .setWorldSlug(request.getWorldSlug()) + .setWorldDisplayName("Synthetic World") + .setRealmId(request.getRealmId()) + .setRealmSlug("realm") + .setRealmDisplayName("Realm") + .setVisible(true) + .setPublicProduction(true) + .setStateScope("SHARED") + .setPlayableStateNamespaceId(request.getPlayableStateNamespaceId()) + .setCharacterCreationPolicy("PLAYER_CREATED") + .setCatalogRevision(3L) + .setCreationRequestId(FIXTURE_ID.toString()) + .setReceiptDigest(digest('a'))) + .setPointer( + CharacterCreatePublicPointer.newBuilder() + .setTenantId(tenant.toString()) + .setRealmId(request.getRealmId()) + .setWorldSlug(request.getWorldSlug()) + .setRealmSlug("realm") + .setAdmissionState("OPEN") + .setAdmissibleGameInstanceId(request.getCanonicalGameInstanceId()) + .setPointerVersion(5L) + .setCatalogRevision(3L) + .setUpdatedAt("2026-10-24T00:00:00.123456789Z") + .setInitialAdmissionRequestId("initial-admission") + .setInitialAdmissionOwnerProofDigest(digest('b')) + .setAdmissionPointerSnapshotDigest("c".repeat(64))) + .setCanonicalVersionId(version.toString()) + .setActiveLifecycleEpoch(7L) + .setOriginalControlPlaneRequestId(descriptor.controlPlaneRequestId()) + .setOriginalOwnerAttemptId(FIXTURE_ID.toString()) + .setOriginalOwnerFence(8L) + .setAuthoredSource(AuthoredInitialActorCoreReadGrpcCodec.toResponse(authored)) + .setPublishedPolicySetEvidence(ByteString.copyFrom(policySet.canonicalBytes())) + .setWorldLifecycleEvidence(ByteString.copyFrom(world.canonicalBytes())) + .build(); + return new WireFixture(request, response, authored, world, policySet); + } + + private static StartSessionPostAuthorizationExecutionTuple postTuple( + UUID tenant, String namespace) { + StartSessionPreAuthorizationReservationTuple pre = + StartSessionPreAuthorizationReservationTuple.createHuman( + "world-lifecycle-control-request", + FIXTURE_ID, + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenant, namespace), + new StartSessionOperatorAction.Target(19L, FIXTURE_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation( + StartSessionOperatorAction.ClientIp.absent()), + "exact original selected authored actor core")); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + "arfp/v1/test-key/" + "b".repeat(64), + FIXTURE_ID, + 19L, + authorityBundle(pre, tenant, namespace), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551615")); + } + + private static byte[] authorityBundle( + StartSessionPreAuthorizationReservationTuple tuple, UUID tenant, String namespace) { + String tenantText = tenant.toString(); + Map value = + Map.of( + "bundleVersion", + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", Map.of("tenantId", tenantText, "targetNamespace", namespace), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", FIXTURE_ID.toString(), + "applicableTenantId", tenantText), + "accountProjectionEvidence", + Map.of( + "sourceType", "ACCOUNT", + "sourceEvidenceId", digest('a'), + "sourceEvidenceVersion", "17", + "projectionStatus", "CURRENT", + "evaluatedAt", "2026-10-09T00:00:00Z", + "expiresAt", "2026-10-09T00:05:00Z"), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", FIXTURE_ID.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", + "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantText, 3L), + "membershipAuthorityGeneration", Map.of(tenantText, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", + Map.of(tenantText, 5L), + "issuanceFence", + "23", + "issuanceEvidence", + Map.of( + "evidenceType", + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", + FIXTURE_ID.toString(), + "controlUiTokenJti", + FIXTURE_ID.toString(), + "role", + "tenantAdmin", + "accountGeneration", + "2", + "tenantGeneration", + "3")); + try { + return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value)); + } catch (IOException invalid) { + throw new IllegalStateException(invalid); + } + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding( + StartSessionTemplateAssociationReadEvidence.Association association, + UUID worldSourceOperationId) + throws Exception { + return sourceBinding(association, worldSourceOperationId, true); + } + + private static AuthoredInitialActorCoreSourceBinding sourceBinding( + StartSessionTemplateAssociationReadEvidence.Association association, + UUID worldSourceOperationId, + boolean visible) + throws Exception { + var policy = + RealmEntryPolicy.parse( + "{\"schemaVersion\":3,\"worldSlug\":\"" + + association.worldSlug() + + "\",\"worldDisplayName\":\"Synthetic World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":" + + visible + + "," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," + + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":{" + + "\"schemaVersion\":1,\"descriptorId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"," + + "\"descriptorRevisionId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}", + tools.jackson.databind.json.JsonMapper.builder().build()); + var policyPayload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmPolicySource.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r1", + "policy", + RealmPolicySource.tree(policy.canonicalJson()))); + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor_created", + Audience.SOURCE_ACTOR, + "welcome_message", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); + List revisions = + List.of( + new RevisionPayload( + "0", + UUID.fromString("13333333-3333-4333-8333-333333333333"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + policyPayload), + new RevisionPayload( + "1", + UUID.fromString("14444444-4444-4444-8444-444444444444"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(disposition)), + new RevisionPayload( + "2", + UUID.fromString("15555555-5555-4555-8555-555555555555"), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.upsertPayload(feedback))); + TargetProof target = + new TargetProof( + association.canonicalTenantId(), + association.canonicalVersionId(), + 42L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + DraftCommitBinding commit = + DraftCommitBinding.create( + target, + UUID.fromString("1eeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + association.selectedCommitId(), + "base-0", + revisions, + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + association.canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0"), + new AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + association.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + commit = PlayerCreatedPublishedPolicyFixtures.withWorldSource(commit); + var selectedPolicy = RealmPolicySource.revision(commit, revisions.getFirst()); + var policySnapshot = new RealmPolicySnapshot(commit, "1", List.of(selectedPolicy)); + var dispositionEntry = + new GameplayRuleSource.Entry( + Family.DISPOSITIONS, + disposition, + commit, + "1", + UUID.fromString("14444444-4444-4444-8444-444444444444")); + var feedbackEntry = + new GameplayRuleSource.Entry( + Family.FEEDBACK, + feedback, + commit, + "2", + UUID.fromString("15555555-5555-4555-8555-555555555555")); + var gameplay = + new GameplayRuleSelectedSource( + gameplaySnapshot(commit, List.of(dispositionEntry, feedbackEntry))); + return AuthoredInitialActorCoreSourceBinding.resolveAll( + worldSourceOperationId, + association.sourceEvidenceDigest(), + association.worldSlug(), + association.publishWorkflowId(), + bytes("selected publication operation bytes"), + bytes("selected release terminal evidence"), + commit, + policySnapshot, + gameplay) + .getFirst(); + } + + private static String gameplaySnapshot( + DraftCommitBinding binding, List entries) { + Map families = new java.util.LinkedHashMap<>(); + for (Family family : Family.values()) { + families.put( + family.name(), + entries.stream() + .filter(value -> value.family() == family) + .map(GameplayRuleSource.Entry::definition) + .toList()); + } + var manifest = + GameplayRuleManifest.fromStored( + GameplayRuleManifest.canonical( + Map.of("schema", GameplayRuleManifest.SCHEMA, "families", families))); + Map snapshot = new java.util.LinkedHashMap<>(); + snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); + snapshot.put("bindingJson", binding.canonicalJson()); + snapshot.put("bindingDigest", binding.digest()); + snapshot.put("sourceEpoch", "1"); + snapshot.put("inheritedCommitId", ""); + snapshot.put("genesisReceiptId", "77777777-7777-4777-8777-777777777777"); + snapshot.put("manifestJson", manifest.canonicalJson()); + snapshot.put( + "entries", + entries.stream() + .map( + entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) + .toList()); + return CommandSource.canonical(snapshot); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String digest(char value) { + return "sha256:" + String.valueOf(value).repeat(64); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java index f6c73b303b..381051d191 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java @@ -2,6 +2,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.time.Instant; @@ -9,6 +10,7 @@ import java.util.Objects; import java.util.UUID; import java.util.function.Consumer; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; @@ -18,10 +20,17 @@ import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +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.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; @@ -175,6 +184,12 @@ public ReadCharacterCreatePublicSourceResponse read( /** Exact current published PLAYER_CREATED input for Entity roster policy resolution only. */ public ReadPlayerCreatedRosterSourceResponse readPlayerCreatedRosterSource( ReadPlayerCreatedRosterSourceRequest request) { + return resolvePlayerCreatedRosterSource(request).response(); + } + + /** Owner-constructed source view, available only after complete current-source revalidation. */ + public ResolvedPlayerCreatedRosterSource resolvePlayerCreatedRosterSource( + ReadPlayerCreatedRosterSourceRequest request) { outsideSql(); requireRosterRequest(request, namespace); var facts = @@ -199,7 +214,87 @@ public ReadPlayerCreatedRosterSourceResponse readPlayerCreatedRosterSource( .setPublishedPolicySetEvidence(ByteString.copyFrom(facts.policySet().canonicalBytes())) .build(); if (response.getSerializedSize() > MAX_RESPONSE_BYTES) throw missing(); - return response; + var descriptor = + PlayerCreationDescriptor.parse(facts.projection().descriptor().canonicalJson()); + var sourceIdentity = + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(facts.projection().bindingId().toString()) + .setAuthoredBindingDigest(facts.projection().bindingDigest()) + .build()); + var route = facts.route(); + var target = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(route.canonicalTenantId().toString()) + .setRealmUuid(route.realmId().toString()) + .setWorldSlug(route.worldSlug()) + .setRealmSlug(route.realmSlug()) + .setGameInstanceUuid(route.canonicalGameInstanceId().toString()) + .setCanonicalVersionUuid(route.canonicalVersionId().toString()) + .setPlayableStateNamespaceUuid(route.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCatalogRevision(route.catalogRevision()) + .setPointerVersion(route.pointerVersion()) + .setActiveWorldEpoch(route.activeWorldEpoch()) + .setPublishedPolicyDigest(rawSourceDigest(facts.selectedPolicy().policyDigest())) + .setPublishedReleaseBundleRef(facts.policySet().publishedReleaseBundleRef()) + .setAdmissionPointerSnapshotDigest( + facts.pointer().snapshot().admissionPointerSnapshotDigest()) + .setPublishedOwnerProofDigest( + rawSourceDigest(facts.pointer().snapshot().ownerProof().proofDigest())) + .build(); + return new ResolvedPlayerCreatedRosterSource(response, route, target, sourceIdentity); + } + + private static String rawSourceDigest(String value) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) throw missing(); + return value.substring(7); + } + + /** + * Immutable source facts; no public factory can turn an arbitrary wire response into this view. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The route and protobuf source values are immutable") + public static final class ResolvedPlayerCreatedRosterSource { + private final ReadPlayerCreatedRosterSourceResponse response; + private final CanonicalPlayableTarget route; + private final CanonicalGameplayRosterTarget target; + private final CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity; + + private ResolvedPlayerCreatedRosterSource( + ReadPlayerCreatedRosterSourceResponse response, + CanonicalPlayableTarget route, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity) { + this.response = response; + this.route = route; + this.target = target; + this.sourceIdentity = sourceIdentity; + } + + public ReadPlayerCreatedRosterSourceResponse response() { + return response; + } + + public CanonicalPlayableTarget route() { + return route; + } + + public CanonicalGameplayRosterTarget target() { + return target; + } + + public CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity() { + return sourceIdentity; + } } private SourceFacts readSource( @@ -247,7 +342,7 @@ private SourceFacts readSource( || !sourceRequest.associationRequest().equals(authored.request()) || !launch.launchBindingEvidence().descriptor().equals(authored.descriptor())) throw missing(); - requireProjection(before, catalog, retained, authored); + var projection = requireProjection(before, catalog, retained, authored); var descriptor = launch.launchBindingEvidence().descriptor(); var lifecycleRequest = new WorldCanonicalInstanceLifecycleEvidence.Request( @@ -277,8 +372,10 @@ private SourceFacts readSource( || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() || !launch.launchBindingEvidence().equals(lifecycle.launchBinding())) throw missing(); - var policySet = - includePublishedPolicies ? readPublishedPolicies(before, authored, lifecycle) : null; + var policies = + includePublishedPolicies + ? readPublishedPolicies(before, authored, lifecycle, projection) + : null; // Re-read every complete local source after all remote calls; never select a newer target. CanonicalPlayableTarget after = routes.readCurrentTarget(tenant); @@ -296,7 +393,16 @@ private SourceFacts readSource( if (!Arrays.equals(confirmed.canonicalSourceResultBytes(), authored.canonicalBytes()) || !confirmed.sourceResultDigest().equals(authored.digest())) throw missing(); return new SourceFacts( - before, catalog, pointer, launch, retained, authored, lifecycle, policySet); + before, + catalog, + pointer, + launch, + retained, + authored, + lifecycle, + policies == null ? null : policies.set(), + projection, + policies == null ? null : policies.selected()); } private record SourceFacts( @@ -307,12 +413,18 @@ private record SourceFacts( Candidate retained, AuthoredInitialActorCoreReadEvidence.ReadResult authored, WorldCanonicalInstanceLifecycleEvidence lifecycle, - PublishedRealmEntryPolicySetEvidence policySet) {} + PublishedRealmEntryPolicySetEvidence policySet, + AuthoredInitialActorCoreProjection projection, + PublishedRealmEntryPolicyEvidence selectedPolicy) {} + + private record PublishedPolicies( + PublishedRealmEntryPolicySetEvidence set, PublishedRealmEntryPolicyEvidence selected) {} - private PublishedRealmEntryPolicySetEvidence readPublishedPolicies( + private PublishedPolicies readPublishedPolicies( CanonicalPlayableTarget route, AuthoredInitialActorCoreReadEvidence.ReadResult authored, - WorldCanonicalInstanceLifecycleEvidence lifecycle) { + WorldCanonicalInstanceLifecycleEvidence lifecycle, + AuthoredInitialActorCoreProjection projection) { outsideSql(); PublishedRealmEntryPolicySetEvidence set; try { @@ -349,16 +461,6 @@ private PublishedRealmEntryPolicySetEvidence readPublishedPolicies( || !set.manifestHash().equals(bundle.getManifestHash()) || !set.manifestHash().equals(worldRelease.manifestHash()) || set.versionNumber() != bundle.getVersionNumber()) throw missing(); - var projections = - authored.projections().stream() - .filter( - projection -> - RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), JSON) - .realmSlug() - .equals(route.realmSlug())) - .toList(); - if (projections.size() != 1) throw missing(); - var projection = projections.getFirst(); var matches = set.policies().stream() .filter( @@ -385,7 +487,7 @@ private PublishedRealmEntryPolicySetEvidence readPublishedPolicies( .selectedCommit() .digest() .equals(projection.selectedCommitDigest())) throw missing(); - return set; + return new PublishedPolicies(set, evidence); } static void requireRosterRequest(ReadPlayerCreatedRosterSourceRequest request, String namespace) { @@ -577,7 +679,7 @@ private static void requireOriginal( throw missing(); } - private static void requireProjection( + private static AuthoredInitialActorCoreProjection requireProjection( CanonicalPlayableTarget route, CanonicalRealmCatalogSnapshot catalog, Candidate retained, @@ -612,6 +714,7 @@ private static void requireProjection( || !projection.selectedCommitId().equals(retained.selectedCommitId()) || !projection.publicationWorkflowId().equals(retained.publishWorkflowId())) throw missing(); + return projection; } static void requireRequest(ReadCharacterCreatePublicSourceRequest request, String namespace) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java new file mode 100644 index 0000000000..bb0d2ae0ee --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java @@ -0,0 +1,386 @@ +package net.firedevops.firemud.gamesession.client; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import java.io.IOException; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +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.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +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.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository.SelectionOutcome; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Unregistered manual consumer of independently resolved SHARED PLAYER_CREATED source facts. */ +public final class CanonicalPlayerCreatedRosterClient + extends AbstractReloadingBlockingGrpcClient< + CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub> { + private final String namespace; + private final CanonicalGameplayRosterReferenceOwner owner; + + public CanonicalPlayerCreatedRosterClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace, + CanonicalGameplayRosterReferenceOwner owner) { + super( + endpoints, + requireFileBackedMtls(tls, "PLAYER_CREATED roster reads"), + channels, + CanonicalPlayerCreatedRosterClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed Game Session workload namespace required"); + } + this.namespace = namespace; + this.owner = owner; + } + + public void init() throws IOException { + requireNoAmbientSql("PLAYER_CREATED client initialization requires no ambient SQL"); + initOnce("PLAYER_CREATED roster client is closed", "Entity PLAYER_CREATED roster unavailable"); + } + + @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) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return CanonicalGameplayRosterServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip"); + } + + public void reserveSelectionInput( + ResolvedPlayerCreatedRosterSource source, + PlayerExecutionContext context, + String selector, + UUID menuSnapshotUuid, + String digest) { + requireOutsideSql(); + var request = rosterRequest(source, context); + var input = + CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector(selector == null ? "" : selector); + if (menuSnapshotUuid != null || digest != null) { + input + .setMenuSnapshotUuid( + Objects.requireNonNull(menuSnapshotUuid, "menuSnapshotUuid").toString()) + .setMenuSnapshotDigest(Objects.requireNonNull(digest, "digest")); + } + requireOwner() + .reserveSelectionInput( + original(request), + CanonicalGameplayRosterReferenceEvidence.requireSelectionInput(input.build())); + } + + public void completeSelection( + ResolvedPlayerCreatedRosterSource source, + PlayerExecutionContext context, + SelectionOutcome outcome) { + requireOutsideSql(); + requireOwner().completeSelection(original(rosterRequest(source, context)), outcome); + } + + public VerifiedPlayerCreatedRoster listPlayerCreatedRoster( + ResolvedPlayerCreatedRosterSource source, PlayerExecutionContext context) { + requireOutsideSql(); + var request = rosterRequest(source, context); + var originalRequest = original(request); + var referenceOwner = requireOwner(); + var retained = requireOriginal(originalRequest, referenceOwner.begin(originalRequest)); + if (!retained.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + var response = + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(retained)); + return new VerifiedPlayerCreatedRoster(source, request, originalRequest, response); + } + var current = requireStub(); + referenceOwner.markRosterReadStarted(originalRequest); + var response = + CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, + current + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .withMaxInboundMessageSize( + CanonicalPlayerCreatedRosterEvidence.MAX_ROSTER_RECEIPT_BYTES) + .listPlayerCreatedRoster(request)); + var recorded = + requireOriginal( + originalRequest, referenceOwner.recordPlayerCreated(originalRequest, response)); + if (!response.equals(CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(recorded))) { + throw new IllegalArgumentException( + "Recorded PLAYER_CREATED roster differs from Entity response"); + } + return new VerifiedPlayerCreatedRoster(source, request, originalRequest, response); + } + + public VerifiedPlayerCreatedCharacter readSelectedPlayerCreatedCharacter( + VerifiedPlayerCreatedRoster roster, PlayerExecutionContext context) { + requireOutsideSql(); + Objects.requireNonNull(roster, "roster"); + // Recheck the exact original context and private source, not a caller-built response wrapper. + var originalContext = roster.listRequest.getPlayerExecutionContext(); + var listContext = context.toBuilder().clearCharacterId().build(); + if (!originalContext.equals(listContext) + || !roster.listRequest.equals(rosterRequest(roster.source, listContext))) { + throw new IllegalArgumentException( + "Selected context or source changed the original roster operation"); + } + long matches = + roster.actors().stream() + .filter(actor -> actor.getCharacterUuid().equals(context.getCharacterId())) + .count(); + if (matches != 1L) { + throw new IllegalArgumentException( + "Selected actor must occur exactly once in the original menu"); + } + var request = + CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest( + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(roster.original.getOperationUuid()) + .setCanonicalAccountUuid(roster.original.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(context.getCharacterId()) + .setExpectedTarget(roster.target()) + .setExpectedSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(roster.snapshotUuid().toString()) + .setSnapshotDigest(roster.snapshotDigest())) + .setExpectedSource(roster.sourceIdentity()) + .setPlayerExecutionContext(context) + .build()); + var referenceOwner = requireOwner(); + var selected = + requireOriginal( + roster.original, + referenceOwner.selectOriginal( + roster.original, UUID.fromString(context.getCharacterId()))); + if (!selected.getSelectedCharacterUuid().equals(context.getCharacterId()) + || !roster.response.equals( + CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(selected))) { + throw new IllegalArgumentException( + "Selected original differs from its exact retained created menu"); + } + CanonicalSelectedPlayerCreatedCharacterResponse response; + boolean cached = !selected.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty(); + if (cached) { + response = + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt(selected); + } else { + response = + requireStub() + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .withMaxInboundMessageSize( + CanonicalPlayerCreatedRosterEvidence.MAX_SELECTED_RECEIPT_BYTES) + .readSelectedPlayerCreatedCharacter(request); + } + requireSelectedResponse(request, response); + if (!cached) { + referenceOwner.recordSelectedPlayerCreatedCharacter(roster.original, response); + } + return new VerifiedPlayerCreatedCharacter(roster, response); + } + + private void requireSelectedResponse( + CanonicalSelectedPlayerCreatedCharacterRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse response) { + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, response); + if (!namespace.equals( + response.getTerminal().getOriginalRequest().getOriginal().getTargetNamespace())) { + throw new IllegalArgumentException("Selected creation original changed the owner namespace"); + } + } + + private CanonicalPlayerCreatedRosterRequest rosterRequest( + ResolvedPlayerCreatedRosterSource source, PlayerExecutionContext context) { + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(context, "context"); + if (!namespace.equals(source.route().targetNamespace())) { + throw new IllegalArgumentException("Resolved PLAYER_CREATED source changed owner namespace"); + } + return CanonicalPlayerCreatedRosterEvidence.requireRequest( + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(context.getRequestId()) + .setCanonicalAccountUuid(context.getAccountId()) + .setExpectedTarget(source.target()) + .setExpectedSource(source.sourceIdentity()) + .setPlayerExecutionContext(context) + .build()); + } + + private GetCanonicalGameplayRosterReferenceRequest original( + CanonicalPlayerCreatedRosterRequest request) { + return CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(request.getRequestUuid()), + UUID.fromString(request.getCanonicalAccountUuid()), + UUID.fromString(request.getPlayerExecutionContext().getSessionId()), namespace, + request.getExpectedTarget(), request.getExpectedSource()); + } + + private static GetCanonicalGameplayRosterReferenceResponse requireOriginal( + GetCanonicalGameplayRosterReferenceRequest request, + GetCanonicalGameplayRosterReferenceResponse response) { + CanonicalGameplayRosterReferenceEvidence.requireResponse(request, response); + CanonicalGameplayRosterReferenceEvidence.requireDereference(response); + return response; + } + + private CanonicalGameplayRosterReferenceOwner requireOwner() { + if (owner == null) { + throw Status.UNAVAILABLE + .withDescription("Canonical roster reference owner is unavailable") + .asRuntimeException(); + } + return owner; + } + + private CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub + requireStub() { + try { + return requireInitializedStub("Entity PLAYER_CREATED roster unavailable"); + } catch (IllegalStateException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Entity PLAYER_CREATED roster unavailable") + .withCause(unavailable) + .asRuntimeException(); + } + } + + private static void requireOutsideSql() { + requireNoAmbientSql( + "PLAYER_CREATED roster operations require no ambient transaction or synchronization"); + } + + /** Exact Entity response, obtained by this client or retained by the original reference owner. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Private resolved source and protobuf messages are immutable") + public static final class VerifiedPlayerCreatedRoster { + private final ResolvedPlayerCreatedRosterSource source; + private final CanonicalPlayerCreatedRosterRequest listRequest; + private final GetCanonicalGameplayRosterReferenceRequest original; + private final CanonicalPlayerCreatedRosterResponse response; + + private VerifiedPlayerCreatedRoster( + ResolvedPlayerCreatedRosterSource source, + CanonicalPlayerCreatedRosterRequest listRequest, + GetCanonicalGameplayRosterReferenceRequest original, + CanonicalPlayerCreatedRosterResponse response) { + this.source = source; + this.listRequest = listRequest; + this.original = original; + this.response = response; + } + + public ResolvedPlayerCreatedRosterSource resolvedSource() { + return source; + } + + public GetCanonicalGameplayRosterReferenceRequest originalSelection() { + return original; + } + + public CanonicalPlayerCreatedRosterResponse response() { + return response; + } + + public CanonicalGameplayRosterTarget target() { + return response.getRoster().getTarget(); + } + + public CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity() { + return response.getSourceIdentity(); + } + + public UUID canonicalAccountUuid() { + return UUID.fromString(response.getRoster().getCanonicalAccountUuid()); + } + + public UUID snapshotUuid() { + return UUID.fromString(response.getRoster().getSnapshotUuid()); + } + + public String snapshotDigest() { + return response.getRoster().getSnapshotDigest(); + } + + public List actors() { + return response.getRoster().getActorsList(); + } + } + + /** Exact persisted creation terminal; this is neither an assignment UUID nor admission proof. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "The verified roster and complete selected protobuf response are immutable") + public static final class VerifiedPlayerCreatedCharacter { + private final VerifiedPlayerCreatedRoster roster; + private final CanonicalSelectedPlayerCreatedCharacterResponse response; + + private VerifiedPlayerCreatedCharacter( + VerifiedPlayerCreatedRoster roster, + CanonicalSelectedPlayerCreatedCharacterResponse response) { + this.roster = roster; + this.response = response; + } + + public VerifiedPlayerCreatedRoster roster() { + return roster; + } + + public CanonicalSelectedPlayerCreatedCharacterResponse response() { + return response; + } + + public UUID selectedCharacterUuid() { + return UUID.fromString(response.getSelectedCharacterUuid()); + } + + public UUID creationOperationUuid() { + return UUID.fromString(response.getCreationOperationUuid()); + } + + public String mutationDigest() { + return response.getMutationDigest(); + } + + public EntityCharacterCreateTerminal terminal() { + return response.getTerminal(); + } + } +} 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 a62581684b..53298477eb 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,6 +7,7 @@ import java.util.UUID; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedRoster; import net.firedevops.firemud.gamesession.dto.CanonicalPublishedPlayerRoute; /** @@ -54,13 +55,53 @@ public static SelectionResult select(ValidatedRoster roster, String selector) { if (roster == null) { return new Denied(Denial.INVALID_SNAPSHOT); } - List actors = roster.snapshot().actors(); + var snapshot = roster.snapshot(); + return select( + roster.canonicalAccountUuid(), + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + snapshot.target(), + snapshot.actors(), + selector, + Denial.NO_PRESEEDED_ACTOR); + } + + /** Reuses ordinal selection only for the created client's private-constructed verified menu. */ + public static SelectionResult select(VerifiedPlayerCreatedRoster roster, String selector) { + if (roster == null) { + return new Denied(Denial.INVALID_SNAPSHOT); + } + var actors = + roster.actors().stream() + .map( + actor -> + new CanonicalGameplayRosterClient.RosterActor( + UUID.fromString(actor.getCharacterUuid()), actor.getDisplayName())) + .toList(); + return select( + roster.canonicalAccountUuid(), + roster.snapshotUuid(), + roster.snapshotDigest(), + roster.target(), + actors, + selector, + Denial.NO_PLAYER_CREATED_ACTOR); + } + + private static SelectionResult select( + UUID account, + UUID snapshot, + String digest, + CanonicalGameplayRosterTarget target, + List actors, + String selector, + Denial empty) { if (actors.isEmpty()) { - return new Denied(Denial.NO_PRESEEDED_ACTOR); + return new Denied(empty); } if (selector == null || selector.isBlank()) { if (actors.size() == 1) { - return selected(roster, 1, actors.getFirst()); + return selected(account, snapshot, digest, target, 1, actors.getFirst()); } return new SelectionRequired( actors.stream() @@ -79,20 +120,18 @@ public static SelectionResult select(ValidatedRoster roster, String selector) { if (ordinal > actors.size()) { return new Denied(Denial.SELECTOR_OUT_OF_RANGE); } - return selected(roster, ordinal, actors.get(ordinal - 1)); + return selected(account, snapshot, digest, target, ordinal, actors.get(ordinal - 1)); } private static Selected selected( - ValidatedRoster roster, int ordinal, CanonicalGameplayRosterClient.RosterActor actor) { - CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot = roster.snapshot(); + UUID account, + UUID snapshot, + String digest, + CanonicalGameplayRosterTarget target, + int ordinal, + CanonicalGameplayRosterClient.RosterActor actor) { return new Selected( - roster.canonicalAccountUuid(), - snapshot.snapshotUuid(), - snapshot.snapshotDigest(), - snapshot.target(), - actor.characterUuid(), - actor.displayName(), - ordinal); + account, snapshot, digest, target, actor.characterUuid(), actor.displayName(), ordinal); } private static boolean isCanonicalDigest(String value) { @@ -213,6 +252,7 @@ public record Denied(Denial reason) implements SelectionResult { public enum Denial { INVALID_SNAPSHOT, NO_PRESEEDED_ACTOR, + NO_PLAYER_CREATED_ACTOR, INVALID_SELECTOR, SELECTOR_OUT_OF_RANGE } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java index 94fbb9bc2a..53ce3bc214 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java @@ -5,7 +5,10 @@ import java.util.Objects; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationRequest; @@ -67,11 +70,12 @@ public GetCanonicalGameplayRosterReferenceResponse begin( throw new IllegalStateException("CANONICAL_ROSTER_TARGET_FENCE_RETIRED"); } dsl.execute( - "INSERT INTO game_session_canonical_roster_selection (operation_uuid, original_request, target_fence_uuid) " - + "VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + "INSERT INTO game_session_canonical_roster_selection (operation_uuid, original_request, target_fence_uuid, entry_policy) " + + "VALUES (?, ?, ?, ?) ON CONFLICT DO NOTHING", CanonicalGameplayRosterReferenceEvidence.uuid(request.getOperationUuid()), request.toByteArray(), - fence.get("target_fence_uuid", java.util.UUID.class)); + fence.get("target_fence_uuid", java.util.UUID.class), + entryPolicy(request)); Record replay = dsl.fetchSingle( "SELECT terminal_at IS NOT NULL AND terminal_at + ? * interval '1 millisecond' <= clock_timestamp() AS closed " @@ -144,6 +148,34 @@ public GetCanonicalGameplayRosterReferenceResponse record( return readExact(request, true); } + public GetCanonicalGameplayRosterReferenceResponse recordPlayerCreated( + GetCanonicalGameplayRosterReferenceRequest request, + CanonicalPlayerCreatedRosterResponse receipt) { + requireWritableTransaction(); + var original = readExact(request, true); + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + request, + original.getOwnerFence(), + java.util.UUID.fromString(original.getTargetFenceUuid()), + Objects.requireNonNull(receipt, "receipt")); + if (!original.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + if (!original.getCanonicalPlayerCreatedRosterReceipt().equals(receipt.toByteString())) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } + return original; + } + int changed = + dsl.execute( + "UPDATE game_session_canonical_roster_selection " + + "SET canonical_player_created_roster_receipt = ?, receipt_recorded_at = clock_timestamp() " + + "WHERE operation_uuid = ? AND owner_fence = ? AND entry_policy = 'PLAYER_CREATED' AND canonical_player_created_roster_receipt IS NULL", + receipt.toByteArray(), + CanonicalGameplayRosterReferenceEvidence.uuid(request.getOperationUuid()), + original.getOwnerFence()); + if (changed != 1) throw new IllegalStateException("CANONICAL_ROSTER_OWNER_FENCE_CHANGED"); + return readExact(request, true); + } + public void reserveSelectionInput( GetCanonicalGameplayRosterReferenceRequest request, net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput input) { @@ -156,7 +188,7 @@ public void reserveSelectionInput( } return; } - if (!original.getCanonicalRosterReceipt().isEmpty()) { + if (hasRoster(original)) { throw new IllegalStateException("CANONICAL_ROSTER_SELECTION_INPUT_NOT_RESERVED_BEFORE_READ"); } dsl.execute( @@ -177,7 +209,7 @@ public GetCanonicalGameplayRosterReferenceResponse selectOriginal( && !"SELECTED".equals(original.getTerminalOutcome())) { throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_TERMINAL_NOT_SELECTED"); } - var roster = CanonicalGameplayRosterReferenceEvidence.receipt(original); + var roster = CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(original); var input = original.getSelectionInput(); int ordinal = 1; if (input.getSelector().isBlank()) { @@ -217,10 +249,14 @@ public void recordSelectedAssignment( net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSelectedAssignmentResponse receipt) { requireWritableTransaction(); + CanonicalGameplayRosterReferenceEvidence.requireRequest(request); + if (isPlayerCreated(request)) + throw new IllegalArgumentException("PRESEEDED_ONLY assignment receipt required"); var original = readExact(request, true); - CanonicalGameplayRosterReferenceEvidence.requireResponse( - request, - original.toBuilder().setCanonicalSelectedAssignmentReceipt(receipt.toByteString()).build()); + var candidate = + original.toBuilder().setCanonicalSelectedAssignmentReceipt(receipt.toByteString()).build(); + CanonicalGameplayRosterReferenceEvidence.requireResponse(request, candidate); + CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt(candidate); if (!original.getCanonicalSelectedAssignmentReceipt().isEmpty()) { if (!original.getCanonicalSelectedAssignmentReceipt().equals(receipt.toByteString())) { throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_ASSIGNMENT_RECEIPT_CONFLICT"); @@ -234,6 +270,36 @@ public void recordSelectedAssignment( original.getOwnerFence()); } + public void recordSelectedPlayerCreatedCharacter( + GetCanonicalGameplayRosterReferenceRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse receipt) { + requireWritableTransaction(); + CanonicalGameplayRosterReferenceEvidence.requireRequest(request); + if (!isPlayerCreated(request)) + throw new IllegalArgumentException("PLAYER_CREATED selected terminal required"); + var original = readExact(request, true); + var candidate = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt(receipt.toByteString()) + .build(); + CanonicalGameplayRosterReferenceEvidence.requireResponse(request, candidate); + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt(candidate); + if (!original.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty()) { + if (!original + .getCanonicalSelectedPlayerCreatedCharacterReceipt() + .equals(receipt.toByteString())) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_CREATED_RECEIPT_CONFLICT"); + } + return; + } + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET canonical_selected_player_created_character_receipt = ? " + + "WHERE operation_uuid = ? AND owner_fence = ? AND entry_policy = 'PLAYER_CREATED'", + receipt.toByteArray(), + CanonicalGameplayRosterReferenceEvidence.uuid(request.getOperationUuid()), + original.getOwnerFence()); + } + private GetCanonicalGameplayRosterReferenceResponse readExact( GetCanonicalGameplayRosterReferenceRequest request, boolean lock) { if (lock) { @@ -259,15 +325,28 @@ private GetCanonicalGameplayRosterReferenceResponse readExact( if (lock && row.get("recovery_uuid", java.util.UUID.class) != null) { throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECOVERY_FENCED"); } + if (!entryPolicy(request).equals(row.get("entry_policy", String.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_POLICY_CONFLICT"); + } byte[] receipt = row.get("canonical_roster_receipt", byte[].class); + byte[] createdReceipt = row.get("canonical_player_created_roster_receipt", byte[].class); try { var result = - CanonicalGameplayRosterReferenceEvidence.response( - request, - row.get("owner_fence", Long.class), - row.get("target_fence_uuid", java.util.UUID.class), - receipt == null ? null : CanonicalGameplayRosterResponse.parseFrom(receipt)) - .toBuilder(); + GetCanonicalGameplayRosterReferenceResponse.newBuilder() + .setRequest(request) + .setOwnerFence(row.get("owner_fence", Long.class)) + .setTargetFenceUuid(row.get("target_fence_uuid", java.util.UUID.class).toString()) + .setState( + receipt == null && createdReceipt == null + ? net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RESERVED + : net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED); + if (receipt != null) + result.setCanonicalRosterReceipt(com.google.protobuf.ByteString.copyFrom(receipt)); + if (createdReceipt != null) + result.setCanonicalPlayerCreatedRosterReceipt( + com.google.protobuf.ByteString.copyFrom(createdReceipt)); byte[] input = row.get("selection_input", byte[].class); if (input != null) { result.setSelectionInput( @@ -283,6 +362,11 @@ private GetCanonicalGameplayRosterReferenceResponse readExact( result.setCanonicalSelectedAssignmentReceipt( com.google.protobuf.ByteString.copyFrom(selectedReceipt)); } + byte[] selectedCreated = + row.get("canonical_selected_player_created_character_receipt", byte[].class); + if (selectedCreated != null) + result.setCanonicalSelectedPlayerCreatedCharacterReceipt( + com.google.protobuf.ByteString.copyFrom(selectedCreated)); java.util.UUID recovery = row.get("recovery_uuid", java.util.UUID.class); if (recovery != null) { result.setRecoveryUuid(recovery.toString()); @@ -317,7 +401,7 @@ private GetCanonicalGameplayRosterReferenceResponse readExact( public void markRosterReadStarted(GetCanonicalGameplayRosterReferenceRequest request) { requireWritableTransaction(); var original = readExact(request, true); - if (original.getCanonicalRosterReceipt().isEmpty()) { + if (!hasRoster(original)) { dsl.execute( "UPDATE game_session_canonical_roster_selection SET roster_read_started = TRUE WHERE operation_uuid = ? AND NOT roster_read_started AND terminal_outcome IS NULL", CanonicalGameplayRosterReferenceEvidence.uuid(request.getOperationUuid())); @@ -336,7 +420,7 @@ public void completeUnissuedDenied(GetCanonicalGameplayRosterReferenceRequest re dsl.execute( "UPDATE game_session_canonical_roster_selection SET terminal_outcome = 'DENIED', terminal_at = clock_timestamp() " + "WHERE operation_uuid = ? AND original_request = ? AND NOT roster_read_started AND terminal_outcome IS NULL AND recovery_uuid IS NULL " - + "AND canonical_roster_receipt IS NULL AND selected_character_uuid IS NULL", + + "AND canonical_roster_receipt IS NULL AND canonical_player_created_roster_receipt IS NULL AND selected_character_uuid IS NULL", CanonicalGameplayRosterReferenceEvidence.uuid(request.getOperationUuid()), request.toByteArray()); } @@ -356,15 +440,23 @@ public void completeSelection( } return; } + boolean created = "PLAYER_CREATED".equals(row.get("entry_policy", String.class)); + byte[] roster = + row.get( + created ? "canonical_player_created_roster_receipt" : "canonical_roster_receipt", + byte[].class); + byte[] selected = + row.get( + created + ? "canonical_selected_player_created_character_receipt" + : "canonical_selected_assignment_receipt", + byte[].class); if (row.get("selection_input", byte[].class) == null - || (Boolean.TRUE.equals(row.get("roster_read_started", Boolean.class)) - && row.get("canonical_roster_receipt", byte[].class) == null) - || (row.get("selected_character_uuid", java.util.UUID.class) != null - && row.get("canonical_selected_assignment_receipt", byte[].class) == null) - || (outcome == SelectionOutcome.SELECTED - && row.get("canonical_selected_assignment_receipt", byte[].class) == null) + || (Boolean.TRUE.equals(row.get("roster_read_started", Boolean.class)) && roster == null) + || (row.get("selected_character_uuid", java.util.UUID.class) != null && selected == null) + || (outcome == SelectionOutcome.SELECTED && selected == null) || (outcome == SelectionOutcome.MENU - && (row.get("canonical_roster_receipt", byte[].class) == null + && (roster == null || row.get("selected_character_uuid", java.util.UUID.class) != null))) { throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECOVERY_REQUIRED"); } @@ -401,8 +493,8 @@ public boolean sealTargetRetirement( + "superseding_catalog_revision = ?, superseding_world_epoch = ? WHERE target_binding_digest = ? AND fence_state = 'ACTIVE' " + "AND NOT EXISTS (SELECT 1 FROM game_session_canonical_roster_selection s WHERE s.target_fence_uuid = f.target_fence_uuid " + "AND (s.terminal_at IS NULL OR s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' > clock_timestamp() " - + "OR ((s.roster_read_started AND s.canonical_roster_receipt IS NULL " - + "OR s.selected_character_uuid IS NOT NULL AND s.canonical_selected_assignment_receipt IS NULL) " + + "OR ((s.roster_read_started AND s.canonical_roster_receipt IS NULL AND s.canonical_player_created_roster_receipt IS NULL " + + "OR s.selected_character_uuid IS NOT NULL AND s.canonical_selected_assignment_receipt IS NULL AND s.canonical_selected_player_created_character_receipt IS NULL) " + "AND NOT (s.recovery_uuid IS NOT NULL AND s.recovery_receipt IS NOT NULL AND s.terminal_outcome = 'DENIED'))))", java.util.UUID.randomUUID(), current.admissionPointerSnapshotDigest(), @@ -519,18 +611,28 @@ public void finishRecovery( if (!original.getTerminalOutcome().isEmpty()) { throw new IllegalStateException("CANONICAL_ROSTER_RECOVERY_OUTCOME_CONFLICT"); } - if (!original.getCanonicalRosterReceipt().isEmpty() - && !original.getCanonicalRosterReceipt().equals(response.getCanonicalRosterReceipt())) { + boolean created = isPlayerCreated(request); + var originalReceipt = + created + ? original.getCanonicalPlayerCreatedRosterReceipt() + : original.getCanonicalRosterReceipt(); + var recoveredReceipt = + created + ? response.getCanonicalPlayerCreatedRosterReceipt() + : response.getCanonicalRosterReceipt(); + if (!originalReceipt.isEmpty() && !originalReceipt.equals(recoveredReceipt)) { throw new IllegalStateException("CANONICAL_ROSTER_RECOVERY_ROSTER_CONFLICT"); } - byte[] receipt = - response.getCanonicalRosterReceipt().isEmpty() - ? null - : response.getCanonicalRosterReceipt().toByteArray(); + byte[] receipt = recoveredReceipt.isEmpty() ? null : recoveredReceipt.toByteArray(); + String column = + created ? "canonical_player_created_roster_receipt" : "canonical_roster_receipt"; dsl.execute( "UPDATE game_session_canonical_roster_selection SET " - + "canonical_roster_receipt = COALESCE(canonical_roster_receipt, ?::bytea), " - + "receipt_recorded_at = CASE WHEN canonical_roster_receipt IS NULL AND ?::bytea IS NOT NULL THEN clock_timestamp() ELSE receipt_recorded_at END, " + + column + + " = COALESCE(" + + column + + ", ?::bytea), " + + "receipt_recorded_at = CASE WHEN canonical_roster_receipt IS NULL AND canonical_player_created_roster_receipt IS NULL AND ?::bytea IS NOT NULL THEN clock_timestamp() ELSE receipt_recorded_at END, " + "recovery_receipt = ?, terminal_outcome = 'DENIED', terminal_at = clock_timestamp() " + "WHERE operation_uuid = ? AND recovery_uuid = ? AND terminal_outcome IS NULL", receipt, @@ -644,11 +746,11 @@ public CanonicalGameplayRosterRetirementAcknowledgementResponse acknowledgeRetir throw new IllegalArgumentException("CANONICAL_ROSTER_RETIREMENT_OBSERVATION_CONFLICT"); } if (request.getSnapshotUuid().isEmpty()) { - if (!original.getCanonicalRosterReceipt().isEmpty()) { + if (hasRoster(original)) { throw new IllegalArgumentException("CANONICAL_ROSTER_RETIREMENT_SNAPSHOT_REQUIRED"); } } else { - var roster = CanonicalGameplayRosterReferenceEvidence.receipt(original); + var roster = CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(original); if (!roster.getSnapshotUuid().equals(request.getSnapshotUuid()) || !roster.getSnapshotDigest().equals(request.getSnapshotDigest())) { throw new IllegalArgumentException("CANONICAL_ROSTER_RETIREMENT_SNAPSHOT_CONFLICT"); @@ -820,7 +922,22 @@ public Health health() { return new Health(row.get("oldest_blocking", Long.class), row.get("cleanup_lag", Long.class)); } + private static boolean hasRoster(GetCanonicalGameplayRosterReferenceResponse original) { + return !original.getCanonicalRosterReceipt().isEmpty() + || !original.getCanonicalPlayerCreatedRosterReceipt().isEmpty(); + } + + private static boolean isPlayerCreated(GetCanonicalGameplayRosterReferenceRequest request) { + return CanonicalGameplayRosterReferenceEvidence.target(request).getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED; + } + + private static String entryPolicy(GetCanonicalGameplayRosterReferenceRequest request) { + return isPlayerCreated(request) ? "PLAYER_CREATED" : "PRESEEDED_ONLY"; + } + private static byte[] targetBinding(GetCanonicalGameplayRosterReferenceRequest request) { + // Keep the complete typed created source identity in the shared namespace/account/target fence. return request.toBuilder().clearOperationUuid().clearSessionUuid().build().toByteArray(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java index b381b09f28..5fb6718b25 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java @@ -1,7 +1,11 @@ package net.firedevops.firemud.gamesession.service; import java.util.Objects; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; @@ -19,6 +23,7 @@ public final class CanonicalGameplayRosterReferenceOwner { private final CanonicalInitialAdmissionRepository admissionRepository; private final net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient recoveryClient; + private final GameSessionCharacterCreatePublicSourceService playerCreatedSourceReader; public CanonicalGameplayRosterReferenceOwner( CanonicalGameplayRosterReferenceRepository repository, @@ -28,12 +33,32 @@ public CanonicalGameplayRosterReferenceOwner( CanonicalInitialAdmissionRepository admissionRepository, net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient recoveryClient) { + this( + repository, + transactions, + sourceReader, + routeReader, + admissionRepository, + recoveryClient, + null); + } + + public CanonicalGameplayRosterReferenceOwner( + CanonicalGameplayRosterReferenceRepository repository, + TransactionOperations transactions, + CanonicalPublishedPlayerRouteReadService sourceReader, + CanonicalPlayerRouteReadService routeReader, + CanonicalInitialAdmissionRepository admissionRepository, + net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient + recoveryClient, + GameSessionCharacterCreatePublicSourceService playerCreatedSourceReader) { this.repository = Objects.requireNonNull(repository, "repository"); this.transactions = Objects.requireNonNull(transactions, "transactions"); this.sourceReader = Objects.requireNonNull(sourceReader, "sourceReader"); this.routeReader = Objects.requireNonNull(routeReader, "routeReader"); this.admissionRepository = Objects.requireNonNull(admissionRepository, "admissionRepository"); this.recoveryClient = Objects.requireNonNull(recoveryClient, "recoveryClient"); + this.playerCreatedSourceReader = playerCreatedSourceReader; } public net.firedevops.firemud.gamesession.v1 @@ -69,7 +94,8 @@ public GetCanonicalGameplayRosterReferenceResponse begin( if (retained.isPresent()) { var original = Objects.requireNonNull(transactions.execute(ignored -> repository.replay(request))); - if (original.getCanonicalRosterReceipt().isEmpty()) { + if (original.getCanonicalRosterReceipt().isEmpty() + && original.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { if (!original.getTerminalOutcome().isEmpty()) { throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_TERMINAL_UNISSUED"); } @@ -82,8 +108,7 @@ public GetCanonicalGameplayRosterReferenceResponse begin( } return original; } - var source = requireCurrentTarget(request); - var qualified = qualifiedSnapshot(source); + var qualified = requireCurrentTarget(request); return Objects.requireNonNull( transactions.execute( ignored -> { @@ -115,6 +140,22 @@ public GetCanonicalGameplayRosterReferenceResponse record( transactions.execute(ignored -> repository.record(request, receipt))); } + public GetCanonicalGameplayRosterReferenceResponse recordPlayerCreated( + GetCanonicalGameplayRosterReferenceRequest request, + CanonicalPlayerCreatedRosterResponse receipt) { + requireOutsideTransaction(); + return Objects.requireNonNull( + transactions.execute(ignored -> repository.recordPlayerCreated(request, receipt))); + } + + public void recordSelectedPlayerCreatedCharacter( + GetCanonicalGameplayRosterReferenceRequest request, + CanonicalSelectedPlayerCreatedCharacterResponse receipt) { + requireOutsideTransaction(); + transactions.executeWithoutResult( + ignored -> repository.recordSelectedPlayerCreatedCharacter(request, receipt)); + } + public void reserveSelectionInput( GetCanonicalGameplayRosterReferenceRequest request, net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput input) { @@ -232,8 +273,99 @@ private static void requireExactCurrentSnapshot( } } + private CanonicalInitialAdmissionRepository.CurrentOpenSnapshot requireCurrentTarget( + GetCanonicalGameplayRosterReferenceRequest request) { + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.requireRequest( + request); + var target = + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.target( + request); + if (target.getEntryPolicy() + == CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) { + return requireCurrentPlayerCreatedTarget(request, target); + } + return qualifiedSnapshot(requirePreseededCurrentTarget(request)); + } + + private CanonicalInitialAdmissionRepository.CurrentOpenSnapshot requireCurrentPlayerCreatedTarget( + GetCanonicalGameplayRosterReferenceRequest request, + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget target) { + if (playerCreatedSourceReader == null) { + throw new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "Canonical PLAYER_CREATED source reader is unavailable"); + } + var sourceRequest = + net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(request.getOperationUuid()) + .setTargetNamespace(request.getTargetNamespace()) + .setCanonicalTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setWorldSlug(target.getWorldSlug()) + .setRealmSlug(target.getRealmSlug()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceId(target.getGameInstanceUuid()) + .setCatalogRevision(target.getCatalogRevision()) + .setPointerVersion(target.getPointerVersion()) + .setExpectedCanonicalVersionId(target.getCanonicalVersionUuid()) + .setActiveWorldEpoch(target.getActiveWorldEpoch()) + .build(); + GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource source; + try { + source = playerCreatedSourceReader.resolvePlayerCreatedRosterSource(sourceRequest); + } catch ( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + failure) { + throw new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "Canonical PLAYER_CREATED source is unavailable", failure); + } catch (io.grpc.StatusRuntimeException failure) { + switch (failure.getStatus().getCode()) { + case FAILED_PRECONDITION -> { + var stale = + new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "CANONICAL_ROSTER_ORIGINAL_SOURCE_MISMATCH"); + stale.initCause(failure); + throw stale; + } + case UNAVAILABLE, DEADLINE_EXCEEDED -> + throw new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "Canonical PLAYER_CREATED source is unavailable", failure); + case INVALID_ARGUMENT -> + throw new CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException( + "Canonical PLAYER_CREATED source selectors are invalid", failure); + default -> throw failure; + } + } + if (source == null + || !request.getCanonicalTarget().equals(source.target().toByteString()) + || !request + .getCanonicalPlayerCreatedSourceIdentity() + .equals(source.sourceIdentity().toByteString()) + || source.route() == null + || !request.getTargetNamespace().equals(source.route().targetNamespace())) { + throw new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "CANONICAL_ROSTER_ORIGINAL_SOURCE_MISMATCH"); + } + var qualified = + admissionRepository.readCurrentOpenSnapshotForRealm( + request.getTargetNamespace(), + java.util.UUID.fromString(target.getTenantUuid()), + java.util.UUID.fromString(target.getRealmUuid())); + try { + requireExactCurrentSnapshot(source.route(), qualified); + } catch (IllegalStateException mismatch) { + var stale = + new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "CANONICAL_ROSTER_ORIGINAL_SOURCE_MISMATCH"); + stale.initCause(mismatch); + throw stale; + } + return qualified; + } + private net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - requireCurrentTarget(GetCanonicalGameplayRosterReferenceRequest request) { + requirePreseededCurrentTarget(GetCanonicalGameplayRosterReferenceRequest request) { var target = net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.target( request); 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 258a392cce..b3fd615132 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 @@ -7,17 +7,24 @@ import java.util.Optional; import java.util.UUID; import java.util.regex.Pattern; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedCharacter; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedRoster; 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.gamesession.repository.CanonicalGameplayRosterReferenceRepository.SelectionOutcome; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; 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. + * Non-admitting composition of the independently resolved policy and Entity's exact 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); @@ -26,22 +33,35 @@ public final class CanonicalGameplayRosterSelectionService { private final CanonicalPlayerRouteReadService routeReader; private final CanonicalPublishedPlayerRouteReadService publishedRouteReader; private final CanonicalGameplayRosterClient rosterClient; + private final GameSessionCharacterCreatePublicSourceService createdSourceReader; + private final CanonicalPlayerCreatedRosterClient createdRosterClient; public CanonicalGameplayRosterSelectionService( CanonicalPlayerRouteReadService routeReader, CanonicalPublishedPlayerRouteReadService publishedRouteReader, CanonicalGameplayRosterClient rosterClient) { + this(routeReader, publishedRouteReader, rosterClient, null, null); + } + + public CanonicalGameplayRosterSelectionService( + CanonicalPlayerRouteReadService routeReader, + CanonicalPublishedPlayerRouteReadService publishedRouteReader, + CanonicalGameplayRosterClient rosterClient, + GameSessionCharacterCreatePublicSourceService createdSourceReader, + CanonicalPlayerCreatedRosterClient createdRosterClient) { this.routeReader = Objects.requireNonNull(routeReader, "routeReader"); this.publishedRouteReader = Objects.requireNonNull(publishedRouteReader, "publishedRouteReader"); this.rosterClient = Objects.requireNonNull(rosterClient, "rosterClient"); + this.createdSourceReader = createdSourceReader; + this.createdRosterClient = createdRosterClient; } /** * Reads a route-bound roster, accepts only an optional one-based ordinal, and obtains Entity's - * 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. + * original policy-specific selected owner 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, @@ -62,6 +82,17 @@ public Result select( if (selectedTarget == null || !matchesContext(authenticatedContext, selectedTarget)) { return new Denied(Denial.ROUTE_MISMATCH); } + if ("PLAYER_CREATED".equals(selectedTarget.characterCreationPolicy())) { + return selectPlayerCreated( + authenticatedContext, + selector, + expectedMenuIdentity, + selectedTarget, + accountUuid.orElseThrow()); + } + if (!"PRESEEDED_ONLY".equals(selectedTarget.characterCreationPolicy())) { + return new Denied(Denial.UNSUPPORTED_ENTRY_POLICY); + } current = publishedRouteReader.readCurrent(selectedTarget); if (current == null || !matchesContext(authenticatedContext, current.route())) { return new Denied(Denial.ROUTE_MISMATCH); @@ -77,20 +108,28 @@ public Result select( expectedMenuIdentity, current, accountUuid.orElseThrow()); - net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository - .SelectionOutcome - outcome = null; - if (result instanceof SelectedOwnerReference) { - outcome = - net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository - .SelectionOutcome.SELECTED; + var outcome = completionOutcome(result); + if (outcome != null) { + try { + rosterClient.completeSelection(current, authenticatedContext, outcome); + } catch (RuntimeException unavailableOrRecoverable) { + return result instanceof Denied ? result : new Denied(Denial.ROSTER_UNAVAILABLE); + } + } + return result; + } + + private static SelectionOutcome completionOutcome(Result result) { + SelectionOutcome outcome = null; + if (result instanceof SelectedOwnerReference + || result instanceof SelectedPlayerCreatedOwnerReference) { + outcome = SelectionOutcome.SELECTED; } else if (result instanceof SelectionRequired) { - outcome = - net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository - .SelectionOutcome.MENU; + outcome = SelectionOutcome.MENU; } else if (result instanceof Denied denied && switch (denied.reason()) { case NO_PRESEEDED_ACTOR, + NO_PLAYER_CREATED_ACTOR, INVALID_SELECTOR, SELECTOR_OUT_OF_RANGE, MISSING_MENU_IDENTITY, @@ -99,13 +138,40 @@ && switch (denied.reason()) { true; default -> false; }) { - outcome = - net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository - .SelectionOutcome.DENIED; + outcome = SelectionOutcome.DENIED; + } + return outcome; + } + + private Result selectPlayerCreated( + PlayerExecutionContext context, + String selector, + SelectionMenuIdentity expectedMenu, + CanonicalPlayableTarget current, + UUID account) { + if (createdSourceReader == null || createdRosterClient == null) { + return new Denied(Denial.ROSTER_UNAVAILABLE); } + if (!"SHARED".equals(current.playableStateScope())) { + return new Denied(Denial.ROUTE_MISMATCH); + } + var request = createdSourceRequest(current, context.getRequestId()); + ResolvedPlayerCreatedRosterSource source; + try { + source = createdSourceReader.resolvePlayerCreatedRosterSource(request); + if (source == null + || !current.equals(source.route()) + || !matchesContext(context, source.route())) { + return new Denied(Denial.ROUTE_CHANGED); + } + } catch (RuntimeException invalidOrUnavailable) { + return new Denied(routeFailure(invalidOrUnavailable)); + } + var result = selectForCreated(context, selector, expectedMenu, source, request, account); + var outcome = completionOutcome(result); if (outcome != null) { try { - rosterClient.completeSelection(current, authenticatedContext, outcome); + createdRosterClient.completeSelection(source, context, outcome); } catch (RuntimeException unavailableOrRecoverable) { return result instanceof Denied ? result : new Denied(Denial.ROSTER_UNAVAILABLE); } @@ -113,6 +179,150 @@ && switch (denied.reason()) { return result; } + private Result selectForCreated( + PlayerExecutionContext context, + String selector, + SelectionMenuIdentity expectedMenu, + ResolvedPlayerCreatedRosterSource source, + ReadPlayerCreatedRosterSourceRequest sourceRequest, + UUID account) { + VerifiedPlayerCreatedRoster snapshot; + try { + createdRosterClient.reserveSelectionInput( + source, + context, + selector, + expectedMenu == null ? null : expectedMenu.snapshotUuid(), + expectedMenu == null ? null : expectedMenu.snapshotDigest()); + snapshot = createdRosterClient.listPlayerCreatedRoster(source, context); + } catch (StatusRuntimeException failure) { + return new Denied(rosterFailure(failure)); + } catch (RuntimeException invalidOrUnavailable) { + var failure = routeFailure(invalidOrUnavailable); + return new Denied( + failure == Denial.INVALID_ROUTE_PROOF ? Denial.INVALID_ROSTER_PROOF : failure); + } + var freshness = requireExactCurrentCreatedSource(source, sourceRequest); + if (freshness != null) { + return new Denied(freshness); + } + if (!matchesCreatedRoster(snapshot, source, context, account)) { + return new Denied(Denial.INVALID_ROSTER_PROOF); + } + if (selector != null && !selector.isBlank()) { + if (expectedMenu == null) { + return new Denied(Denial.MISSING_MENU_IDENTITY); + } + if (!expectedMenu.matches(snapshot)) { + return new Denied(Denial.STALE_MENU_IDENTITY); + } + } + var selection = CanonicalGameplayActorSelection.select(snapshot, selector); + if (selection instanceof CanonicalGameplayActorSelection.SelectionRequired required) { + return new SelectionRequired( + required.choices(), + new SelectionMenuIdentity(snapshot.snapshotUuid(), snapshot.snapshotDigest())); + } + if (selection instanceof CanonicalGameplayActorSelection.Denied denied) { + return new Denied(mapSelectionDenial(denied.reason())); + } + var selected = (CanonicalGameplayActorSelection.Selected) selection; + var selectedContext = + context.toBuilder().setCharacterId(selected.characterUuid().toString()).build(); + VerifiedPlayerCreatedCharacter reference; + try { + reference = createdRosterClient.readSelectedPlayerCreatedCharacter(snapshot, selectedContext); + } catch (StatusRuntimeException failure) { + return new Denied(assignmentFailure(failure, expectedMenu != null)); + } catch (RuntimeException invalidOrUnavailable) { + var failure = routeFailure(invalidOrUnavailable); + return new Denied( + failure == Denial.INVALID_ROUTE_PROOF ? Denial.INVALID_ASSIGNMENT_PROOF : failure); + } + if (reference == null + || reference.roster() != snapshot + || !reference.selectedCharacterUuid().equals(selected.characterUuid()) + || !reference.response().getCanonicalAccountUuid().equals(account.toString()) + || !reference.response().getRequestUuid().equals(context.getRequestId()) + || !reference.response().getTarget().equals(source.target()) + || !reference.response().getSourceIdentity().equals(source.sourceIdentity()) + || !reference + .response() + .getSnapshot() + .getSnapshotUuid() + .equals(snapshot.snapshotUuid().toString()) + || !reference + .response() + .getSnapshot() + .getSnapshotDigest() + .equals(snapshot.snapshotDigest())) { + return new Denied(Denial.INVALID_ASSIGNMENT_PROOF); + } + freshness = requireExactCurrentCreatedSource(source, sourceRequest); + if (freshness != null) { + return new Denied(freshness); + } + return new SelectedPlayerCreatedOwnerReference( + reference, selected.displayName(), selected.ordinal()); + } + + private static boolean matchesCreatedRoster( + VerifiedPlayerCreatedRoster snapshot, + ResolvedPlayerCreatedRosterSource source, + PlayerExecutionContext context, + UUID account) { + if (snapshot == null || snapshot.resolvedSource() == null) return false; + var original = + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .playerCreatedRequest( + UUID.fromString(context.getRequestId()), + account, + UUID.fromString(context.getSessionId()), + source.route().targetNamespace(), + source.target(), + source.sourceIdentity()); + return original.equals(snapshot.originalSelection()) + && account.equals(snapshot.canonicalAccountUuid()) + && source.route().equals(snapshot.resolvedSource().route()) + && source.target().equals(snapshot.target()) + && source.sourceIdentity().equals(snapshot.sourceIdentity()); + } + + private Denial requireExactCurrentCreatedSource( + ResolvedPlayerCreatedRosterSource expected, ReadPlayerCreatedRosterSourceRequest request) { + try { + var actual = createdSourceReader.resolvePlayerCreatedRosterSource(request); + return actual != null + && expected.route().equals(actual.route()) + && expected.target().equals(actual.target()) + && expected.sourceIdentity().equals(actual.sourceIdentity()) + ? null + : Denial.ROUTE_CHANGED; + } catch (RuntimeException invalidOrUnavailable) { + return routeFailure(invalidOrUnavailable); + } + } + + private static ReadPlayerCreatedRosterSourceRequest createdSourceRequest( + CanonicalPlayableTarget route, String requestId) { + return ReadPlayerCreatedRosterSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(requestId) + .setTargetNamespace(route.targetNamespace()) + .setCanonicalTenantId(route.canonicalTenantId().toString()) + .setRealmId(route.realmId().toString()) + .setWorldSlug(route.worldSlug()) + .setRealmSlug(route.realmSlug()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setPlayableStateScope(route.playableStateScope()) + .setCanonicalGameInstanceId(route.canonicalGameInstanceId().toString()) + .setCatalogRevision(route.catalogRevision()) + .setPointerVersion(route.pointerVersion()) + .setExpectedCanonicalVersionId(route.canonicalVersionId().toString()) + .setActiveWorldEpoch(route.activeWorldEpoch()) + .build(); + } + private Result selectForCurrent( PlayerExecutionContext authenticatedContext, String selector, @@ -209,6 +419,9 @@ private static Denial routeFailure(RuntimeException failure) { || failure instanceof CanonicalPublishedPlayerRouteReadService.StorageUnavailableException || failure instanceof CanonicalPublishedPlayerRouteReadService.GameDesignUnavailableException + || failure + instanceof + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException || failure instanceof StatusRuntimeException status && isTransient(status.getStatus())) { return Denial.ROUTE_UNAVAILABLE; } @@ -307,6 +520,7 @@ private static Denial mapSelectionDenial(CanonicalGameplayActorSelection.Denial return switch (reason) { case INVALID_SNAPSHOT -> Denial.INVALID_ROSTER_PROOF; case NO_PRESEEDED_ACTOR -> Denial.NO_PRESEEDED_ACTOR; + case NO_PLAYER_CREATED_ACTOR -> Denial.NO_PLAYER_CREATED_ACTOR; case INVALID_SELECTOR -> Denial.INVALID_SELECTOR; case SELECTOR_OUT_OF_RANGE -> Denial.SELECTOR_OUT_OF_RANGE; }; @@ -317,7 +531,11 @@ private static boolean hasAmbientTransaction() { || TransactionSynchronizationManager.isSynchronizationActive(); } - public sealed interface Result permits SelectedOwnerReference, SelectionRequired, Denied {} + public sealed interface Result + permits SelectedOwnerReference, + SelectedPlayerCreatedOwnerReference, + SelectionRequired, + Denied {} /** * Entity's original committed owner reference, still only source evidence for later revalidation. @@ -336,6 +554,17 @@ public record SelectedOwnerReference( } } + /** Complete original creation terminal for later owner revalidation; never actor admission. */ + public record SelectedPlayerCreatedOwnerReference( + VerifiedPlayerCreatedCharacter ownerReference, String displayName, int ordinal) + implements Result { + public SelectedPlayerCreatedOwnerReference { + Objects.requireNonNull(ownerReference, "ownerReference"); + Objects.requireNonNull(displayName, "displayName"); + if (ordinal < 1) throw new IllegalArgumentException("ordinal must be one-based"); + } + } + public record SelectionMenuIdentity(UUID snapshotUuid, String snapshotDigest) { public SelectionMenuIdentity { Objects.requireNonNull(snapshotUuid, "snapshotUuid"); @@ -345,6 +574,11 @@ public record SelectionMenuIdentity(UUID snapshotUuid, String snapshotDigest) { } } + private boolean matches(VerifiedPlayerCreatedRoster snapshot) { + return snapshotUuid.equals(snapshot.snapshotUuid()) + && snapshotDigest.equals(snapshot.snapshotDigest()); + } + private boolean matches(CanonicalGameplayRosterClient.PreseededRosterSnapshot snapshot) { return snapshotUuid.equals(snapshot.snapshotUuid()) && snapshotDigest.equals(snapshot.snapshotDigest()); @@ -376,6 +610,8 @@ public enum Denial { ROSTER_UNAVAILABLE, INVALID_ROSTER_PROOF, NO_PRESEEDED_ACTOR, + NO_PLAYER_CREATED_ACTOR, + UNSUPPORTED_ENTRY_POLICY, INVALID_SELECTOR, SELECTOR_OUT_OF_RANGE, MISSING_MENU_IDENTITY, diff --git a/services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql b/services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql new file mode 100644 index 0000000000..42eed610c2 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql @@ -0,0 +1,266 @@ +-- Distinct PLAYER_CREATED original receipts; published PRESEEDED_ONLY columns keep their bounds. +-- The owner sets entry_policy from its closed original request; SQL never mints source authority. +ALTER TABLE game_session_canonical_roster_selection + ADD COLUMN entry_policy VARCHAR(16) NOT NULL DEFAULT 'PRESEEDED_ONLY', + ADD COLUMN canonical_player_created_roster_receipt BYTEA + CHECK (octet_length(canonical_player_created_roster_receipt) BETWEEN 1 AND 67584), + ADD COLUMN canonical_selected_player_created_character_receipt BYTEA + CHECK (octet_length(canonical_selected_player_created_character_receipt) BETWEEN 1 AND 202375168); + +-- [jooq ignore start] +-- Replace only the two applied cross-column checks that assume a single roster column. Locate +-- their exact referenced column sets instead of depending on generated constraint names. +DO $$ +DECLARE + constraint_name TEXT; + replaced INTEGER := 0; +BEGIN + FOR constraint_name IN + SELECT c.conname FROM pg_constraint c + WHERE c.conrelid = 'game_session_canonical_roster_selection'::regclass AND c.contype = 'c' + AND (SELECT array_agg(a.attname::text ORDER BY a.attname) + FROM pg_attribute a WHERE a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)) + IN (ARRAY['canonical_roster_receipt','selected_character_uuid','selection_input']::text[], + ARRAY['canonical_roster_receipt','receipt_recorded_at']::text[]) + LOOP + EXECUTE format('ALTER TABLE game_session_canonical_roster_selection DROP CONSTRAINT %I', constraint_name); + replaced := replaced + 1; + END LOOP; + IF replaced <> 2 THEN RAISE EXCEPTION 'expected exact predecessor roster constraints'; END IF; +END; +$$; +-- [jooq ignore stop] + +ALTER TABLE game_session_canonical_roster_selection + ADD CONSTRAINT gs_roster_reference_policy_receipts CHECK ( + (entry_policy = 'PRESEEDED_ONLY' AND canonical_player_created_roster_receipt IS NULL + AND canonical_selected_player_created_character_receipt IS NULL) + OR (entry_policy = 'PLAYER_CREATED' AND canonical_roster_receipt IS NULL + AND canonical_selected_assignment_receipt IS NULL)), + ADD CONSTRAINT gs_roster_reference_selected_menu CHECK (selected_character_uuid IS NULL + OR (selection_input IS NOT NULL AND (canonical_roster_receipt IS NOT NULL + OR canonical_player_created_roster_receipt IS NOT NULL))), + ADD CONSTRAINT gs_roster_reference_created_selected_actor CHECK ( + canonical_selected_player_created_character_receipt IS NULL OR selected_character_uuid IS NOT NULL), + ADD CONSTRAINT gs_roster_reference_receipt_clock CHECK ( + (canonical_roster_receipt IS NOT NULL OR canonical_player_created_roster_receipt IS NOT NULL) + = (receipt_recorded_at IS NOT NULL)); + +-- [jooq ignore start] + + +CREATE OR REPLACE FUNCTION guard_game_session_canonical_roster_target_fence() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND OLD.fence_state = 'RETIRED' + AND OLD.retired_at + OLD.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() + AND NOT EXISTS (SELECT 1 FROM game_session_canonical_roster_selection s WHERE s.target_fence_uuid = OLD.target_fence_uuid) THEN + RETURN OLD; + END IF; + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'roster target fence tombstone remains required' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.fence_state <> 'ACTIVE' THEN + RAISE EXCEPTION 'roster target fence must begin active' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.target_fence_uuid, NEW.target_binding_digest, NEW.target_binding, NEW.owner_fence, + NEW.minimum_retention_millis, NEW.replay_horizon_millis) + IS DISTINCT FROM ROW(OLD.target_fence_uuid, OLD.target_binding_digest, OLD.target_binding, OLD.owner_fence, + OLD.minimum_retention_millis, OLD.replay_horizon_millis) + OR OLD.fence_state = 'RETIRED' + OR NEW.fence_state <> 'RETIRED' + OR EXISTS (SELECT 1 FROM game_session_canonical_roster_selection s + WHERE s.target_fence_uuid = OLD.target_fence_uuid + AND (s.terminal_at IS NULL + OR s.terminal_at + OLD.minimum_retention_millis * interval '1 millisecond' > clock_timestamp() + OR ((s.roster_read_started AND s.canonical_roster_receipt IS NULL AND s.canonical_player_created_roster_receipt IS NULL + OR s.selected_character_uuid IS NOT NULL AND s.canonical_selected_assignment_receipt IS NULL AND s.canonical_selected_player_created_character_receipt IS NULL) + AND NOT (s.recovery_uuid IS NOT NULL AND s.recovery_receipt IS NOT NULL AND s.terminal_outcome = 'DENIED')))) THEN + RAISE EXCEPTION 'roster target retirement requires closed references and owner-local horizons' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION guard_game_session_canonical_roster_selection() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND EXISTS (SELECT 1 FROM game_session_canonical_roster_target_fences f + WHERE f.target_fence_uuid = OLD.target_fence_uuid AND f.fence_state = 'RETIRED' + AND f.retired_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp()) THEN + RETURN OLD; + END IF; + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'roster original selection dependencies remain protected' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM game_session_canonical_roster_target_fences + WHERE target_fence_uuid = NEW.target_fence_uuid AND owner_fence = NEW.owner_fence + AND fence_state = 'ACTIVE' FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'roster target fence is sealed against new and recovered references' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_roster_receipt IS NOT NULL OR NEW.canonical_player_created_roster_receipt IS NOT NULL OR NEW.receipt_recorded_at IS NOT NULL + OR NEW.selection_input IS NOT NULL OR NEW.selected_character_uuid IS NOT NULL + OR NEW.canonical_selected_assignment_receipt IS NOT NULL OR NEW.canonical_selected_player_created_character_receipt IS NOT NULL OR NEW.roster_read_started + OR NEW.terminal_outcome IS NOT NULL OR NEW.recovery_uuid IS NOT NULL + OR NEW.recovery_started_at IS NOT NULL OR NEW.recovery_receipt IS NOT NULL THEN + RAISE EXCEPTION 'roster selection must reserve before owner read' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.recovery_uuid IS NULL AND NEW.recovery_uuid IS NOT NULL THEN + IF OLD.terminal_outcome IS NOT NULL OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_roster_target_fences f + WHERE f.target_fence_uuid = OLD.target_fence_uuid + AND OLD.recorded_at + f.replay_horizon_millis * interval '1 millisecond' <= clock_timestamp()) + OR ROW(NEW.selection_input, NEW.selected_character_uuid, NEW.canonical_selected_assignment_receipt, NEW.canonical_selected_player_created_character_receipt, + NEW.roster_read_started, NEW.canonical_roster_receipt, NEW.canonical_player_created_roster_receipt, NEW.receipt_recorded_at, NEW.terminal_outcome, NEW.terminal_at, NEW.recovery_receipt) + IS DISTINCT FROM ROW(OLD.selection_input, OLD.selected_character_uuid, OLD.canonical_selected_assignment_receipt, OLD.canonical_selected_player_created_character_receipt, + OLD.roster_read_started, OLD.canonical_roster_receipt, OLD.canonical_player_created_roster_receipt, OLD.receipt_recorded_at, OLD.terminal_outcome, OLD.terminal_at, OLD.recovery_receipt) THEN + RAISE EXCEPTION 'roster recovery must fence the unchanged original after its stored replay horizon' USING ERRCODE = '23514'; + END IF; + END IF; + IF (OLD.recovery_uuid IS NOT NULL AND ( + ROW(NEW.recovery_uuid, NEW.recovery_started_at, NEW.selection_input, NEW.selected_character_uuid, + NEW.canonical_selected_assignment_receipt, NEW.canonical_selected_player_created_character_receipt, NEW.roster_read_started) + IS DISTINCT FROM ROW(OLD.recovery_uuid, OLD.recovery_started_at, OLD.selection_input, OLD.selected_character_uuid, + OLD.canonical_selected_assignment_receipt, OLD.canonical_selected_player_created_character_receipt, OLD.roster_read_started) + OR (NEW IS DISTINCT FROM OLD AND (NEW.recovery_receipt IS NULL OR NEW.terminal_outcome IS DISTINCT FROM 'DENIED')))) + OR (OLD.recovery_receipt IS NOT NULL AND NEW.recovery_receipt IS DISTINCT FROM OLD.recovery_receipt) + OR (OLD.recovery_uuid IS NULL AND NEW.recovery_uuid IS NULL + AND ROW(NEW.recovery_started_at, NEW.recovery_receipt) IS DISTINCT FROM ROW(OLD.recovery_started_at, OLD.recovery_receipt)) THEN + RAISE EXCEPTION 'roster recovery fence and positive closure cannot be replaced' USING ERRCODE = '23514'; + END IF; + IF ROW(NEW.operation_uuid, NEW.original_request, NEW.owner_fence, NEW.recorded_at, NEW.target_fence_uuid, NEW.entry_policy) + IS DISTINCT FROM ROW(OLD.operation_uuid, OLD.original_request, OLD.owner_fence, OLD.recorded_at, OLD.target_fence_uuid, OLD.entry_policy) + OR (OLD.roster_read_started AND NOT NEW.roster_read_started) + OR (OLD.terminal_outcome IS NOT NULL + AND ROW(NEW.terminal_outcome, NEW.terminal_at) IS DISTINCT FROM ROW(OLD.terminal_outcome, OLD.terminal_at)) + OR (OLD.terminal_outcome IS NOT NULL AND NEW IS DISTINCT FROM OLD) + OR (OLD.selection_input IS NOT NULL AND NEW.selection_input IS DISTINCT FROM OLD.selection_input) + OR (OLD.selection_input IS NULL AND (OLD.canonical_roster_receipt IS NOT NULL OR OLD.canonical_player_created_roster_receipt IS NOT NULL) AND NEW.selection_input IS NOT NULL) + OR (OLD.selected_character_uuid IS NOT NULL AND NEW.selected_character_uuid IS DISTINCT FROM OLD.selected_character_uuid) + OR (OLD.canonical_selected_assignment_receipt IS NOT NULL + AND NEW.canonical_selected_assignment_receipt IS DISTINCT FROM OLD.canonical_selected_assignment_receipt) + OR (OLD.canonical_selected_player_created_character_receipt IS NOT NULL + AND NEW.canonical_selected_player_created_character_receipt IS DISTINCT FROM OLD.canonical_selected_player_created_character_receipt) + OR (OLD.canonical_player_created_roster_receipt IS NOT NULL + AND ROW(NEW.canonical_player_created_roster_receipt, NEW.receipt_recorded_at) + IS DISTINCT FROM ROW(OLD.canonical_player_created_roster_receipt, OLD.receipt_recorded_at)) + OR (OLD.canonical_roster_receipt IS NOT NULL + AND ROW(NEW.canonical_roster_receipt, NEW.receipt_recorded_at) + IS DISTINCT FROM ROW(OLD.canonical_roster_receipt, OLD.receipt_recorded_at)) THEN + RAISE EXCEPTION 'original roster selection cannot be replaced or reopened' USING ERRCODE = '23514'; + END IF; + IF OLD.terminal_outcome IS NULL AND NEW.terminal_outcome IS NOT NULL + AND NOT (NEW.recovery_uuid IS NOT NULL AND NEW.recovery_receipt IS NOT NULL AND NEW.terminal_outcome = 'DENIED') + AND NOT (NEW.terminal_outcome = 'DENIED' AND NOT NEW.roster_read_started + AND NEW.canonical_roster_receipt IS NULL AND NEW.canonical_player_created_roster_receipt IS NULL + AND NEW.selected_character_uuid IS NULL AND NEW.recovery_uuid IS NULL) + AND (NEW.selection_input IS NULL + OR (NEW.roster_read_started AND NEW.canonical_roster_receipt IS NULL AND NEW.canonical_player_created_roster_receipt IS NULL) + OR (NEW.selected_character_uuid IS NOT NULL AND NEW.canonical_selected_assignment_receipt IS NULL AND NEW.canonical_selected_player_created_character_receipt IS NULL) + OR (NEW.terminal_outcome = 'SELECTED' AND NEW.canonical_selected_assignment_receipt IS NULL AND NEW.canonical_selected_player_created_character_receipt IS NULL) + OR (NEW.terminal_outcome = 'MENU' AND (NEW.selected_character_uuid IS NOT NULL + OR (NEW.canonical_roster_receipt IS NULL AND NEW.canonical_player_created_roster_receipt IS NULL)))) THEN + RAISE EXCEPTION 'roster terminal outcome requires its exact policy receipts or positive recovery' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION freeze_game_session_roster_retirement_inventory() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO game_session_canonical_roster_retirement_transfers + (operation_uuid, original_request, target_fence_uuid, retirement_uuid, minimum_retention_millis) + SELECT s.operation_uuid, s.original_request, NEW.target_fence_uuid, NEW.retirement_uuid, NEW.minimum_retention_millis + FROM game_session_canonical_roster_selection s + WHERE s.target_fence_uuid = NEW.target_fence_uuid + AND (s.roster_read_started OR s.canonical_roster_receipt IS NOT NULL OR s.canonical_player_created_roster_receipt IS NOT NULL OR s.recovery_receipt IS NOT NULL); + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION gs_roster_retirement_observations_complete(fence UUID) +RETURNS BOOLEAN LANGUAGE SQL AS $$ + SELECT NOT EXISTS ( + SELECT 1 FROM game_session_canonical_roster_selection s + JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) + LEFT JOIN game_session_canonical_roster_retirement_transfers t + ON t.operation_uuid = s.operation_uuid AND t.original_request = s.original_request + AND t.target_fence_uuid = f.target_fence_uuid AND t.retirement_uuid = f.retirement_uuid + AND t.minimum_retention_millis = f.minimum_retention_millis + WHERE s.target_fence_uuid = fence + AND (s.roster_read_started OR s.canonical_roster_receipt IS NOT NULL OR s.canonical_player_created_roster_receipt IS NOT NULL OR s.recovery_receipt IS NOT NULL) + AND t.acknowledgement_uuid IS NULL) + AND NOT EXISTS (SELECT 1 FROM game_session_canonical_roster_retirement_transfers t + WHERE t.target_fence_uuid = fence AND t.acknowledgement_uuid IS NULL); +$$; + +CREATE OR REPLACE FUNCTION guard_game_session_roster_retirement_transfer() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'TRUNCATE' THEN + RAISE EXCEPTION 'roster retirement transfers remain protected' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'DELETE' THEN + IF OLD.confirmed_at IS NULL OR OLD.target_purged_at IS NULL + OR GREATEST(OLD.confirmed_at, OLD.target_purged_at) + + OLD.effective_minimum_millis * interval '1 millisecond' > clock_timestamp() + OR EXISTS (SELECT 1 FROM game_session_canonical_roster_target_fences f WHERE f.target_fence_uuid = OLD.target_fence_uuid) + OR EXISTS (SELECT 1 FROM game_session_canonical_roster_selection s WHERE s.operation_uuid = OLD.operation_uuid OR s.target_fence_uuid = OLD.target_fence_uuid) THEN + RAISE EXCEPTION 'roster retirement receipt confirmation and horizons required' USING ERRCODE = '23514'; + END IF; + RETURN OLD; + END IF; + IF TG_OP = 'INSERT' THEN + NEW.recorded_at := clock_timestamp(); + IF NEW.acknowledgement_uuid IS NOT NULL OR NEW.confirmed_at IS NOT NULL OR NEW.target_purged_at IS NOT NULL + OR NOT EXISTS (SELECT 1 FROM game_session_canonical_roster_selection s + JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) + WHERE s.operation_uuid = NEW.operation_uuid AND s.original_request = NEW.original_request + AND f.target_fence_uuid = NEW.target_fence_uuid AND f.retirement_uuid = NEW.retirement_uuid + AND f.minimum_retention_millis = NEW.minimum_retention_millis AND f.fence_state = 'RETIRED' + AND (s.roster_read_started OR s.canonical_roster_receipt IS NOT NULL OR s.canonical_player_created_roster_receipt IS NOT NULL OR s.recovery_receipt IS NOT NULL)) THEN + RAISE EXCEPTION 'exact retired original inventory required' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.operation_uuid, NEW.original_request, NEW.target_fence_uuid, NEW.retirement_uuid, NEW.minimum_retention_millis, NEW.recorded_at) + IS DISTINCT FROM ROW(OLD.operation_uuid, OLD.original_request, OLD.target_fence_uuid, OLD.retirement_uuid, OLD.minimum_retention_millis, OLD.recorded_at) + OR (OLD.acknowledgement_uuid IS NOT NULL AND ROW(NEW.acknowledgement_uuid, NEW.request_digest, NEW.observation_uuid, + NEW.admission_uuid, NEW.snapshot_uuid, NEW.snapshot_digest, NEW.entity_principal, NEW.effective_minimum_millis, NEW.received_at) + IS DISTINCT FROM ROW(OLD.acknowledgement_uuid, OLD.request_digest, OLD.observation_uuid, + OLD.admission_uuid, OLD.snapshot_uuid, OLD.snapshot_digest, OLD.entity_principal, OLD.effective_minimum_millis, OLD.received_at)) + OR (OLD.confirmed_at IS NOT NULL AND NEW.confirmed_at IS DISTINCT FROM OLD.confirmed_at) + OR (OLD.target_purged_at IS NOT NULL AND NEW.target_purged_at IS DISTINCT FROM OLD.target_purged_at) THEN + RAISE EXCEPTION 'roster retirement receipt identity is immutable' USING ERRCODE = '23514'; + END IF; + IF OLD.target_purged_at IS NULL AND NEW.target_purged_at IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM game_session_canonical_roster_target_fences f WHERE f.target_fence_uuid = OLD.target_fence_uuid + AND f.fence_state = 'RETIRED' AND f.retired_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() + AND gs_roster_retirement_observations_complete(f.target_fence_uuid)) THEN + RAISE EXCEPTION 'all exact observations and stored target horizon required' USING ERRCODE = '23514'; + END IF; + IF OLD.acknowledgement_uuid IS NULL AND NEW.acknowledgement_uuid IS NOT NULL THEN + NEW.received_at := clock_timestamp(); + END IF; + IF OLD.confirmed_at IS NULL AND NEW.confirmed_at IS NOT NULL THEN + NEW.confirmed_at := clock_timestamp(); + END IF; + IF OLD.target_purged_at IS NULL AND NEW.target_purged_at IS NOT NULL THEN + NEW.target_purged_at := clock_timestamp(); + END IF; + RETURN NEW; +END; +$$; + +-- ACK envelopes keep Common's policy-specific 128 KiB / 195 MiB bounds and bounded +-- confirmation overhead. This compact table retains the exact request hash, not a truncated proof. +-- Existing fence/selection deletion and transfer-confirmation/truncation guards remain installed. +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index 15a5803d97..a3cae68689 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -13,11 +13,14 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterRecoveryEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRecoveryResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient.VerifiedRecovery; @@ -25,6 +28,7 @@ import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationResponse; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; @@ -80,6 +84,11 @@ void upgradeActualCanonicalHistory() { .containsExactlyElementsOf(beforeObservation); assertThat(history().get(history().size() - 1)) .contains("1017", "V1017__canonical_roster_retirement_observation.sql"); + var beforeCreated = history(); + migrate("1020"); + assertThat(history().subList(0, beforeCreated.size())).containsExactlyElementsOf(beforeCreated); + assertThat(history()).hasSize(beforeCreated.size() + 1); + assertThat(history().getLast()).contains("1020", "V1020__player_created_roster_reference.sql"); transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); repository = new CanonicalGameplayRosterReferenceRepository( @@ -1764,6 +1773,656 @@ private static CanonicalGameplayRosterRetirementAcknowledgementRequest acknowled return CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(request.build()); } + @Test + void createdEmptyMenuReplaysExactTypedReceiptWithoutInventingASelection() throws Exception { + repository = repository(policy(60000L, 60000L, 60000L)); + var fixture = createdFixture(false); + var original = fixture.original(); + transaction.executeWithoutResult( + ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, fixture.roster()); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); + }); + var recorded = repository.read(original); + var retained = createdRow(original); + assertThat( + CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(recorded) + .getRoster() + .getActorsList()) + .isEmpty(); + assertThat(recorded.getSelectedCharacterUuid()).isEmpty(); + assertThat(recorded.getCanonicalRosterReceipt()).isEmpty(); + assertThat( + transaction.execute( + ignored -> repository.replay(original))) + .isEqualTo(recorded); + assertThat( + transaction.execute( + ignored -> repository.recordPlayerCreated(original, fixture.roster()))) + .isEqualTo(recorded); + assertThat(createdRow(original)).isEqualTo(retained); + assertThatThrownBy( + () -> + transaction.execute( + ignored -> repository.selectOriginal(original, UUID.randomUUID()))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void createdOneActorAndCompleteSelectedTerminalReplayWithExactBytesAndPolicyIsolation() + throws Exception { + repository = repository(policy(60000L, 60000L, 60000L)); + var fixture = createdFixture(true); + var original = fixture.original(); + transaction.executeWithoutResult( + ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, fixture.roster()); + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); + }); + var selected = repository.read(original); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + selected)) + .isEqualTo(fixture.selected()); + assertThat(selected.getCanonicalSelectedPlayerCreatedCharacterReceipt()) + .isEqualTo(fixture.selected().toByteString()); + assertThat(selected.getCanonicalSelectedAssignmentReceipt()).isEmpty(); + var retained = createdRow(original); + transaction.executeWithoutResult( + ignored -> repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected())); + assertThat( + transaction.execute( + ignored -> repository.replay(original))) + .isEqualTo(selected); + assertThat(createdRow(original)).isEqualTo(retained); + assertThatThrownBy( + () -> + transaction.execute( + ignored -> repository.record(original, fixture.roster().getRoster()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> + repository.recordSelectedAssignment( + original, + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSelectedAssignmentResponse + .getDefaultInstance()))) + .isInstanceOf(IllegalArgumentException.class); + var changed = + fixture.selected().toBuilder() + .setTerminal( + fixture.selected().getTerminal().toBuilder() + .setTerminalId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> repository.recordSelectedPlayerCreatedCharacter(original, changed))) + .hasMessageContaining("CREATED_RECEIPT_CONFLICT"); + assertThat(createdRow(original)).isEqualTo(retained); + } + + @Test + void createdSourceIdentityOwnsItsFenceAndSqlRefusesMixedMutableAndIncompleteReceipts() + throws Exception { + repository = repository(policy(60000L, 60000L, 60000L)); + var fixture = createdFixture(true); + var original = fixture.original(); + transaction.executeWithoutResult( + ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.recordPlayerCreated(original, fixture.roster()); + }); + var initial = repository.read(original); + var alteredRoster = + fixture.roster().toBuilder() + .setRoster( + fixture.roster().getRoster().toBuilder() + .setSnapshotUuid(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> + transaction.execute( + ignored -> repository.recordPlayerCreated(original, alteredRoster))) + .hasMessageContaining("RECEIPT_CONFLICT"); + var source = CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity(original); + var changedSource = + original.toBuilder() + .setCanonicalPlayerCreatedSourceIdentity( + source.toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .build() + .toByteString()) + .build(); + assertThatThrownBy(() -> transaction.execute(ignored -> repository.begin(changedSource))) + .hasMessageContaining("REQUEST_CONFLICT"); + assertThat( + dsl.fetchSingle("SELECT count(*) FROM game_session_canonical_roster_target_fences") + .get(0, Long.class)) + .isEqualTo(1L); + var otherOperation = + changedSource.toBuilder().setOperationUuid(UUID.randomUUID().toString()).build(); + var other = transaction.execute(ignored -> repository.begin(otherOperation)); + assertThat(other.getTargetFenceUuid()).isNotEqualTo(initial.getTargetFenceUuid()); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET entry_policy='PRESEEDED_ONLY' WHERE operation_uuid=?", + UUID.fromString(original.getOperationUuid()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET canonical_roster_receipt=? WHERE operation_uuid=?", + new byte[] {1}, + UUID.fromString(original.getOperationUuid()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET canonical_player_created_roster_receipt=? WHERE operation_uuid=?", + alteredRoster.toByteArray(), + UUID.fromString(original.getOperationUuid()))) + .isInstanceOf(DataAccessException.class); + transaction.execute( + ignored -> + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid()))); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> + repository.completeSelection( + original, + CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED))) + .hasMessageContaining("RECOVERY_REQUIRED"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET terminal_outcome='SELECTED', terminal_at=clock_timestamp() WHERE operation_uuid=?", + UUID.fromString(original.getOperationUuid()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> dsl.execute("TRUNCATE game_session_canonical_roster_selection CASCADE")) + .isInstanceOf(DataAccessException.class); + var definitions = + dsl.fetch( + "SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='game_session_canonical_roster_selection'::regclass") + .getValues(0, String.class); + assertThat(definitions) + .anyMatch(value -> value.contains("202375168")) + .anyMatch(value -> value.contains("67584")) + .anyMatch(value -> value.contains("65536")) + .anyMatch(value -> value.contains("8192")); + assertThat(repository.read(original).getTerminalOutcome()).isEmpty(); + } + + @Test + void createdRecoveryClosesMissingSelectedReceiptAndRequiresEveryExactEntityAck() + throws Exception { + var fixture = createdFixture(true); + var original = fixture.original(); + transaction.executeWithoutResult( + ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, fixture.roster()); + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + }); + Thread.sleep(5L); + var recovery = + transaction + .execute(ignored -> repository.beginRecoveries(original, current(original))) + .getFirst(); + var owner = repository.read(original); + var response = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + recovery, + UUID.randomUUID(), + owner.getOwnerFence(), + UUID.fromString(owner.getTargetFenceUuid()), + fixture.roster()); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> + repository.recordSelectedPlayerCreatedCharacter( + original, fixture.selected()))) + .hasMessageContaining("RECOVERY_FENCED"); + transaction.executeWithoutResult( + ignored -> repository.finishRecovery(verifiedRecovery(recovery, response))); + var closed = repository.read(original); + assertThat(closed.getTerminalOutcome()).isEqualTo("DENIED"); + assertThat(closed.getCanonicalSelectedPlayerCreatedCharacterReceipt()).isEmpty(); + assertThat(closed.getCanonicalPlayerCreatedRosterReceipt()) + .isEqualTo(fixture.roster().toByteString()); + assertThat(closed.getSelectedCharacterUuid()) + .isEqualTo(fixture.selected().getSelectedCharacterUuid()); + Thread.sleep(5L); + assertThat( + transaction.execute( + ignored -> repository.sealTargetRetirement(original, current(original)))) + .isTrue(); + var proof = repository.read(original); + var candidate = + new CanonicalGameplayRosterReferenceRepository.TargetCandidate( + UUID.fromString(proof.getTargetFenceUuid()), original, "RETIRED"); + Thread.sleep(5L); + assertThat(transaction.execute(ignored -> repository.purgeRetiredTarget(candidate))) + .isFalse(); + var acknowledgement = createdAcknowledgement(original, proof, response.getAdmissionUuid()); + assertThatThrownBy( + () -> + transaction.execute( + ignored -> + repository.acknowledgeRetirement( + acknowledgement.toBuilder() + .setAdmissionUuid(UUID.randomUUID().toString()) + .build(), + createdPrincipal(original)))) + .hasMessageContaining("ADMISSION_CONFLICT"); + var ack = + transaction.execute( + ignored -> + repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original))); + assertThat(transaction.execute(ignored -> repository.purgeRetiredTarget(candidate))) + .isTrue(); + assertThat( + transaction.execute( + ignored -> + repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original)))) + .isEqualTo(ack); + } + + @Test + void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterReceipt() + throws Exception { + repository = new CanonicalGameplayRosterReferenceRepository(dsl, policy(5000L, 5000L, 5000L)); + var fixture = createdFixture(false); + var original = fixture.original(); + transaction.executeWithoutResult( + ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + }); + Thread.sleep(5500L); + var recovery = + transaction + .execute(ignored -> repository.beginRecoveries(original, current(original))) + .getFirst(); + var owner = repository.read(original); + var response = + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + recovery, + UUID.randomUUID(), + owner.getOwnerFence(), + UUID.fromString(owner.getTargetFenceUuid()), + null); + transaction.executeWithoutResult( + ignored -> repository.finishRecovery(verifiedRecovery(recovery, response))); + var closed = repository.read(original); + assertThat(closed.getTerminalOutcome()).isEqualTo("DENIED"); + assertThat(closed.getRecoveryUuid()).isEqualTo(recovery.getRecoveryUuid()); + assertThat(closed.getCanonicalRosterReceipt()).isEmpty(); + assertThat(closed.getCanonicalPlayerCreatedRosterReceipt()).isEmpty(); + assertThatThrownBy( + () -> + transaction.execute( + ignored -> repository.recordPlayerCreated(original, fixture.roster()))) + .hasMessageContaining("RECOVERY_FENCED"); + Thread.sleep(5500L); + assertThat( + transaction.execute( + ignored -> repository.sealTargetRetirement(original, current(original)))) + .isTrue(); + var proof = repository.read(original); + var acknowledgement = createdAcknowledgement(original, proof, response.getAdmissionUuid()); + assertThat(acknowledgement.getSnapshotUuid()).isEmpty(); + transaction.execute( + ignored -> repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original))); + Thread.sleep(5500L); + var candidate = + new CanonicalGameplayRosterReferenceRepository.TargetCandidate( + UUID.fromString(proof.getTargetFenceUuid()), original, "RETIRED"); + assertThat(transaction.execute(ignored -> repository.purgeRetiredTarget(candidate))) + .isTrue(); + } + + @Test + void completeCreatedSelectedRetirementFreezesInventoryEvenWithoutDispatchFlag() throws Exception { + var fixture = createdFixture(true); + var original = fixture.original(); + transaction.executeWithoutResult( + ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.recordPlayerCreated(original, fixture.roster()); + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); + }); + Thread.sleep(5L); + assertThat( + transaction.execute( + ignored -> repository.sealTargetRetirement(original, current(original)))) + .isTrue(); + var proof = repository.read(original); + assertThat(proof.getCanonicalSelectedPlayerCreatedCharacterReceipt()) + .isEqualTo(fixture.selected().toByteString()); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM game_session_canonical_roster_retirement_transfers") + .get(0, Long.class)) + .isEqualTo(1L); + assertThatThrownBy(() -> dsl.execute("DELETE FROM game_session_canonical_roster_selection")) + .isInstanceOf(DataAccessException.class); + var request = createdAcknowledgement(original, proof, UUID.randomUUID().toString()); + var ack = + transaction.execute( + ignored -> repository.acknowledgeRetirement(request, createdPrincipal(original))); + Thread.sleep(5L); + var candidate = + new CanonicalGameplayRosterReferenceRepository.TargetCandidate( + UUID.fromString(proof.getTargetFenceUuid()), original, "RETIRED"); + assertThat(transaction.execute(ignored -> repository.purgeRetiredTarget(candidate))) + .isTrue(); + assertThat( + transaction.execute( + ignored -> repository.acknowledgeRetirement(request, createdPrincipal(original)))) + .isEqualTo(ack); + } + + @Test + void actual1017To1020UpgradePreservesPriorHistoryOriginalBytesAndXmin() throws Exception { + String previousSchema = "gs_created_upgrade_" + UUID.randomUUID().toString().replace("-", ""); + var previousSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + previousSource.setSchema(previousSchema); + var previous = DSL.using(previousSource, SQLDialect.POSTGRES); + try { + migrate(previousSource, previousSchema, "1017"); + var original = request(); + var roster = receipt(original); + var fence = UUID.randomUUID(); + var binding = + original.toBuilder().clearOperationUuid().clearSessionUuid().build().toByteArray(); + String digest = + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(binding)); + // Controlled predecessor writer through all installed guards; no current owner RPC or Human + // admission. + previous.execute( + "INSERT INTO game_session_canonical_roster_target_fences(target_fence_uuid,target_binding_digest,target_binding,minimum_retention_millis,replay_horizon_millis) VALUES(?,?,?,60000,60000)", + fence, + digest, + binding); + previous.execute( + "INSERT INTO game_session_canonical_roster_selection(operation_uuid,original_request,target_fence_uuid) VALUES(?,?,?)", + UUID.fromString(original.getOperationUuid()), + original.toByteArray(), + fence); + previous.execute( + "UPDATE game_session_canonical_roster_selection SET canonical_roster_receipt=?,receipt_recorded_at=clock_timestamp() WHERE operation_uuid=?", + roster.toByteArray(), + UUID.fromString(original.getOperationUuid())); + var before = + previous.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + String retained = + previous + .fetchSingle( + "SELECT encode(original_request,'hex') AS original_request_hex,encode(canonical_roster_receipt,'hex') AS roster_receipt_hex,recorded_at,receipt_recorded_at,xmin::text AS row_version FROM game_session_canonical_roster_selection") + .intoMap() + .toString(); + var upgraded = migrate(previousSource, previousSchema, "1020"); + assertThat(upgraded.getConfiguration().isOutOfOrder()).isFalse(); + assertThat(upgraded.info().applied()) + .allSatisfy( + info -> + assertThat(info.getState()) + .isNotEqualTo(org.flywaydb.core.api.MigrationState.OUT_OF_ORDER)); + var after = + previous.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + assertThat(after.subList(0, before.size())).containsExactlyElementsOf(before); + assertThat(after).hasSize(before.size() + 1); + assertThat(after.getLast().get("version")).isEqualTo("1020"); + assertThat( + previous + .fetchSingle( + "SELECT encode(original_request,'hex') AS original_request_hex,encode(canonical_roster_receipt,'hex') AS roster_receipt_hex,recorded_at,receipt_recorded_at,xmin::text AS row_version FROM game_session_canonical_roster_selection") + .intoMap() + .toString()) + .isEqualTo(retained); + assertThat( + previous + .fetchSingle( + "SELECT entry_policy,canonical_player_created_roster_receipt,canonical_selected_player_created_character_receipt FROM game_session_canonical_roster_selection") + .get("entry_policy", String.class)) + .isEqualTo("PRESEEDED_ONLY"); + var upgradedRepository = + new CanonicalGameplayRosterReferenceRepository(previous, policy(60000L, 60000L, 60000L)); + assertThat(upgradedRepository.read(original).getCanonicalRosterReceipt()) + .isEqualTo(roster.toByteString()); + } finally { + previous.execute("DROP SCHEMA IF EXISTS " + previousSchema + " CASCADE"); + } + } + + private String createdRow(GetCanonicalGameplayRosterReferenceRequest original) { + return dsl.fetchSingle( + "SELECT row_to_json(s)::text, xmin::text FROM game_session_canonical_roster_selection s WHERE operation_uuid=?", + UUID.fromString(original.getOperationUuid())) + .intoMap() + .toString(); + } + + private static String createdPrincipal(GetCanonicalGameplayRosterReferenceRequest original) { + return "spiffe://firemud/ns/" + original.getTargetNamespace() + "/sa/entity-management-service"; + } + + private static CanonicalGameplayRosterRetirementAcknowledgementRequest createdAcknowledgement( + GetCanonicalGameplayRosterReferenceRequest original, + GetCanonicalGameplayRosterReferenceResponse proof, + String admission) { + var request = + CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(original) + .setObservedRetirement(proof) + .setObservationUuid(UUID.randomUUID().toString()) + .setAdmissionUuid(admission) + .setMinimumRetentionMillis(1L); + if (!proof.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + var roster = CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(proof); + request + .setSnapshotUuid(roster.getSnapshotUuid()) + .setSnapshotDigest(roster.getSnapshotDigest()); + } + return request.build(); + } + + private record CreatedFixture( + GetCanonicalGameplayRosterReferenceRequest original, + CanonicalPlayerCreatedRosterResponse roster, + CanonicalSelectedPlayerCreatedCharacterResponse selected) {} + + private static CreatedFixture createdFixture(boolean oneActor) throws Exception { + Path root = Path.of("").toAbsolutePath(); + while (root != null && !java.nio.file.Files.exists(root.resolve("settings.gradle.kts"))) + root = root.getParent(); + if (root == null) + throw new IllegalStateException("Controlled CHARACTER_CREATE fixture unavailable"); + byte[] bytes = + java.nio.file.Files.readString( + root.resolve( + "services/account-service/src/testFixtures/resources/charactercreate/public-action.json")) + .strip() + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + var action = + net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec.decode(bytes); + var authored = action.mutation().authoredSource(); + var descriptor = + net.firedevops.firemud.common.publication.PlayerCreationDescriptor.parse( + authored.descriptor().canonicalJson()); + var source = + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity + .newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(authored.bindingId()) + .setAuthoredBindingDigest(authored.bindingDigest()) + .build(); + var target = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(action.scope().tenantId()) + .setRealmUuid(action.target().realmId()) + .setWorldSlug(action.target().worldSlug()) + .setRealmSlug(action.target().realmSlug()) + .setGameInstanceUuid(action.target().gameInstanceId()) + .setCanonicalVersionUuid(action.target().versionId()) + .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) + .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) + .setActiveWorldEpoch(Long.parseLong(action.expectedVersion().activeLifecycleEpoch())) + .setPublishedPolicyDigest(authored.policy().contentDigest().substring(7)) + .setPublishedReleaseBundleRef("controlled-created-release") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .build(); + var original = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.randomUUID(), + UUID.fromString(action.target().accountId()), + UUID.randomUUID(), + action.scope().targetNamespace(), + target, + source); + String character = UUID.randomUUID().toString(); + var actors = + oneActor + ? List.of( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(character) + .setDisplayName("Persisted fixture actor") + .setActorKind( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind + .CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()) + : List.of(); + String snapshot = UUID.randomUUID().toString(); + String snapshotDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + original.getCanonicalAccountUuid(), target, source, actors); + var roster = + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(source) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setTarget(target) + .setSnapshotUuid(snapshot) + .setSnapshotDigest(snapshotDigest) + .addAllActors(actors)) + .build(); + String creationOperation = UUID.randomUUID().toString(); + String mutationDigest = + net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec.mutationDigest( + action); + var creationRequest = + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(creationOperation) + .setMutationDigest(mutationDigest) + .build(); + var account = + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(creationOperation) + .setMutationDigest(mutationDigest) + .setCreateCharacterRequestId(UUID.randomUUID().toString()) + .setConnectScopeId("controlled-create-scope") + .setAuthenticatedAccountId(action.target().accountId()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(com.google.protobuf.ByteString.copyFrom(bytes)) + .setOriginalSourceReadback( + com.google.protobuf.ByteString.copyFromUtf8("controlled-source-readback")) + .build(); + var protection = + net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference.newBuilder() + .setProtectionId(UUID.randomUUID().toString()) + .setProtectionFence(1L) + .build(); + var terminal = + net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest( + net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest + .newBuilder() + .setOriginal(creationRequest) + .setAccountProtection(protection) + .setGameSessionProtection( + protection.toBuilder().setProtectionId(UUID.randomUUID().toString())) + .setWorldProtection( + protection.toBuilder().setProtectionId(UUID.randomUUID().toString()))) + .setAccountOriginal(account) + .setOriginalAccountProtection( + com.google.protobuf.ByteString.copyFromUtf8("controlled-account-protection")) + .setOriginalGameSessionProtection( + com.google.protobuf.ByteString.copyFromUtf8("controlled-game-session-protection")) + .setOriginalWorldProtection( + com.google.protobuf.ByteString.copyFromUtf8("controlled-world-protection")) + .setEntityIntakeRequestId(UUID.randomUUID().toString()) + .setOutcome( + net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome + .ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(character) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1L) + .setCompletedAt("2026-10-23T00:00:00Z") + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .build(); + var selected = + CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(character) + .setTarget(target) + .setSourceIdentity(source) + .setSnapshot( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference + .newBuilder() + .setSnapshotUuid(snapshot) + .setSnapshotDigest(snapshotDigest)) + .setCreationOperationUuid(creationOperation) + .setMutationDigest(mutationDigest) + .setTerminal(terminal) + .build(); + return new CreatedFixture(original, roster, selected); + } + private CanonicalGameplayRosterReferenceRepository.TargetCandidate retireOriginal( GetCanonicalGameplayRosterReferenceRequest request) throws Exception { transaction.executeWithoutResult( @@ -1925,23 +2584,30 @@ private CanonicalGameplayRosterReferenceRepository repository( } private void migrate(String target) { + migrate(dataSource, schema, target); + } + + private static Flyway migrate( + DriverManagerDataSource selectedSource, String selectedSchema, String target) { var configuration = Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) + .dataSource(selectedSource) + .schemas(selectedSchema) + .defaultSchema(selectedSchema) .locations( "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath(), "filesystem:" + Path.of("../common-saga/src/main/resources/db/migration/saga") .toAbsolutePath()) - .placeholders(java.util.Map.of("serviceSchema", schema)) + .placeholders(java.util.Map.of("serviceSchema", selectedSchema)) .target(target); configuration .getPluginRegister() .getPlugin(PostgreSQLConfigurationExtension.class) .setTransactionalLock(false); - configuration.load().migrate(); + var flyway = configuration.load(); + flyway.migrate(); + return flyway; } private static CanonicalGameplayRosterResponse receipt( 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 a9dc5b53d9..434d89d721 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 @@ -113,7 +113,7 @@ void rosterRetirementUsesRealCommittedAdmissionReaderAndLocksCurrentPointerUnder prepared.catalog(), prepared.binding(), prepared.gameInstanceUuid()); reservePre1006Attempt(fixture, predecessor.launch(), admission); seedPre1006Terminal(fixture, prepared, predecessor.launch(), admission, true); - migration(fixture, "1017").migrate(); + migration(fixture, "1020").migrate(); var routes = new net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService( NAMESPACE, @@ -339,7 +339,7 @@ void recoveryUsesRealCommittedV2PointerWithSyntheticRetainedV1Originals() throws uuid(122)); reservePre1006Attempt(fixture, predecessor.launch(), admission); seedPre1006ExpectedClosedTerminal(fixture, prepared, predecessor.launch(), admission, origin); - migration(fixture, "1017").migrate(); + migration(fixture, "1020").migrate(); var routes = new net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService( NAMESPACE, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java index fda3727841..04d4fad42b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java @@ -34,11 +34,15 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; 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.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; @@ -71,6 +75,90 @@ class GameSessionCharacterCreatePublicSourceServiceTest { private static final UUID INSTANCE = UUID.randomUUID(); private static final UUID PLAYABLE = UUID.randomUUID(); private static final UUID VERSION = UUID.randomUUID(); + private static final UUID DESCRIPTOR = UUID.randomUUID(); + private static final UUID DESCRIPTOR_REVISION = UUID.randomUUID(); + private static final UUID AUTHORED_BINDING = UUID.randomUUID(); + private static final String DESCRIPTOR_JSON = + "{\"schemaVersion\":1,\"descriptorId\":\"" + + DESCRIPTOR + + "\",\"descriptorRevisionId\":\"" + + DESCRIPTOR_REVISION + + "\",\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}"; + + @Test + void resolvedCreatedSourceBindsActualSelectedTargetDescriptorAndAuthoredIdentity() { + try (var fixture = new Fixture()) { + var resolved = fixture.service.resolvePlayerCreatedRosterSource(rosterRequest()); + assertThat(resolved.route()).isSameAs(fixture.route); + var target = resolved.target(); + assertThat(target.getTenantUuid()).isEqualTo(TENANT.toString()); + assertThat(target.getRealmUuid()).isEqualTo(REALM.toString()); + assertThat(target.getWorldSlug()).isEqualTo("world"); + assertThat(target.getRealmSlug()).isEqualTo("realm"); + assertThat(target.getGameInstanceUuid()).isEqualTo(INSTANCE.toString()); + assertThat(target.getCanonicalVersionUuid()).isEqualTo(VERSION.toString()); + assertThat(target.getPlayableStateNamespaceUuid()).isEqualTo(PLAYABLE.toString()); + assertThat(target.getPlayableStateScope()) + .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(target.getEntryPolicy()) + .isEqualTo( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED); + assertThat(target.getCatalogRevision()).isEqualTo(1L); + assertThat(target.getPointerVersion()).isEqualTo(3L); + assertThat(target.getActiveWorldEpoch()).isEqualTo(7L); + assertThat(target.getPublishedPolicyDigest()).isEqualTo("c".repeat(64)); + assertThat(target.getPublishedReleaseBundleRef()).isEqualTo("original-release"); + assertThat(target.getAdmissionPointerSnapshotDigest()).isEqualTo("b".repeat(64)); + assertThat(target.getPublishedOwnerProofDigest()).isEqualTo("a".repeat(64)); + var identity = resolved.sourceIdentity(); + assertThat(CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity(identity)) + .isSameAs(identity); + assertThat(identity.getSchemaVersion()).isEqualTo(1); + assertThat(identity.getDescriptorUuid()).isEqualTo(DESCRIPTOR.toString()); + assertThat(identity.getDescriptorRevisionUuid()).isEqualTo(DESCRIPTOR_REVISION.toString()); + assertThat(identity.getDescriptorDigest()) + .isEqualTo(PlayerCreationDescriptor.parse(DESCRIPTOR_JSON).digest()); + assertThat(identity.getAuthoredBindingUuid()).isEqualTo(AUTHORED_BINDING.toString()); + assertThat(identity.getAuthoredBindingDigest()).isEqualTo("sha256:" + "d".repeat(64)); + assertThat(resolved.response().getRequest()).isEqualTo(rosterRequest()); + assertThat(resolved.response().getAuthoredSource().toByteArray()) + .containsExactly( + AuthoredInitialActorCoreReadGrpcCodec.toResponse(fixture.authored).toByteArray()); + assertThat(resolved.response().getPublishedPolicySetEvidence().toByteArray()) + .containsExactly(fixture.policySet.canonicalBytes()); + assertThat(fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isEqualTo(resolved.response()); + verify(fixture.gameDesign, org.mockito.Mockito.times(2)).read(any()); + verify(fixture.world, org.mockito.Mockito.times(2)).read(any()); + assertThat( + GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource.class + .getDeclaredConstructors()) + .allSatisfy( + constructor -> + assertThat(java.lang.reflect.Modifier.isPrivate(constructor.getModifiers())) + .isTrue()); + } + } + + @Test + void resolvedCreatedSourceRejectsMalformedDescriptorBindingAndChangedAuthoredReadback() { + List> invalidations = + List.of( + fixture -> when(fixture.projection.descriptor().canonicalJson()).thenReturn("{}"), + fixture -> when(fixture.projection.bindingId()).thenReturn(new UUID(0L, 0L)), + fixture -> when(fixture.projection.bindingDigest()).thenReturn("d".repeat(64)), + fixture -> when(fixture.policyEvidence.policyDigest()).thenReturn("c".repeat(64)), + fixture -> when(fixture.authored.canonicalBytes()).thenReturn(new byte[] {9}), + fixture -> when(fixture.projection.canonicalTenantId()).thenReturn(UUID.randomUUID()), + fixture -> when(fixture.projection.canonicalVersionId()).thenReturn(UUID.randomUUID())); + for (var invalidate : invalidations) { + try (var fixture = new Fixture()) { + invalidate.accept(fixture); + assertThatThrownBy(() -> fixture.service.resolvePlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(RuntimeException.class); + } + } + } @Test void actualSourceCompositionClassifiesOutboundStatusesAsDependencyUnavailable() { @@ -345,7 +433,7 @@ void finalTargetRereadOccursAfterTheAdditionalPublishedPolicyOwnerCall() { when(fixture.routes.readCurrentTarget(TENANT)).thenReturn(changed); return fixture.policySet; }); - assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + assertThatThrownBy(() -> fixture.service.resolvePlayerCreatedRosterSource(rosterRequest())) .isInstanceOf(StatusRuntimeException.class); verify(fixture.gameDesign).read(any()); verify(fixture.world).read(any()); @@ -973,6 +1061,11 @@ private static final class Fixture implements AutoCloseable { when(authored.digest()).thenReturn("source-result-digest"); when(authored.descriptor()).thenReturn(launchDescriptor); when(projection.policy().canonicalJson()).thenReturn("controlled-policy"); + when(projection.bindingId()).thenReturn(AUTHORED_BINDING); + when(projection.bindingDigest()).thenReturn("sha256:" + "d".repeat(64)); + when(projection.descriptor().canonicalJson()).thenReturn(DESCRIPTOR_JSON); + when(projection.descriptor().digest()) + .thenReturn(PlayerCreationDescriptor.parse(DESCRIPTOR_JSON).digest()); when(projection.canonicalTenantId()).thenReturn(TENANT); when(projection.canonicalVersionId()).thenReturn(VERSION); when(projection.worldSourceOperationId()).thenReturn(sourceOperation); @@ -1034,6 +1127,7 @@ private static final class Fixture implements AutoCloseable { when(policySet.terminalEvidenceBytes()).thenReturn(new byte[] {7}); when(policySet.policies()).thenReturn(List.of(policyEvidence)); when(policyEvidence.policy()).thenReturn(policy); + when(policyEvidence.policyDigest()).thenReturn("sha256:" + "c".repeat(64)); when(policyEvidence.requireValidDigest(policySet)).thenReturn(policyEvidence); when(policyEvidence.sourceCommitId()).thenReturn(commit); when(policyEvidence.sourceRevisionId()).thenReturn(policyRevision); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java new file mode 100644 index 0000000000..f68e02b35b --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java @@ -0,0 +1,751 @@ +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.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +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.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +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.CanonicalGameplayRosterResponse; +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.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedCharacter; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedRoster; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository.SelectionOutcome; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Controlled source, transport and owner doubles: no genuine mTLS or upstream custody claim. */ +class CanonicalPlayerCreatedRosterClientTest { + @TempDir Path directory; + private final CanonicalGameplayRosterReferenceOwner owner = + mock(CanonicalGameplayRosterReferenceOwner.class); + private final ResolvedPlayerCreatedRosterSource source = + mock(ResolvedPlayerCreatedRosterSource.class); + private final GrpcChannelFactory channels = mock(GrpcChannelFactory.class); + private final List clients = new ArrayList<>(); + private final CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub = + mock(CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub.class); + private Fixture fixture; + private CommonGrpcClientProperties tls; + private AtomicReference stored; + + @BeforeEach + void controlledComposition() throws Exception { + fixture = fixture(); + tls = new CommonGrpcClientProperties(); + // Readable controlled files exercise configuration only; the channel factory is a double. + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "controlled-cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "controlled-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "controlled-ca").toString()); + when(channels.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(mock(ManagedChannel.class)); + when(source.target()).thenReturn(fixture.target()); + when(source.sourceIdentity()).thenReturn(fixture.source()); + var route = mock(CanonicalPlayableTarget.class); + when(route.targetNamespace()).thenReturn(fixture.namespace()); + when(source.route()).thenReturn(route); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withMaxInboundMessageSize(anyInt())).thenReturn(stub); + when(stub.listPlayerCreatedRoster(any())) + .thenAnswer( + call -> { + outside(); + return fixture.roster(); + }); + when(stub.readSelectedPlayerCreatedCharacter(any())) + .thenAnswer( + call -> { + outside(); + return fixture.selected(); + }); + stored = + new AtomicReference<>( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), 1, UUID.randomUUID(), null)); + when(owner.begin(fixture.original())) + .thenAnswer( + call -> { + outside(); + return stored.get(); + }); + when(owner.recordPlayerCreated(fixture.original(), fixture.roster())) + .thenAnswer( + call -> { + outside(); + stored.set( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), + 1, + UUID.fromString(stored.get().getTargetFenceUuid()), + fixture.roster())); + return stored.get(); + }); + when(owner.selectOriginal( + fixture.original(), UUID.fromString(fixture.selected().getSelectedCharacterUuid()))) + .thenAnswer( + call -> { + outside(); + stored.set( + stored.get().toBuilder() + .setSelectionInput( + CanonicalGameplayRosterSelectionInput.newBuilder().setSchemaVersion(1)) + .setSelectedCharacterUuid(fixture.selected().getSelectedCharacterUuid()) + .build()); + return stored.get(); + }); + doAnswer( + call -> { + outside(); + stored.set( + stored.get().toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toByteString()) + .build()); + return null; + }) + .when(owner) + .recordSelectedPlayerCreatedCharacter(fixture.original(), fixture.selected()); + } + + @AfterEach + void closeControlledClients() throws Exception { + TransactionSynchronizationManager.clear(); + for (var client : clients) client.close(); + } + + @Test + void listsAndSelectsThroughDistinctMethodsAndPreservesCompleteOriginalTerminal() + throws Exception { + var client = client(true); + var roster = client.listPlayerCreatedRoster(source, fixture.context()); + assertThat(roster.response()).isEqualTo(fixture.roster()); + assertThat(roster.resolvedSource()).isSameAs(source); + assertThat(roster.originalSelection()).isEqualTo(fixture.original()); + assertThat(roster.target()).isEqualTo(fixture.target()); + assertThat(roster.sourceIdentity()).isEqualTo(fixture.source()); + assertThat(roster.actors()) + .containsExactlyElementsOf(fixture.roster().getRoster().getActorsList()); + assertThat(roster.snapshotDigest()).isEqualTo(fixture.roster().getRoster().getSnapshotDigest()); + var selected = client.readSelectedPlayerCreatedCharacter(roster, selectedContext()); + assertThat(selected.roster()).isSameAs(roster); + assertThat(selected.response()).isEqualTo(fixture.selected()); + assertThat(selected.terminal().toByteString()) + .isEqualTo(fixture.selected().getTerminal().toByteString()); + assertThat(selected.creationOperationUuid().toString()) + .isEqualTo(fixture.selected().getCreationOperationUuid()); + assertThat(selected.mutationDigest()).isEqualTo(fixture.selected().getMutationDigest()); + var calls = inOrder(owner, stub); + calls.verify(owner).begin(fixture.original()); + calls.verify(owner).markRosterReadStarted(fixture.original()); + calls.verify(stub).listPlayerCreatedRoster(any()); + calls.verify(owner).recordPlayerCreated(fixture.original(), fixture.roster()); + calls + .verify(owner) + .selectOriginal( + fixture.original(), UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + calls.verify(stub).readSelectedPlayerCreatedCharacter(any()); + calls + .verify(owner) + .recordSelectedPlayerCreatedCharacter(fixture.original(), fixture.selected()); + verify(stub).withMaxInboundMessageSize(66 * 1024); + verify(stub).withMaxInboundMessageSize(193 * 1024 * 1024); + var list = org.mockito.ArgumentCaptor.forClass(CanonicalPlayerCreatedRosterRequest.class); + verify(stub).listPlayerCreatedRoster(list.capture()); + assertThat(list.getValue().getExpectedSource()).isEqualTo(fixture.source()); + assertThat(list.getValue().getPlayerExecutionContext()).isEqualTo(fixture.context()); + var selection = + org.mockito.ArgumentCaptor.forClass(CanonicalSelectedPlayerCreatedCharacterRequest.class); + verify(stub).readSelectedPlayerCreatedCharacter(selection.capture()); + assertThat(selection.getValue().getExpectedSnapshot().getSnapshotUuid()) + .isEqualTo(roster.snapshotUuid().toString()); + assertThat(selection.getValue().getPlayerExecutionContext()).isEqualTo(selectedContext()); + } + + @Test + void exactStoredMenuAndSelectedReceiptReplayWithoutAnInitializedTransport() throws Exception { + var first = client(true); + var roster = first.listPlayerCreatedRoster(source, fixture.context()); + first.readSelectedPlayerCreatedCharacter(roster, selectedContext()); + var replay = client(false); + var replayedRoster = replay.listPlayerCreatedRoster(source, fixture.context()); + var selected = replay.readSelectedPlayerCreatedCharacter(replayedRoster, selectedContext()); + assertThat(replayedRoster.response()).isEqualTo(fixture.roster()); + assertThat(selected.response().toByteString()).isEqualTo(fixture.selected().toByteString()); + verify(stub).listPlayerCreatedRoster(any()); + verify(stub).readSelectedPlayerCreatedCharacter(any()); + verify(owner).recordPlayerCreated(fixture.original(), fixture.roster()); + verify(owner).recordSelectedPlayerCreatedCharacter(fixture.original(), fixture.selected()); + } + + @Test + void reserveAndCompleteUseExactCreatedOriginalAndClosedInput() throws Exception { + var client = client(false); + UUID menu = UUID.randomUUID(); + client.reserveSelectionInput(source, fixture.context(), "2", menu, "1".repeat(64)); + verify(owner) + .reserveSelectionInput( + fixture.original(), + CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("2") + .setMenuSnapshotUuid(menu.toString()) + .setMenuSnapshotDigest("1".repeat(64)) + .build()); + client.completeSelection(source, fixture.context(), SelectionOutcome.DENIED); + verify(owner).completeSelection(fixture.original(), SelectionOutcome.DENIED); + assertThatThrownBy( + () -> client.reserveSelectionInput(source, fixture.context(), "1", menu, null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> client.reserveSelectionInput(source, fixture.context(), "1", null, "invalid")) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + client.reserveSelectionInput( + source, fixture.context(), "x".repeat(129), null, null)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + } + + @Test + void wrongPolicyNamespaceAndMalformedContextRefuseBeforeOwnerOrRpc() throws Exception { + var client = client(false); + when(source.target()) + .thenReturn( + fixture.target().toBuilder() + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + .build()); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isInstanceOf(IllegalArgumentException.class); + when(source.target()).thenReturn(fixture.target()); + var foreign = mock(CanonicalPlayableTarget.class); + when(foreign.targetNamespace()).thenReturn("foreign"); + when(source.route()).thenReturn(foreign); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isInstanceOf(IllegalArgumentException.class); + when(source.route()).thenReturn(mock(CanonicalPlayableTarget.class)); + when(source.route().targetNamespace()).thenReturn(fixture.namespace()); + var invalid = + List.of( + fixture.context().toBuilder().setRealmId(UUID.randomUUID().toString()).build(), + fixture.context().toBuilder().setSessionId("not-uuid").build(), + fixture.context().toBuilder().setPlayableStateScope("1").build(), + selectedContext()); + for (var context : invalid) { + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, context)) + .isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(owner, stub); + } + + @Test + void changedOwnerOriginalAndChangedEntitySourceOrAccountFailClosed() throws Exception { + var client = client(true); + var other = + fixture.original().toBuilder().setOperationUuid(UUID.randomUUID().toString()).build(); + when(owner.begin(fixture.original())) + .thenReturn( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + other, 1, UUID.randomUUID(), null)); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isInstanceOf(IllegalArgumentException.class); + when(owner.begin(fixture.original())).thenReturn(stored.get()); + var wrongSource = + fixture.roster().toBuilder() + .setSourceIdentity( + fixture.source().toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString())) + .build(); + var wrongAccount = + fixture.roster().toBuilder() + .setRoster( + fixture.roster().getRoster().toBuilder() + .setCanonicalAccountUuid(UUID.randomUUID().toString())) + .build(); + for (var response : List.of(wrongSource, wrongAccount)) { + when(stub.listPlayerCreatedRoster(any())).thenReturn(response); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isInstanceOf(IllegalArgumentException.class); + } + verify(owner, never()).recordPlayerCreated(any(), any()); + } + + @Test + void selectedRequiresOriginalContextActorSourceAndExactStoredSnapshot() throws Exception { + var client = client(true); + var roster = client.listPlayerCreatedRoster(source, fixture.context()); + var invalid = + List.of( + selectedContext().toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + selectedContext().toBuilder().setSessionId(UUID.randomUUID().toString()).build(), + selectedContext().toBuilder().setAccountId(UUID.randomUUID().toString()).build(), + selectedContext().toBuilder().setCharacterId(UUID.randomUUID().toString()).build()); + for (var context : invalid) { + assertThatThrownBy(() -> client.readSelectedPlayerCreatedCharacter(roster, context)) + .isInstanceOf(IllegalArgumentException.class); + } + when(source.sourceIdentity()) + .thenReturn( + fixture.source().toBuilder().setDescriptorUuid(UUID.randomUUID().toString()).build()); + assertThatThrownBy(() -> client.readSelectedPlayerCreatedCharacter(roster, selectedContext())) + .isInstanceOf(IllegalArgumentException.class); + when(source.sourceIdentity()).thenReturn(fixture.source()); + var changedRoster = + fixture.roster().toBuilder() + .setRoster( + fixture.roster().getRoster().toBuilder() + .setSnapshotUuid(UUID.randomUUID().toString())) + .build(); + var changedOriginal = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), + 1, + UUID.fromString(stored.get().getTargetFenceUuid()), + changedRoster) + .toBuilder() + .setSelectionInput( + CanonicalGameplayRosterSelectionInput.newBuilder().setSchemaVersion(1)) + .setSelectedCharacterUuid(fixture.selected().getSelectedCharacterUuid()) + .build(); + when(owner.selectOriginal(any(), any())).thenReturn(changedOriginal); + assertThatThrownBy(() -> client.readSelectedPlayerCreatedCharacter(roster, selectedContext())) + .isInstanceOf(IllegalArgumentException.class); + verify(stub, never()).readSelectedPlayerCreatedCharacter(any()); + } + + @Test + void selectedResponseBindingOrTerminalSubstitutionCannotBeRecorded() throws Exception { + var client = client(true); + var roster = client.listPlayerCreatedRoster(source, fixture.context()); + var responses = + List.of( + fixture.selected().toBuilder() + .setCreationOperationUuid(UUID.randomUUID().toString()) + .build(), + fixture.selected().toBuilder() + .setSnapshot( + fixture.selected().getSnapshot().toBuilder() + .setSnapshotUuid(UUID.randomUUID().toString())) + .build(), + fixture.selected().toBuilder() + .setSourceIdentity( + fixture.source().toBuilder() + .setAuthoredBindingUuid(UUID.randomUUID().toString())) + .build()); + for (var response : responses) { + when(stub.readSelectedPlayerCreatedCharacter(any())).thenReturn(response); + assertThatThrownBy(() -> client.readSelectedPlayerCreatedCharacter(roster, selectedContext())) + .isInstanceOf(IllegalArgumentException.class); + } + verify(owner, never()).recordSelectedPlayerCreatedCharacter(any(), any()); + } + + @Test + void noTransportOrOwnerAndEstablishedUnavailableFailuresRemainClosed() throws Exception { + var client = client(false); + assertUnavailable(() -> client.listPlayerCreatedRoster(source, fixture.context())); + verify(owner, never()).markRosterReadStarted(any()); + var missingOwner = + new CanonicalPlayerCreatedRosterClient( + new ServiceEndpointsProperties(), tls, channels, fixture.namespace(), null); + clients.add(missingOwner); + assertUnavailable(() -> missingOwner.listPlayerCreatedRoster(source, fixture.context())); + assertUnavailable( + () -> missingOwner.reserveSelectionInput(source, fixture.context(), "", null, null)); + assertUnavailable( + () -> missingOwner.completeSelection(source, fixture.context(), SelectionOutcome.DENIED)); + var storage = + new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "controlled unavailable"); + doThrow(storage).when(owner).begin(any()); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isSameAs(storage); + var remote = Status.UNAVAILABLE.withDescription("Entity unavailable").asRuntimeException(); + doThrow(remote).when(owner).begin(any()); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isSameAs(remote); + } + + @Test + void actualGrpcFailuresPropagateWithoutRecordingReceipts() throws Exception { + var client = client(true); + var failure = + Status.FAILED_PRECONDITION.withDescription("exact source changed").asRuntimeException(); + doThrow(failure).when(stub).listPlayerCreatedRoster(any()); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isSameAs(failure); + verify(owner, never()).recordPlayerCreated(any(), any()); + doReturn(fixture.roster()).when(stub).listPlayerCreatedRoster(any()); + var roster = client.listPlayerCreatedRoster(source, fixture.context()); + doThrow(failure).when(stub).readSelectedPlayerCreatedCharacter(any()); + assertThatThrownBy(() -> client.readSelectedPlayerCreatedCharacter(roster, selectedContext())) + .isSameAs(failure); + verify(owner, never()).recordSelectedPlayerCreatedCharacter(any(), any()); + } + + @Test + void everyOperationRejectsActualAndSynchronizationOnlyAmbientSql() throws Exception { + var client = client(true); + var roster = client.listPlayerCreatedRoster(source, fixture.context()); + var operations = + List.of( + () -> client.reserveSelectionInput(source, fixture.context(), "", null, null), + () -> client.completeSelection(source, fixture.context(), SelectionOutcome.DENIED), + () -> client.listPlayerCreatedRoster(source, fixture.context()), + () -> client.readSelectedPlayerCreatedCharacter(roster, selectedContext())); + for (boolean synchronizationOnly : List.of(false, true)) { + if (synchronizationOnly) TransactionSynchronizationManager.initSynchronization(); + else TransactionSynchronizationManager.setActualTransactionActive(true); + try { + for (var operation : operations) { + assertThatThrownBy(operation::run).isInstanceOf(IllegalStateException.class); + } + } finally { + TransactionSynchronizationManager.clear(); + } + } + verify(owner).begin(fixture.original()); + verify(owner, never()).reserveSelectionInput(any(), any()); + verify(owner, never()).completeSelection(any(), any()); + verify(owner, never()).selectOriginal(any(), any()); + } + + @Test + void actualBuiltStubPinsTheEntityPeerAndUsesCompressionDeadlineAndCreatedRosterBudget() + throws Exception { + var channel = mock(ManagedChannel.class); + var ssl = mock(javax.net.ssl.SSLSession.class); + var certificate = mock(java.security.cert.X509Certificate.class); + when(ssl.getPeerCertificates()).thenReturn(new java.security.cert.Certificate[] {certificate}); + when(certificate.getSubjectAlternativeNames()) + .thenReturn( + List.of(List.of(6, "spiffe://firemud/ns/foreign/sa/entity-management-service"))); + @SuppressWarnings("unchecked") + io.grpc.ClientCall + call = mock(io.grpc.ClientCall.class); + when(call.getAttributes()) + .thenReturn( + io.grpc.Attributes.newBuilder() + .set(io.grpc.Grpc.TRANSPORT_ATTR_SSL_SESSION, ssl) + .build()); + doAnswer( + invocation -> { + io.grpc.ClientCall.Listener listener = + invocation.getArgument(0); + listener.onMessage(fixture.roster()); + listener.onClose(Status.OK, new io.grpc.Metadata()); + return null; + }) + .when(call) + .start(any(), any()); + when(channel.newCall( + any(), any())) + .thenReturn(call); + when(channels.buildChannel(anyString(), anyInt(), any(), anyBoolean())).thenReturn(channel); + var client = client(false); + client.init(); + assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + var options = org.mockito.ArgumentCaptor.forClass(io.grpc.CallOptions.class); + verify(channel).newCall(any(), options.capture()); + assertThat(options.getValue().getCompressor()).isEqualTo("gzip"); + assertThat(options.getValue().getMaxInboundMessageSize()).isEqualTo(66 * 1024); + assertThat(options.getValue().getDeadline()).isNotNull(); + assertThat(options.getValue().getCredentials()) + .isInstanceOf( + net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials.class); + verify(owner, never()).recordPlayerCreated(any(), any()); + // This is a controlled TLS-session transport seam, not a completed physical TLS handshake. + } + + @Test + void wrappersHaveOnlyPrivateConstructorsAndTlsConfigurationIsRequired() { + for (var type : + List.of(VerifiedPlayerCreatedRoster.class, VerifiedPlayerCreatedCharacter.class)) { + assertThat(type.getDeclaredConstructors()) + .allMatch(c -> Modifier.isPrivate(c.getModifiers())); + } + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new CanonicalPlayerCreatedRosterClient( + new ServiceEndpointsProperties(), + plaintext, + channels, + fixture.namespace(), + owner)) + .isInstanceOf(IllegalArgumentException.class); + var classpath = tls.copy(); + classpath.setCertChain("classpath:client.crt"); + assertThatThrownBy( + () -> + new CanonicalPlayerCreatedRosterClient( + new ServiceEndpointsProperties(), + classpath, + channels, + fixture.namespace(), + owner)) + .isInstanceOf(IllegalArgumentException.class); + } + + private CanonicalPlayerCreatedRosterClient client(boolean initialized) throws Exception { + var client = + new CanonicalPlayerCreatedRosterClient( + new ServiceEndpointsProperties(), tls, channels, fixture.namespace(), owner); + clients.add(client); + if (initialized) { + client.init(); + // Controlled transport replacement after real manual initialization. No peer custody claim. + ReflectionTestUtils.setField(client, "stub", stub); + } + return client; + } + + private PlayerExecutionContext selectedContext() { + return fixture.context().toBuilder() + .setCharacterId(fixture.selected().getSelectedCharacterUuid()) + .build(); + } + + private static void assertUnavailable(Runnable operation) { + assertThatThrownBy(operation::run) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + } + + private static void outside() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private record Fixture( + String namespace, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + PlayerExecutionContext context, + GetCanonicalGameplayRosterReferenceRequest original, + CanonicalPlayerCreatedRosterResponse roster, + CanonicalSelectedPlayerCreatedCharacterResponse selected) {} + + private static Fixture fixture() throws Exception { + Path root = Path.of("").toAbsolutePath(); + while (root != null && !Files.exists(root.resolve("settings.gradle.kts"))) + root = root.getParent(); + if (root == null) + throw new IllegalStateException("Controlled CHARACTER_CREATE fixture unavailable"); + byte[] bytes = + Files.readString( + root.resolve( + "services/account-service/src/testFixtures/resources/charactercreate/public-action.json")) + .strip() + .getBytes(StandardCharsets.UTF_8); + var action = CharacterCreateOperatorActionCodec.decode(bytes); + var authored = action.mutation().authoredSource(); + var descriptor = PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); + var source = + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(authored.bindingId()) + .setAuthoredBindingDigest(authored.bindingDigest()) + .build(); + var target = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(action.scope().tenantId()) + .setRealmUuid(action.target().realmId()) + .setWorldSlug(action.target().worldSlug()) + .setRealmSlug(action.target().realmSlug()) + .setGameInstanceUuid(action.target().gameInstanceId()) + .setCanonicalVersionUuid(action.target().versionId()) + .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) + .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) + .setActiveWorldEpoch(Long.parseLong(action.expectedVersion().activeLifecycleEpoch())) + .setPublishedPolicyDigest(authored.policy().contentDigest().substring(7)) + .setPublishedReleaseBundleRef("controlled-created-release") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .build(); + var context = + PlayerExecutionContext.newBuilder() + .setRequestId(UUID.randomUUID().toString()) + .setSessionId(UUID.randomUUID().toString()) + .setAccountId(action.target().accountId()) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .build(); + var original = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(context.getRequestId()), + UUID.fromString(context.getAccountId()), + UUID.fromString(context.getSessionId()), + action.scope().targetNamespace(), + target, + source); + String character = UUID.randomUUID().toString(); + var actors = + List.of( + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(character) + .setDisplayName("Controlled persisted actor") + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()); + String snapshot = UUID.randomUUID().toString(); + String digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + context.getAccountId(), target, source, actors); + var roster = + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(source) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(context.getAccountId()) + .setTarget(target) + .setSnapshotUuid(snapshot) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .build(); + String operation = UUID.randomUUID().toString(); + String mutation = CharacterCreateOperatorActionCodec.mutationDigest(action); + var accountRequest = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(operation) + .setMutationDigest(mutation) + .build(); + var account = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(action.scope().targetNamespace()) + .setOperationId(operation) + .setMutationDigest(mutation) + .setCreateCharacterRequestId(UUID.randomUUID().toString()) + .setConnectScopeId("controlled-create-scope") + .setAuthenticatedAccountId(action.target().accountId()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(bytes)) + .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-source-readback")) + .build(); + var protection = + CharacterCreateProtectionReference.newBuilder() + .setProtectionId(UUID.randomUUID().toString()) + .setProtectionFence(1) + .build(); + var terminal = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest( + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(accountRequest) + .setAccountProtection(protection) + .setGameSessionProtection( + protection.toBuilder().setProtectionId(UUID.randomUUID().toString())) + .setWorldProtection( + protection.toBuilder().setProtectionId(UUID.randomUUID().toString()))) + .setAccountOriginal(account) + .setOriginalAccountProtection(ByteString.copyFromUtf8("controlled-account-protection")) + .setOriginalGameSessionProtection( + ByteString.copyFromUtf8("controlled-game-session-protection")) + .setOriginalWorldProtection(ByteString.copyFromUtf8("controlled-world-protection")) + .setEntityIntakeRequestId(UUID.randomUUID().toString()) + .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setCharacterId(character) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1) + .setCompletedAt("2026-10-23T00:00:00Z") + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) + .build(); + var selected = + CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(context.getRequestId()) + .setCanonicalAccountUuid(context.getAccountId()) + .setSelectedCharacterUuid(character) + .setTarget(target) + .setSourceIdentity(source) + .setSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(snapshot) + .setSnapshotDigest(digest)) + .setCreationOperationUuid(operation) + .setMutationDigest(mutation) + .setTerminal(terminal) + .build(); + return new Fixture( + action.scope().targetNamespace(), target, source, context, original, roster, selected); + } +} 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 index 4810b7c5b2..f5212f816c 100644 --- 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 @@ -1,11 +1,15 @@ package net.firedevops.firemud.gamesession.command.text; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedRoster; import org.junit.jupiter.api.Test; import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; @@ -93,6 +97,72 @@ void rejectsUuidNameAndNonCanonicalOrdinalSelectors() { } } + @Test + void createdPrivateCapabilityUsesTheSameZeroOneManyAndOrdinalRules() { + // Controlled private-capability double proves ordinal mechanics, not Entity/source custody. + var roster = mock(VerifiedPlayerCreatedRoster.class); + var target = + CanonicalGameplayRosterClient.expectedTarget( + PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute()) + .toBuilder() + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .build(); + UUID snapshot = UUID.randomUUID(); + when(roster.canonicalAccountUuid()).thenReturn(ACCOUNT_UUID); + when(roster.snapshotUuid()).thenReturn(snapshot); + when(roster.snapshotDigest()).thenReturn("a".repeat(64)); + when(roster.target()).thenReturn(target); + when(roster.actors()).thenReturn(List.of()); + assertThat(CanonicalGameplayActorSelection.select(roster, null)) + .isEqualTo( + new CanonicalGameplayActorSelection.Denied( + CanonicalGameplayActorSelection.Denial.NO_PLAYER_CREATED_ACTOR)); + var first = + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(FIRST_ACTOR_UUID.toString()) + .setDisplayName("Pilot One") + .build(); + var second = + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(SECOND_ACTOR_UUID.toString()) + .setDisplayName("Pilot Two") + .build(); + when(roster.actors()).thenReturn(List.of(first)); + assertThat(CanonicalGameplayActorSelection.select(roster, null)) + .isInstanceOfSatisfying( + CanonicalGameplayActorSelection.Selected.class, + selected -> { + assertThat(selected.characterUuid()).isEqualTo(FIRST_ACTOR_UUID); + assertThat(selected.canonicalAccountUuid()).isEqualTo(ACCOUNT_UUID); + assertThat(selected.rosterSnapshotUuid()).isEqualTo(snapshot); + assertThat(selected.rosterSnapshotDigest()).isEqualTo("a".repeat(64)); + assertThat(selected.target()).isEqualTo(target); + assertThat(selected.ordinal()).isEqualTo(1); + }); + when(roster.actors()).thenReturn(List.of(first, second)); + 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)); + for (String selector : + List.of(FIRST_ACTOR_UUID.toString(), "Pilot One", "01", "+1", "0", "3")) { + assertThat(CanonicalGameplayActorSelection.select(roster, selector)) + .isInstanceOf(CanonicalGameplayActorSelection.Denied.class); + } + assertThat(CanonicalGameplayActorSelection.select((VerifiedPlayerCreatedRoster) null, null)) + .isEqualTo( + new CanonicalGameplayActorSelection.Denied( + CanonicalGameplayActorSelection.Denial.INVALID_SNAPSHOT)); + } + @Test void rejectsCrossAccountChangedTargetAndMalformedActors() { var route = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java new file mode 100644 index 0000000000..f3dd48a718 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java @@ -0,0 +1,505 @@ +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.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository.CurrentOpenSnapshot; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; +import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +/** Controlled orchestration doubles, not SQL proof or genuine source/provenance custody. */ +class CanonicalGameplayRosterReferenceOwnerTest { + private final CanonicalGameplayRosterReferenceRepository repository = + mock(CanonicalGameplayRosterReferenceRepository.class); + private final CanonicalPublishedPlayerRouteReadService published = + mock(CanonicalPublishedPlayerRouteReadService.class); + private final CanonicalPlayerRouteReadService routes = + mock(CanonicalPlayerRouteReadService.class); + private final CanonicalInitialAdmissionRepository admissions = + mock(CanonicalInitialAdmissionRepository.class); + private final CanonicalGameplayRosterRecoveryClient recovery = + mock(CanonicalGameplayRosterRecoveryClient.class); + private final GameSessionCharacterCreatePublicSourceService created = + mock(GameSessionCharacterCreatePublicSourceService.class); + // A private-view double tests consumption only; no constructor/factory bypass is introduced. + private final ResolvedPlayerCreatedRosterSource source = + mock(ResolvedPlayerCreatedRosterSource.class); + private final CanonicalPlayableTarget route = route("test"); + private final CanonicalGameplayRosterTarget target = + CanonicalGameplayRosterClient.expectedTarget( + PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute()) + .toBuilder() + .setEntryPolicy( + CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .build(); + private final CanonicalPlayerCreatedRosterSourceIdentity identity = + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(UUID.randomUUID().toString()) + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .setDescriptorDigest("sha256:" + "1".repeat(64)) + .setAuthoredBindingUuid(UUID.randomUUID().toString()) + .setAuthoredBindingDigest("sha256:" + "2".repeat(64)) + .build(); + private final GetCanonicalGameplayRosterReferenceRequest request = + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), "test", target, identity); + private final CurrentOpenSnapshot snapshot = snapshot(route, route.pointerVersion()); + private final GetCanonicalGameplayRosterReferenceResponse reserved = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + request, 1, UUID.randomUUID(), null); + private final CanonicalGameplayRosterReferenceOwner owner = + new CanonicalGameplayRosterReferenceOwner( + repository, transactions(), published, routes, admissions, recovery, created); + + @BeforeEach + void controlledSource() { + when(repository.find(request)).thenReturn(Optional.empty()); + when(repository.begin(request)) + .thenAnswer( + ignored -> { + inside(); + return reserved; + }); + when(source.target()).thenReturn(target); + when(source.sourceIdentity()).thenReturn(identity); + when(source.route()).thenReturn(route); + when(created.resolvePlayerCreatedRosterSource(any())) + .thenAnswer( + ignored -> { + outside(); + return source; + }); + when(admissions.readCurrentOpenSnapshotForRealm( + "test", route.canonicalTenantId(), route.realmId())) + .thenAnswer( + ignored -> { + outside(); + return snapshot; + }); + when(admissions.lockExactCurrentOpenSnapshot(snapshot)) + .thenAnswer( + ignored -> { + inside(); + return snapshot; + }); + } + + @Test + void freshCreatedReservationResolvesExactSourceOutsideSqlThenLocksCurrentPointerInsideSql() { + assertThat(owner.begin(request)).isSameAs(reserved); + var calls = inOrder(repository, created, admissions); + calls.verify(repository).find(request); + calls.verify(created).resolvePlayerCreatedRosterSource(expectedSourceRequest()); + calls + .verify(admissions) + .readCurrentOpenSnapshotForRealm("test", route.canonicalTenantId(), route.realmId()); + calls.verify(repository).begin(request); + calls.verify(admissions).lockExactCurrentOpenSnapshot(snapshot); + verifyNoInteractions(published, routes, recovery); + outside(); + } + + @Test + void missingCreatedCollaboratorFailsClosedWhileSixArgumentCompositionStillExists() { + var preseededComposition = + new CanonicalGameplayRosterReferenceOwner( + repository, transactions(), published, routes, admissions, recovery); + assertThatThrownBy(() -> preseededComposition.begin(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class); + verify(repository, never()).begin(any()); + verifyNoInteractions(created, published, admissions); + } + + @Test + void preseededRequestsContinueThroughTheExistingPublishedSourceReader() { + var preseeded = + CanonicalGameplayRosterReferenceEvidence.request( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "test", + CanonicalGameplayRosterClient.expectedTarget( + PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute())); + when(repository.find(preseeded)).thenReturn(Optional.empty()); + var stale = + new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "published PRESEEDED_ONLY source changed"); + when(published.readCurrent( + any( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence.Request + .class))) + .thenAnswer( + ignored -> { + outside(); + throw stale; + }); + assertThatThrownBy(() -> owner.begin(preseeded)).isSameAs(stale); + verifyNoInteractions(created, admissions); + verify(repository, never()).begin(any()); + } + + @Test + void retainedCreatedReceiptReplaysWithoutResolvingOrRebindingCurrentSource() { + var retained = + reserved.toBuilder() + .setState( + CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED) + .setCanonicalPlayerCreatedRosterReceipt( + ByteString.copyFromUtf8("controlled retained bytes")) + .build(); + when(repository.find(request)).thenReturn(Optional.of(retained)); + when(repository.replay(request)).thenReturn(retained); + assertThat(owner.begin(request)).isSameAs(retained); + verify(repository, never()).begin(any()); + verifyNoInteractions(created, published, admissions); + } + + @Test + void targetSourceAndNamespaceSubstitutionsRefuseBeforeReservation() { + when(source.target()) + .thenReturn(target.toBuilder().setPointerVersion(target.getPointerVersion() + 1).build()); + assertStaleBeforeReservation(); + when(source.target()).thenReturn(target); + when(source.sourceIdentity()) + .thenReturn( + identity.toBuilder().setDescriptorRevisionUuid(UUID.randomUUID().toString()).build()); + assertStaleBeforeReservation(); + when(source.sourceIdentity()).thenReturn(identity); + when(source.route()).thenReturn(route("foreign")); + assertStaleBeforeReservation(); + verifyNoInteractions(admissions); + } + + @Test + void independentlyChangedCurrentPointerRefusesBeforeReservation() { + when(admissions.readCurrentOpenSnapshotForRealm( + "test", route.canonicalTenantId(), route.realmId())) + .thenReturn(snapshot(route, route.pointerVersion() + 1)); + assertStaleBeforeReservation(); + verify(admissions, never()).lockExactCurrentOpenSnapshot(any()); + } + + @Test + void currentPointerLockFailureEscapesWithoutReturningAReservedResult() { + doThrow(new IllegalStateException("current pointer changed under lock")) + .when(admissions) + .lockExactCurrentOpenSnapshot(snapshot); + assertThatThrownBy(() -> owner.begin(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("current pointer changed under lock"); + verify(repository).begin(request); + // This callback seam proves ordering/propagation, not physical transaction rollback. + outside(); + } + + @Test + void sourceTransportCategoriesRemainTypedAndPreserveCauses() { + var cases = + List.of( + Map.entry( + Status.FAILED_PRECONDITION, + CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class), + Map.entry( + Status.UNAVAILABLE, + CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class), + Map.entry( + Status.DEADLINE_EXCEEDED, + CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class), + Map.entry( + Status.INVALID_ARGUMENT, + CanonicalPublishedPlayerRouteReadService.InvalidAuthorityException.class)); + for (var entry : cases) { + var failure = entry.getKey().withDescription("private source detail").asRuntimeException(); + doThrow(failure).when(created).resolvePlayerCreatedRosterSource(any()); + assertThatThrownBy(() -> owner.begin(request)) + .isInstanceOf(entry.getValue()) + .hasCause(failure); + } + // Controlled exception double checks orchestration; actual dependency classification is proved + // by the source service tests. + var dependency = + mock( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + .class); + doThrow(dependency).when(created).resolvePlayerCreatedRosterSource(any()); + assertThatThrownBy(() -> owner.begin(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class) + .hasCause(dependency); + var unexpected = Status.INTERNAL.asRuntimeException(); + doThrow(unexpected).when(created).resolvePlayerCreatedRosterSource(any()); + assertThatThrownBy(() -> owner.begin(request)).isSameAs(unexpected); + verify(repository, never()).begin(any()); + verifyNoInteractions(admissions); + } + + @Test + void staleUnissuedReplayClosesDeniedButUnavailableReplayRemainsProtected() { + when(repository.find(request)).thenReturn(Optional.of(reserved)); + when(repository.replay(request)).thenReturn(reserved); + doAnswer( + ignored -> { + inside(); + return null; + }) + .when(repository) + .completeUnissuedDenied(request); + doThrow(Status.FAILED_PRECONDITION.asRuntimeException()) + .when(created) + .resolvePlayerCreatedRosterSource(any()); + assertThatThrownBy(() -> owner.begin(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + verify(repository).completeUnissuedDenied(request); + doThrow(Status.UNAVAILABLE.asRuntimeException()) + .when(created) + .resolvePlayerCreatedRosterSource(any()); + assertThatThrownBy(() -> owner.begin(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class); + var dependency = + mock( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + .class); + doThrow(dependency).when(created).resolvePlayerCreatedRosterSource(any()); + assertThatThrownBy(() -> owner.begin(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class) + .hasCause(dependency); + verify(repository).completeUnissuedDenied(request); + verify(repository, never()).begin(any()); + } + + @Test + void unissuedOwnerReadRequiresSourceButRecoveryAndClosedEvidenceRemainReadable() { + when(repository.read(request)).thenReturn(reserved); + assertThat(owner.read(request)).isSameAs(reserved); + verify(created).resolvePlayerCreatedRosterSource(expectedSourceRequest()); + doThrow(new AssertionError("source must not be reread")) + .when(created) + .resolvePlayerCreatedRosterSource(any()); + var recovering = reserved.toBuilder().setRecoveryUuid(UUID.randomUUID().toString()).build(); + var closed = reserved.toBuilder().setTerminalOutcome("DENIED").build(); + var recorded = + reserved.toBuilder() + .setState( + CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED) + .setCanonicalPlayerCreatedRosterReceipt(ByteString.copyFromUtf8("retained")) + .build(); + for (var original : List.of(recovering, closed, recorded)) { + when(repository.read(request)).thenReturn(original); + assertThat(owner.read(request)).isSameAs(original); + } + } + + @Test + void createdReceiptWritesForwardDistinctCompleteValuesWithinShortTransactions() { + var roster = + CanonicalPlayerCreatedRosterResponse.newBuilder().setSourceIdentity(identity).build(); + var selected = + CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setCreationOperationUuid(UUID.randomUUID().toString()) + .build(); + when(repository.recordPlayerCreated(request, roster)) + .thenAnswer( + ignored -> { + inside(); + return reserved; + }); + doAnswer( + ignored -> { + inside(); + return null; + }) + .when(repository) + .recordSelectedPlayerCreatedCharacter(request, selected); + assertThat(owner.recordPlayerCreated(request, roster)).isSameAs(reserved); + owner.recordSelectedPlayerCreatedCharacter(request, selected); + verify(repository).recordSelectedPlayerCreatedCharacter(request, selected); + var oldReceipt = CanonicalGameplayRosterResponse.getDefaultInstance(); + doThrow(new IllegalArgumentException("strict PRESEEDED_ONLY repository method")) + .when(repository) + .record(request, oldReceipt); + assertThatThrownBy(() -> owner.record(request, oldReceipt)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(created, published, admissions); + outside(); + } + + @Test + void ambientTransactionsRefuseBeforeSourceOrStorage() { + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> owner.begin(request)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + owner.recordPlayerCreated( + request, CanonicalPlayerCreatedRosterResponse.getDefaultInstance())) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy( + () -> + owner.recordSelectedPlayerCreatedCharacter( + request, + CanonicalSelectedPlayerCreatedCharacterResponse.getDefaultInstance())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(repository, created, published, admissions); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private void assertStaleBeforeReservation() { + assertThatThrownBy(() -> owner.begin(request)) + .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StaleAuthorityException.class); + verify(repository, never()).begin(any()); + } + + private ReadPlayerCreatedRosterSourceRequest expectedSourceRequest() { + return ReadPlayerCreatedRosterSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId(request.getOperationUuid()) + .setTargetNamespace("test") + .setCanonicalTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setWorldSlug(target.getWorldSlug()) + .setRealmSlug(target.getRealmSlug()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceId(target.getGameInstanceUuid()) + .setCatalogRevision(target.getCatalogRevision()) + .setPointerVersion(target.getPointerVersion()) + .setExpectedCanonicalVersionId(target.getCanonicalVersionUuid()) + .setActiveWorldEpoch(target.getActiveWorldEpoch()) + .build(); + } + + private static CanonicalPlayableTarget route(String namespace) { + var r = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute().route(); + return new CanonicalPlayableTarget( + namespace, + r.tenantSlug(), + r.canonicalTenantId(), + r.worldSlug(), + r.worldDisplayName(), + r.realmId(), + r.realmSlug(), + r.realmDisplayName(), + r.gameSessionTenantId(), + r.gameInstanceId(), + r.playableStateNamespaceId(), + r.playableStateScope(), + r.canonicalGameInstanceId(), + r.canonicalVersionId(), + r.runtimeVersionId(), + r.catalogRevision(), + r.pointerVersion(), + r.admissionPointerSnapshotDigest(), + r.activeWorldEpoch(), + r.initialAdmissionRequestId(), + r.initialAdmissionRequestDigest(), + r.initialAdmissionOriginKind(), + r.expectedPriorPointerVersion(), + r.holdId(), + r.holdFence(), + r.holdBindingDigest(), + r.auditEventId(), + r.ownerProofDigest(), + r.ownerProofOutcome(), + r.positiveDurableAbort(), + r.ownerProofTerminalAt(), + "PLAYER_CREATED"); + } + + private static CurrentOpenSnapshot snapshot(CanonicalPlayableTarget r, long pointer) { + return new CurrentOpenSnapshot( + new CanonicalInitialAdmissionOwnerProof( + CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED, + r.initialAdmissionRequestId(), + r.initialAdmissionRequestDigest(), + r.targetNamespace(), + r.canonicalTenantId(), + r.worldSlug(), + r.realmId(), + r.playableStateNamespaceId(), + r.playableStateScope(), + r.canonicalGameInstanceId(), + r.canonicalVersionId(), + r.activeWorldEpoch(), + r.catalogRevision(), + r.initialAdmissionOriginKind(), + r.expectedPriorPointerVersion(), + r.holdId(), + r.holdFence(), + r.holdBindingDigest(), + pointer, + r.auditEventId(), + r.ownerProofDigest(), + false, + r.ownerProofTerminalAt()), + r.admissionPointerSnapshotDigest()); + } + + private static TransactionOperations transactions() { + return new TransactionOperations() { + @Override + public T execute(TransactionCallback action) { + outside(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.initSynchronization(); + try { + return action.doInTransaction(new SimpleTransactionStatus()); + } finally { + TransactionSynchronizationManager.clear(); + } + } + }; + } + + private static void outside() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static void inside() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + } +} 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 8184e803b4..788dc99d65 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 @@ -32,6 +32,8 @@ import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; @@ -40,7 +42,16 @@ 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.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedCharacter; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedRoster; import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; import net.firedevops.firemud.gamesession.command.text.CanonicalGameplayActorSelection; import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; @@ -50,12 +61,14 @@ 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.CanonicalGameplayRosterReferenceRepository.SelectionOutcome; 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.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -727,6 +740,705 @@ void failedTerminalWritePreservesDenialButRefusesSuccessfulSelectionAndMenu() th CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); } + @Test + void createdZeroDeniesAndOneReturnsTheDistinctCompleteTerminalReference() throws Exception { + var empty = createdHarness(0); + assertDenied( + empty.service().select(empty.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.NO_PLAYER_CREATED_ACTOR); + verify(empty.client()) + .completeSelection(empty.source(), empty.context(), SelectionOutcome.DENIED); + verify(empty.client(), never()).readSelectedPlayerCreatedCharacter(any(), any()); + verifyNoInteractions(empty.preseeded(), empty.publications()); + + var one = createdHarness(1); + assertThat(one.service().select(one.context(), null, null)) + .isInstanceOfSatisfying( + CanonicalGameplayRosterSelectionService.SelectedPlayerCreatedOwnerReference.class, + selected -> { + assertThat(selected.ownerReference()).isSameAs(one.reference()); + assertThat(selected.displayName()).isEqualTo("Created One"); + assertThat(selected.ordinal()).isEqualTo(1); + assertThat(selected.ownerReference().terminal().toByteString()) + .isEqualTo(one.reference().response().getTerminal().toByteString()); + assertThat(selected.ownerReference().creationOperationUuid().toString()) + .isEqualTo(one.reference().response().getCreationOperationUuid()); + }); + verify(one.client()).completeSelection(one.source(), one.context(), SelectionOutcome.SELECTED); + verify(one.sources(), org.mockito.Mockito.times(3)).resolvePlayerCreatedRosterSource(any()); + var request = org.mockito.ArgumentCaptor.forClass(ReadPlayerCreatedRosterSourceRequest.class); + verify(one.sources(), org.mockito.Mockito.times(3)) + .resolvePlayerCreatedRosterSource(request.capture()); + var actual = request.getValue(); + assertThat(actual.getSchemaVersion()).isEqualTo(1); + assertThat(actual.getReadRequestId()).isEqualTo(one.context().getRequestId()); + assertThat(actual.getTargetNamespace()).isEqualTo(one.route().targetNamespace()); + assertThat(actual.getCanonicalTenantId()).isEqualTo(one.route().canonicalTenantId().toString()); + assertThat(actual.getRealmId()).isEqualTo(one.route().realmId().toString()); + assertThat(actual.getWorldSlug()).isEqualTo(one.route().worldSlug()); + assertThat(actual.getRealmSlug()).isEqualTo(one.route().realmSlug()); + assertThat(actual.getPlayableStateNamespaceId()) + .isEqualTo(one.route().playableStateNamespaceId().toString()); + assertThat(actual.getPlayableStateScope()).isEqualTo("SHARED"); + assertThat(actual.getCanonicalGameInstanceId()) + .isEqualTo(one.route().canonicalGameInstanceId().toString()); + assertThat(actual.getCatalogRevision()).isEqualTo(one.route().catalogRevision()); + assertThat(actual.getPointerVersion()).isEqualTo(one.route().pointerVersion()); + assertThat(actual.getExpectedCanonicalVersionId()) + .isEqualTo(one.route().canonicalVersionId().toString()); + assertThat(actual.getActiveWorldEpoch()).isEqualTo(one.route().activeWorldEpoch()); + verifyNoInteractions(one.preseeded(), one.publications()); + } + + @Test + void createdManyUsesExactMenuAndOnlyOneBasedOrdinals() throws Exception { + var menuHarness = createdHarness(2); + var menu = + (CanonicalGameplayRosterSelectionService.SelectionRequired) + menuHarness.service().select(menuHarness.context(), null, null); + assertThat(menu.choices()) + .containsExactly( + new CanonicalGameplayActorSelection.Choice(1, "Created One"), + new CanonicalGameplayActorSelection.Choice(2, "Created Two")); + verify(menuHarness.client()) + .completeSelection(menuHarness.source(), menuHarness.context(), SelectionOutcome.MENU); + // A later explicit choice has its own original operation and retains the earlier menu identity. + var choice = createdHarness(2); + assertThat(choice.service().select(choice.context(), "2", menu.menuIdentity())) + .isInstanceOfSatisfying( + CanonicalGameplayRosterSelectionService.SelectedPlayerCreatedOwnerReference.class, + selected -> + assertThat(selected.ownerReference().selectedCharacterUuid()) + .isEqualTo(SECOND_ACTOR)); + verify(choice.client()) + .reserveSelectionInput( + choice.source(), + choice.context(), + "2", + menu.menuIdentity().snapshotUuid(), + menu.menuIdentity().snapshotDigest()); + for (String selector : List.of(FIRST_ACTOR.toString(), "Created One", "01", "0", "3")) { + var invalid = createdHarness(2); + assertDenied( + invalid.service().select(invalid.context(), selector, menu.menuIdentity()), + selector.equals("3") + ? CanonicalGameplayRosterSelectionService.Denial.SELECTOR_OUT_OF_RANGE + : CanonicalGameplayRosterSelectionService.Denial.INVALID_SELECTOR); + verify(invalid.client()) + .completeSelection(invalid.source(), invalid.context(), SelectionOutcome.DENIED); + verify(invalid.client(), never()).readSelectedPlayerCreatedCharacter(any(), any()); + } + var missing = createdHarness(2); + assertDenied( + missing.service().select(missing.context(), "1", null), + CanonicalGameplayRosterSelectionService.Denial.MISSING_MENU_IDENTITY); + var stale = createdHarness(2); + assertDenied( + stale + .service() + .select( + stale.context(), + "1", + new CanonicalGameplayRosterSelectionService.SelectionMenuIdentity( + CHANGED_SNAPSHOT, menu.menuIdentity().snapshotDigest())), + CanonicalGameplayRosterSelectionService.Denial.STALE_MENU_IDENTITY); + } + + @Test + void createdDispatchNeverFallsBackAndUnsupportedPoliciesStayDenied() throws Exception { + var h = createdHarness(1); + for (String policy : List.of("AUTO_PROVISIONED", "UNKNOWN")) { + when(h.routes().readCurrentTarget(h.route().canonicalTenantId())) + .thenReturn(withPolicy(h.route(), policy)); + assertDenied( + h.service().select(h.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.UNSUPPORTED_ENTRY_POLICY); + } + verifyNoInteractions(h.sources(), h.client(), h.preseeded(), h.publications()); + when(h.routes().readCurrentTarget(h.route().canonicalTenantId())).thenReturn(h.route()); + for (var service : + List.of( + new CanonicalGameplayRosterSelectionService( + h.routes(), h.publications(), h.preseeded()), + new CanonicalGameplayRosterSelectionService( + h.routes(), h.publications(), h.preseeded(), h.sources(), null), + new CanonicalGameplayRosterSelectionService( + h.routes(), h.publications(), h.preseeded(), null, h.client()))) { + assertDenied( + service.select(h.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); + } + verifyNoInteractions(h.sources(), h.client(), h.preseeded(), h.publications()); + var old = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute(); + var routes = mock(CanonicalPlayerRouteReadService.class); + var publications = mock(CanonicalPublishedPlayerRouteReadService.class); + var preseeded = mock(CanonicalGameplayRosterClient.class); + var sources = mock(GameSessionCharacterCreatePublicSourceService.class); + var created = mock(CanonicalPlayerCreatedRosterClient.class); + when(routes.readCurrentTarget(old.route().canonicalTenantId())).thenReturn(old.route()); + when(publications.readCurrent(old.route())).thenReturn(old); + when(preseeded.listPreseededRoster(any(), any())) + .thenReturn(PublishedRealmPolicyEvidenceFixture.rosterSnapshot(old, ACCOUNT, List.of())); + var fiveArgumentPreseeded = + new CanonicalGameplayRosterSelectionService( + routes, publications, preseeded, sources, created); + assertDenied( + fiveArgumentPreseeded.select( + context(old.route(), UUID.randomUUID().toString()), null, null), + CanonicalGameplayRosterSelectionService.Denial.NO_PRESEEDED_ACTOR); + verifyNoInteractions(sources, created); + } + + @Test + void createdSourceTargetDescriptorAndPolicyRacesAfterEitherRpcRefuseSelection() throws Exception { + for (boolean afterSelected : List.of(false, true)) { + for (String changedPart : List.of("target", "source", "policy")) { + var h = createdHarness(1); + var changed = mock(ResolvedPlayerCreatedRosterSource.class); + var changedRoute = + changedPart.equals("policy") ? withPolicy(h.route(), "PRESEEDED_ONLY") : h.route(); + var changedTarget = + changedPart.equals("target") + ? h.source().target().toBuilder() + .setPointerVersion(h.route().pointerVersion() + 1) + .build() + : h.source().target(); + var changedIdentity = + changedPart.equals("source") + ? h.source().sourceIdentity().toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .build() + : h.source().sourceIdentity(); + when(changed.route()).thenReturn(changedRoute); + when(changed.target()).thenReturn(changedTarget); + when(changed.sourceIdentity()).thenReturn(changedIdentity); + if (afterSelected) + when(h.sources().resolvePlayerCreatedRosterSource(any())) + .thenReturn(h.source(), h.source(), changed); + else + when(h.sources().resolvePlayerCreatedRosterSource(any())).thenReturn(h.source(), changed); + assertDenied( + h.service().select(h.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + verify(h.client()).completeSelection(h.source(), h.context(), SelectionOutcome.DENIED); + if (!afterSelected) + verify(h.client(), never()).readSelectedPlayerCreatedCharacter(any(), any()); + } + } + } + + @Test + void createdSourceRereadIgnoresOnlyCorrelationFieldsAndRequiresInitialFullRoute() + throws Exception { + var h = createdHarness(1); + var same = mock(ResolvedPlayerCreatedRosterSource.class); + var sameRoute = h.route(); + var sameTarget = h.source().target(); + var sameIdentity = h.source().sourceIdentity(); + when(same.route()).thenReturn(sameRoute); + when(same.target()).thenReturn(sameTarget); + when(same.sourceIdentity()).thenReturn(sameIdentity); + when(same.response()) + .thenReturn( + net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse.newBuilder() + .setRequest( + ReadPlayerCreatedRosterSourceRequest.newBuilder() + .setReadRequestId(UUID.randomUUID().toString())) + .build()); + when(h.sources().resolvePlayerCreatedRosterSource(any())).thenReturn(h.source(), same, same); + assertThat(h.service().select(h.context(), null, null)) + .isInstanceOf( + CanonicalGameplayRosterSelectionService.SelectedPlayerCreatedOwnerReference.class); + var changed = createdHarness(1); + when(changed.source().route()).thenReturn(withPolicy(changed.route(), "AUTO_PROVISIONED")); + assertDenied( + changed.service().select(changed.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + verifyNoInteractions(changed.client()); + } + + @Test + void createdTransientAndUntrustedPeerFailuresNeverPrematurelyFinalize() throws Exception { + for (boolean selectedRead : List.of(false, true)) { + var unavailable = createdHarness(1); + if (selectedRead) + doThrow(Status.UNAVAILABLE.asRuntimeException()) + .when(unavailable.client()) + .readSelectedPlayerCreatedCharacter(any(), any()); + else + doThrow(Status.UNAVAILABLE.asRuntimeException()) + .when(unavailable.client()) + .listPlayerCreatedRoster(any(), any()); + assertDenied( + unavailable.service().select(unavailable.context(), null, null), + selectedRead + ? CanonicalGameplayRosterSelectionService.Denial.ASSIGNMENT_UNAVAILABLE + : CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); + verify(unavailable.client(), never()).completeSelection(any(), any(), any()); + var wrongPeer = createdHarness(1); + if (selectedRead) + doThrow(Status.UNAUTHENTICATED.asRuntimeException()) + .when(wrongPeer.client()) + .readSelectedPlayerCreatedCharacter(any(), any()); + else + doThrow(Status.UNAUTHENTICATED.asRuntimeException()) + .when(wrongPeer.client()) + .listPlayerCreatedRoster(any(), any()); + assertDenied( + wrongPeer.service().select(wrongPeer.context(), null, null), + selectedRead + ? CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF + : CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + verify(wrongPeer.client(), never()).completeSelection(any(), any(), any()); + var storage = createdHarness(1); + var failure = + new CanonicalPublishedPlayerRouteReadService.StorageUnavailableException( + "owner unavailable"); + if (selectedRead) + doThrow(failure).when(storage.client()).readSelectedPlayerCreatedCharacter(any(), any()); + else doThrow(failure).when(storage.client()).listPlayerCreatedRoster(any(), any()); + assertDenied( + storage.service().select(storage.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_UNAVAILABLE); + verify(storage.client(), never()).completeSelection(any(), any(), any()); + } + // Controlled exception double checks dispatch, not upstream source custody. + for (RuntimeException failure : + List.of( + Status.UNAVAILABLE.asRuntimeException(), + mock( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + .class))) { + for (int phase = 0; phase < 3; phase++) { + var h = createdHarness(1); + var calls = new AtomicInteger(); + int failedPhase = phase; + when(h.sources().resolvePlayerCreatedRosterSource(any())) + .thenAnswer( + call -> { + assertNoAmbientSql(); + if (calls.getAndIncrement() == failedPhase) throw failure; + return h.source(); + }); + assertDenied( + h.service().select(h.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_UNAVAILABLE); + verify(h.client(), never()).completeSelection(any(), any(), any()); + } + } + } + + @Test + void createdTypedStaleOwnerFailuresRetainRouteChangedAndDefinitiveDeniedCompletion() + throws Exception { + for (int phase = 0; phase < 3; phase++) { + var h = createdHarness(1); + var stale = + new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "owner source changed"); + if (phase == 0) + doThrow(stale).when(h.client()).reserveSelectionInput(any(), any(), any(), any(), any()); + else if (phase == 1) doThrow(stale).when(h.client()).listPlayerCreatedRoster(any(), any()); + else doThrow(stale).when(h.client()).readSelectedPlayerCreatedCharacter(any(), any()); + assertDenied( + h.service().select(h.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_CHANGED); + verify(h.client()).completeSelection(h.source(), h.context(), SelectionOutcome.DENIED); + } + } + + @Test + void createdAccountOriginalAndSelectedCapabilitySubstitutionFailClosed() throws Exception { + var account = createdHarness(1); + when(account.roster().canonicalAccountUuid()).thenReturn(UUID.randomUUID()); + assertDenied( + account.service().select(account.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + var original = createdHarness(1); + var substitutedOriginal = + original.roster().originalSelection().toBuilder() + .setSessionUuid(UUID.randomUUID().toString()) + .build(); + when(original.roster().originalSelection()).thenReturn(substitutedOriginal); + assertDenied( + original.service().select(original.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ROSTER_PROOF); + var selected = createdHarness(1); + var substitutedRoster = mock(VerifiedPlayerCreatedRoster.class); + when(selected.reference().roster()).thenReturn(substitutedRoster); + assertDenied( + selected.service().select(selected.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_ASSIGNMENT_PROOF); + verify(selected.client(), never()).completeSelection(any(), any(), any()); + } + + @Test + void createdContextAndAmbientSqlRefuseBeforeSourceAndTerminalWriteFailureStaysClosed() + throws Exception { + var h = createdHarness(1); + assertDenied( + h.service() + .select( + h.context().toBuilder().setCharacterId(FIRST_ACTOR.toString()).build(), null, null), + CanonicalGameplayRosterSelectionService.Denial.INVALID_CONTEXT); + assertDenied( + h.service() + .select( + h.context().toBuilder().setRealmId(UUID.randomUUID().toString()).build(), + null, + null), + CanonicalGameplayRosterSelectionService.Denial.ROUTE_MISMATCH); + try { + TransactionSynchronizationManager.initSynchronization(); + assertDenied( + h.service().select(h.context(), null, null), + CanonicalGameplayRosterSelectionService.Denial.AMBIENT_TRANSACTION); + } finally { + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(h.sources(), h.client()); + for (int count : List.of(0, 1, 2)) { + var terminalFailure = createdHarness(count); + doThrow(new IllegalStateException("controlled missing terminal readback")) + .when(terminalFailure.client()) + .completeSelection(any(), any(), any()); + assertDenied( + terminalFailure.service().select(terminalFailure.context(), null, null), + count == 0 + ? CanonicalGameplayRosterSelectionService.Denial.NO_PLAYER_CREATED_ACTOR + : CanonicalGameplayRosterSelectionService.Denial.ROSTER_UNAVAILABLE); + } + } + + // These private-view/client-capability doubles establish orchestration, not authentication, + // genuine source issuance or SQL. The complete terminal values use the existing controlled + // CHARACTER_CREATE vector; actual Common/client grammar and physical owner proofs are separate. + private static CreatedHarness createdHarness(int actorCount) throws Exception { + java.nio.file.Path root = java.nio.file.Path.of("").toAbsolutePath(); + while (root != null && !java.nio.file.Files.exists(root.resolve("settings.gradle.kts"))) + root = root.getParent(); + if (root == null) + throw new IllegalStateException("Controlled CHARACTER_CREATE fixture unavailable"); + byte[] bytes = + java.nio.file.Files.readString( + root.resolve( + "services/account-service/src/testFixtures/resources/charactercreate/public-action.json")) + .strip() + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + var action = + net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec.decode(bytes); + var authored = action.mutation().authoredSource(); + var descriptor = + net.firedevops.firemud.common.publication.PlayerCreationDescriptor.parse( + authored.descriptor().canonicalJson()); + var identity = + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(authored.bindingId()) + .setAuthoredBindingDigest(authored.bindingDigest()) + .build(); + var target = + CanonicalGameplayRosterTarget.newBuilder() + .setTenantUuid(action.scope().tenantId()) + .setRealmUuid(action.target().realmId()) + .setWorldSlug(action.target().worldSlug()) + .setRealmSlug(action.target().realmSlug()) + .setGameInstanceUuid(action.target().gameInstanceId()) + .setCanonicalVersionUuid(action.target().versionId()) + .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) + .setPlayableStateScope( + net.firedevops.firemud.entitymanagement.v1.PlayableStateScope + .PLAYABLE_STATE_SCOPE_SHARED) + .setEntryPolicy( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) + .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) + .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) + .setActiveWorldEpoch(Long.parseLong(action.expectedVersion().activeLifecycleEpoch())) + .setPublishedPolicyDigest(authored.policy().contentDigest().substring(7)) + .setPublishedReleaseBundleRef("controlled-created-release") + .setAdmissionPointerSnapshotDigest("b".repeat(64)) + .setPublishedOwnerProofDigest("c".repeat(64)) + .build(); + var r = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute().route(); + var route = + new CanonicalPlayableTarget( + action.scope().targetNamespace(), + r.tenantSlug(), + UUID.fromString(target.getTenantUuid()), + target.getWorldSlug(), + r.worldDisplayName(), + UUID.fromString(target.getRealmUuid()), + target.getRealmSlug(), + r.realmDisplayName(), + r.gameSessionTenantId(), + r.gameInstanceId(), + UUID.fromString(target.getPlayableStateNamespaceUuid()), + "SHARED", + UUID.fromString(target.getGameInstanceUuid()), + UUID.fromString(target.getCanonicalVersionUuid()), + r.runtimeVersionId(), + target.getCatalogRevision(), + target.getPointerVersion(), + target.getAdmissionPointerSnapshotDigest(), + target.getActiveWorldEpoch(), + r.initialAdmissionRequestId(), + r.initialAdmissionRequestDigest(), + r.initialAdmissionOriginKind(), + r.expectedPriorPointerVersion(), + r.holdId(), + r.holdFence(), + r.holdBindingDigest(), + r.auditEventId(), + "sha256:" + target.getPublishedOwnerProofDigest(), + r.ownerProofOutcome(), + false, + r.ownerProofTerminalAt(), + "PLAYER_CREATED"); + var context = + context(route, UUID.randomUUID().toString()).toBuilder() + .setAccountId(action.target().accountId()) + .build(); + var source = mock(ResolvedPlayerCreatedRosterSource.class); + when(source.route()).thenReturn(route); + when(source.target()).thenReturn(target); + when(source.sourceIdentity()).thenReturn(identity); + var actors = + java.util.stream.IntStream.range(0, actorCount) + .mapToObj( + i -> + CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid((i == 0 ? FIRST_ACTOR : SECOND_ACTOR).toString()) + .setDisplayName(i == 0 ? "Created One" : "Created Two") + .setActorKind( + CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build()) + .toList(); + String digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + context.getAccountId(), target, identity, actors); + var receipt = + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(identity) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(context.getAccountId()) + .setTarget(target) + .setSnapshotUuid(SNAPSHOT.toString()) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .build(); + var roster = mock(VerifiedPlayerCreatedRoster.class); + when(roster.response()).thenReturn(receipt); + when(roster.resolvedSource()).thenReturn(source); + when(roster.originalSelection()) + .thenReturn( + CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + UUID.fromString(context.getRequestId()), + UUID.fromString(context.getAccountId()), + UUID.fromString(context.getSessionId()), + route.targetNamespace(), + target, + identity)); + when(roster.canonicalAccountUuid()).thenReturn(UUID.fromString(context.getAccountId())); + when(roster.target()).thenReturn(target); + when(roster.sourceIdentity()).thenReturn(identity); + when(roster.snapshotUuid()).thenReturn(SNAPSHOT); + when(roster.snapshotDigest()).thenReturn(digest); + when(roster.actors()).thenReturn(actors); + String operation = UUID.randomUUID().toString(); + String mutation = + net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec.mutationDigest( + action); + var original = + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(route.targetNamespace()) + .setOperationId(operation) + .setMutationDigest(mutation) + .build(); + var account = + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(route.targetNamespace()) + .setOperationId(operation) + .setMutationDigest(mutation) + .setCreateCharacterRequestId(UUID.randomUUID().toString()) + .setConnectScopeId("controlled-created-scope") + .setAuthenticatedAccountId(context.getAccountId()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(com.google.protobuf.ByteString.copyFrom(bytes)) + .setOriginalSourceReadback( + com.google.protobuf.ByteString.copyFromUtf8("controlled-source-readback")) + .build(); + var protection = + net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference.newBuilder() + .setProtectionId(UUID.randomUUID().toString()) + .setProtectionFence(1) + .build(); + var terminal = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest( + net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest + .newBuilder() + .setOriginal(original) + .setAccountProtection(protection) + .setGameSessionProtection( + protection.toBuilder().setProtectionId(UUID.randomUUID().toString())) + .setWorldProtection( + protection.toBuilder().setProtectionId(UUID.randomUUID().toString()))) + .setAccountOriginal(account) + .setOriginalAccountProtection( + com.google.protobuf.ByteString.copyFromUtf8("controlled-account-protection")) + .setOriginalGameSessionProtection( + com.google.protobuf.ByteString.copyFromUtf8("controlled-game-session-protection")) + .setOriginalWorldProtection( + com.google.protobuf.ByteString.copyFromUtf8("controlled-world-protection")) + .setEntityIntakeRequestId(UUID.randomUUID().toString()) + .setOutcome( + net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome + .ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1) + .setCompletedAt("2026-10-23T00:00:00Z") + .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)); + var references = new java.util.HashMap(); + for (var actor : actors) { + String actorOperation = UUID.randomUUID().toString(); + var actorTerminal = + terminal + .clone() + .setCharacterId(actor.getCharacterUuid()) + .setTerminalId(UUID.randomUUID().toString()) + .setOriginalRequest( + terminal.getOriginalRequest().toBuilder() + .setOriginal(original.toBuilder().setOperationId(actorOperation))) + .setAccountOriginal(account.toBuilder().setOperationId(actorOperation)); + var response = + CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(context.getRequestId()) + .setCanonicalAccountUuid(context.getAccountId()) + .setSelectedCharacterUuid(actor.getCharacterUuid()) + .setTarget(target) + .setSourceIdentity(identity) + .setSnapshot( + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(SNAPSHOT.toString()) + .setSnapshotDigest(digest)) + .setCreationOperationUuid(actorOperation) + .setMutationDigest(mutation) + .setTerminal(actorTerminal) + .build(); + var verified = mock(VerifiedPlayerCreatedCharacter.class); + when(verified.roster()).thenReturn(roster); + when(verified.response()).thenReturn(response); + when(verified.selectedCharacterUuid()).thenReturn(UUID.fromString(actor.getCharacterUuid())); + when(verified.creationOperationUuid()).thenReturn(UUID.fromString(actorOperation)); + when(verified.mutationDigest()).thenReturn(mutation); + when(verified.terminal()).thenReturn(response.getTerminal()); + references.put(UUID.fromString(actor.getCharacterUuid()), verified); + } + var routes = mock(CanonicalPlayerRouteReadService.class); + var publications = mock(CanonicalPublishedPlayerRouteReadService.class); + var preseeded = mock(CanonicalGameplayRosterClient.class); + var sources = mock(GameSessionCharacterCreatePublicSourceService.class); + var client = mock(CanonicalPlayerCreatedRosterClient.class); + when(routes.readCurrentTarget(route.canonicalTenantId())) + .thenAnswer( + call -> { + assertNoAmbientSql(); + return route; + }); + when(sources.resolvePlayerCreatedRosterSource(any())) + .thenAnswer( + call -> { + assertNoAmbientSql(); + return source; + }); + when(client.listPlayerCreatedRoster(source, context)) + .thenAnswer( + call -> { + assertNoAmbientSql(); + return roster; + }); + when(client.readSelectedPlayerCreatedCharacter(org.mockito.ArgumentMatchers.eq(roster), any())) + .thenAnswer( + call -> { + assertNoAmbientSql(); + PlayerExecutionContext selectedContext = call.getArgument(1); + return references.get(UUID.fromString(selectedContext.getCharacterId())); + }); + return new CreatedHarness( + new CanonicalGameplayRosterSelectionService( + routes, publications, preseeded, sources, client), + route, + context, + routes, + publications, + preseeded, + sources, + source, + client, + roster, + references.get(FIRST_ACTOR)); + } + + private static CanonicalPlayableTarget withPolicy(CanonicalPlayableTarget r, String policy) { + return new CanonicalPlayableTarget( + r.targetNamespace(), + r.tenantSlug(), + r.canonicalTenantId(), + r.worldSlug(), + r.worldDisplayName(), + r.realmId(), + r.realmSlug(), + r.realmDisplayName(), + r.gameSessionTenantId(), + r.gameInstanceId(), + r.playableStateNamespaceId(), + r.playableStateScope(), + r.canonicalGameInstanceId(), + r.canonicalVersionId(), + r.runtimeVersionId(), + r.catalogRevision(), + r.pointerVersion(), + r.admissionPointerSnapshotDigest(), + r.activeWorldEpoch(), + r.initialAdmissionRequestId(), + r.initialAdmissionRequestDigest(), + r.initialAdmissionOriginKind(), + r.expectedPriorPointerVersion(), + r.holdId(), + r.holdFence(), + r.holdBindingDigest(), + r.auditEventId(), + r.ownerProofDigest(), + r.ownerProofOutcome(), + r.positiveDurableAbort(), + r.ownerProofTerminalAt(), + policy); + } + + private static void assertNoAmbientSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private record CreatedHarness( + CanonicalGameplayRosterSelectionService service, + CanonicalPlayableTarget route, + PlayerExecutionContext context, + CanonicalPlayerRouteReadService routes, + CanonicalPublishedPlayerRouteReadService publications, + CanonicalGameplayRosterClient preseeded, + GameSessionCharacterCreatePublicSourceService sources, + ResolvedPlayerCreatedRosterSource source, + CanonicalPlayerCreatedRosterClient client, + VerifiedPlayerCreatedRoster roster, + VerifiedPlayerCreatedCharacter reference) {} + private static TestHarness harness(List actors) throws Exception { return harness(actors, false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java index fce1ca8962..afd9db7257 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java @@ -27,6 +27,7 @@ import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; @@ -473,6 +474,56 @@ void missingTransferOwnerStaysUnavailableForBothMethods() throws Exception { verifyNoInteractions(owner); } + @Test + void actualAdapterPreservesLargeCreatedOriginalAckAndConfirmationOverAuthenticatedSocket() + throws Exception { + // Complementary to Entity's actual-client fixture: real GS adapter, controlled durable owner. + var fixture = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection(NAMESPACE); + int defaultReceiveLimit = 4 * 1024 * 1024; + assertThat(fixture.original().getSerializedSize()).isGreaterThan(defaultReceiveLimit); + assertThat(fixture.acknowledgementRequest().getSerializedSize()) + .isGreaterThan(defaultReceiveLimit); + assertThat(fixture.confirmation().getSerializedSize()).isGreaterThan(defaultReceiveLimit); + String principal = "spiffe://firemud/ns/gameplay/sa/entity-management-service"; + var confirmed = + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(fixture.confirmation()); + when(owner.read(fixture.originalRequest())).thenReturn(fixture.original()); + when(owner.acknowledgeRetirement(fixture.acknowledgementRequest(), principal)) + .thenReturn(fixture.acknowledgement()); + when(owner.confirmRetirementAcknowledgement(fixture.confirmation(), principal)) + .thenReturn(confirmed); + start( + "server", + true, + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + try (var channel = channel("entity")) { + var createdStub = + stub(channel.channel()) + .withMaxInboundMessageSize( + CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES); + var original = createdStub.getCanonicalGameplayRosterReference(fixture.originalRequest()); + assertThat(original).isEqualTo(fixture.original()); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + original) + .getTerminal() + .toByteString()) + .isEqualTo(fixture.selected().getTerminal().toByteString()); + assertThat( + createdStub.acknowledgeCanonicalGameplayRosterRetirement( + fixture.acknowledgementRequest())) + .isEqualTo(fixture.acknowledgement()); + assertThat( + createdStub.confirmCanonicalGameplayRosterRetirementAcknowledgement( + fixture.confirmation())) + .isEqualTo(confirmed); + verify(owner).read(fixture.originalRequest()); + verify(owner).acknowledgeRetirement(fixture.acknowledgementRequest(), principal); + verify(owner).confirmRetirementAcknowledgement(fixture.confirmation(), principal); + } + } + private static net.firedevops.firemud.gamesession.v1 .CanonicalGameplayRosterRetirementAcknowledgementRequest retirementRequest() { @@ -509,19 +560,31 @@ private void start(String identity) throws Exception { } private void start(String identity, boolean ownerPresent) throws Exception { - start(identity, ownerPresent ? owner : null); + start(identity, ownerPresent, 0); + } + + private void start(String identity, boolean ownerPresent, int maxInboundBytes) throws Exception { + start(identity, ownerPresent ? owner : null, maxInboundBytes); } private void start(String identity, CanonicalGameplayRosterReferenceOwner availableOwner) throws Exception { + start(identity, availableOwner, 0); + } + + private void start( + String identity, CanonicalGameplayRosterReferenceOwner availableOwner, int maxInboundBytes) + throws Exception { @SuppressWarnings("unchecked") ObjectProvider route = mock(ObjectProvider.class); @SuppressWarnings("unchecked") ObjectProvider provider = mock(ObjectProvider.class); when(provider.getIfAvailable()).thenReturn(availableOwner); var serverIdentity = pki.identity(identity); + var serverBuilder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)); + if (maxInboundBytes > 0) serverBuilder.maxInboundMessageSize(maxInboundBytes); server = - NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + serverBuilder .sslContext( GrpcSslContexts.configure( SslContextBuilder.forServer( From 1cafc09ed07e1bb3823dd509cf0a5d3eed0f8cc7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:29:45 +1300 Subject: [PATCH 02/22] Receive typed created-roster owner evidence failures --- ...EntityPlayerCreatedRosterSourceClient.java | 19 ++++++ ...ayerCreatedRosterSourceClientMtlsTest.java | 63 ++++++++++++++++++- 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java index addac1fbc2..152b059cb4 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java @@ -87,6 +87,16 @@ public AuthenticatedSource read(ReadPlayerCreatedRosterSourceRequest request) { requireInitializedStub("Creation public source is unavailable") .withDeadlineAfter(5L, TimeUnit.SECONDS) .readPlayerCreatedRosterSource(request); + try { + return validateOwnerResponse(request, response); + } catch (RuntimeException invalidOwnerEvidence) { + throw new InvalidOwnerEvidenceException(invalidOwnerEvidence); + } + } + + private AuthenticatedSource validateOwnerResponse( + ReadPlayerCreatedRosterSourceRequest request, + ReadPlayerCreatedRosterSourceResponse response) { if (response == null || !response.getUnknownFields().asMap().isEmpty() || response.getSchemaVersion() != 1 @@ -337,6 +347,15 @@ private static RuntimeException invalid() { return EntityCharacterCreateBindings.invalid(); } + /** Authenticated owner response failed its closed value checks; caller input is separate. */ + public static final class InvalidOwnerEvidenceException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + private InvalidOwnerEvidenceException(RuntimeException cause) { + super("Game Session PLAYER_CREATED roster source evidence is invalid", cause); + } + } + /** Constructor custody establishes this transport read, never the other owners' authority. */ public static final class AuthenticatedSource { private final ReadPlayerCreatedRosterSourceResponse response; diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java index 6b51306dd9..281775cdc8 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java @@ -8,6 +8,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.io.IOException; import java.nio.file.Path; @@ -47,6 +48,7 @@ import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.testing.PlayerCreatedPublishedPolicyFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient.InvalidOwnerEvidenceException; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture; @@ -174,7 +176,10 @@ endpoints, new CommonGrpcClientProperties(), channels, NAMESPACE)) () -> new EntityPlayerCreatedRosterSourceClient( endpoints, controlled.clientProperties("entity"), channels, "Other")) - .isInstanceOf(RuntimeException.class); + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT)); } @Test @@ -235,7 +240,12 @@ void malformedAndChangedRequestSelectorsRefuseBeforeAnyReceivedRpc() throws Exce request.toBuilder().setReadRequestId(new UUID(0, 0).toString()).build(), request.toBuilder().setCatalogRevision(0).build(), request.toBuilder().setPointerVersion(0).build())) { - assertThatThrownBy(() -> client.read(changed)).isInstanceOf(RuntimeException.class); + assertThatThrownBy(() -> client.read(changed)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); } assertThat(owner.receivedRequests()).isEmpty(); } @@ -477,7 +487,9 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws good.toBuilder().setUnknownFields(unknown()).build())) { owner.respondWith(changed); assertThatThrownBy(() -> client.read(fixture.request())) - .isInstanceOf(RuntimeException.class); + .isInstanceOfSatisfying( + InvalidOwnerEvidenceException.class, + failure -> assertThat(failure.getCause()).isNotNull()); } assertThat(owner.receivedRequests()).isNotEmpty().allMatch(fixture.request()::equals); owner.respondWith(good); @@ -485,6 +497,51 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws } } + @Test + void authenticatedMalformedOwnerResponseKeepsGuardAndCodecCausesDistinctFromCallerInput() + throws Exception { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { + client.init(); + owner.respondWith(fixture.response().toBuilder().setSchemaVersion(2).build()); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOfSatisfying( + InvalidOwnerEvidenceException.class, + failure -> + assertThat(failure.getCause()) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + guard -> + assertThat(guard.getStatus().getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT))); + owner.respondWith( + fixture.response().toBuilder() + .setWorldLifecycleEvidence(ByteString.copyFromUtf8("not-json-world-evidence")) + .build()); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(InvalidOwnerEvidenceException.class) + .hasCauseInstanceOf(IllegalArgumentException.class); + assertThat(owner.receivedRequests()).containsExactly(fixture.request(), fixture.request()); + owner.respondWith(fixture.response()); + assertThat(client.read(fixture.request()).response()).isEqualTo(fixture.response()); + } + } + + @Test + void unavailableTransportIsNotReclassifiedAsInvalidOwnerEvidence() throws Exception { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { + client.init(); + owner.close(); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(owner.receivedRequests()).isEmpty(); + } + } + @Test void inboundTransportRejectsResponseBeyond32MiBBeforeSourceDecoding() throws Exception { try (var owner = controlled.owner("server"); From 8d341be996706954f7eb03071c3ad6d3e90abfd2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:55:18 +1300 Subject: [PATCH 03/22] docs: record created owner and roster component qualification --- .../entity-management-service/api-contracts.md | 4 ++-- .../entity-management-service/runtime-and-data.md | 2 +- .../game-session-service/api-contracts.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 10 ++++++---- .../player-access-and-session.md | 6 ++++-- 6 files changed, 15 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 9ec23dc680..fa8268029e 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -12,7 +12,7 @@ The prepared selected-source command and immutable receipt/digest reads remain s Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has manually composed certificate-guarded client, peer-interceptor, and read-adapter source definitions, but no automatic runtime handler, client, or service-bean registration. Default component scanning and legacy activation flags leave this family unregistered; [Runtime and Data](./runtime-and-data.md#implementation-status) owns its registration prerequisites. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. -Forward V1016 adds the created snapshot branch to the existing sealed-roster family. The created-roster API and storage changes in this isolated candidate remain unvalidated and do not register the service, handler, or caller; no new owner-custody, gameplay-admission, or activation proof is claimed. +Forward V1016 adds the created snapshot branch to the existing sealed-roster family. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The complete Game Session original-owner to Entity capture to Game Session receipt composition remains unrun; the API, handler and caller remain unregistered, and no production source-custody, Account-protection settlement, gameplay-admission or activation proof is established. The manually composed Account/Game Session evidence bridge currently supports `SHARED` only; the assignment bridge requires already canonical, non-nil UUID game-instance text under the existing bridge contract. Those bounded adapters supply no owner proof outside their declared scope. They do not narrow the passive assignment core, which supports `SHARED` and `ISOLATED` and hashes exact bounded opaque game-instance text without parsing or normalization. @@ -61,7 +61,7 @@ curl http://localhost:8080/ping - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. - `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – target `PRESEEDED_ONLY` pre-admission wire contract described in [Implementation Status](#implementation-status). Source models and manually composed certificate-guarded handler, peer-interceptor, client, and read-adapter source definitions are present; none of these or callers is registered. The result is discovery evidence, not actor admission or a session-binding shortcut. -- `CanonicalGameplayRosterService.ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter` – distinct non-admitting `PLAYER_CREATED` reads with the target contract described in [Player-created roster and selected character](#player-created-roster-and-selected-character). They do not change either preseeded method; this candidate's created-roster path remains unvalidated and unregistered. +- `CanonicalGameplayRosterService.ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter` – distinct non-admitting `PLAYER_CREATED` reads with the target contract described in [Player-created roster and selected character](#player-created-roster-and-selected-character). They do not change either preseeded method. Controlled component and isolated backend qualification is recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation); the full original-owner composition remains unrun and this path remains unregistered. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains 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. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `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/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 3b8f900aaa..3f1cef7553 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -23,7 +23,7 @@ This document defines Entity Management’s runtime model, persistence ownership - Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude actors carrying canonical `tenant_uuid` provenance even when their status becomes `QUARANTINED`, including updates and condition expiry. Legitimate legacy/quarantined rows with null canonical tenant provenance retain legacy behavior. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The services and certificate-guarded client/read-adapter source definitions are manually composed and unregistered; neither default scanning nor an optional flag registers them. No authenticated production transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). -- Forward V1016 adds the immutable `PLAYER_CREATED` source identity and created-receipt branch to the shared snapshot family while preserving the `PRESEEDED_ONLY` guards and budgets. This isolated candidate's created-roster changes remain unvalidated and unregistered; the source/selected owner chain does not establish production custody, actor admission or `PLAY`. +- Forward V1016 adds the immutable `PLAYER_CREATED` source identity and created-receipt branch to the shared snapshot family while preserving the `PRESEEDED_ONLY` guards and budgets. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The complete Game Session original-owner to Entity capture to Game Session receipt composition remains unrun and unregistered; production source custody, Account-protection settlement, production PKI, actor admission and `PLAY` remain unproved. - Sealed canonical roster snapshots and their actor references are immutable Entity-owned records: append a new snapshot/reference set when the canonical target or roster changes, preserving the existing deletion guards. The [family retention declaration](#sealed-canonical-roster-retention) defines its ADR 0163 obligations. Before any handler, service, or alternative snapshot writer is registered, owner-local disposal must be proved with authoritative terminal/reference/hold carriers and compatible configured horizons. Local carrier and disposal source is prepared with focused qualification; genuine producer composition and registration remain unavailable. See the [implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). This does not set a numeric horizon, authorize deletion, or establish indefinite retention. The current passive writer has no registered production call chain; its pending implementation obligation is tracked under #2967 and is not completion or merge proof. - Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 20323b7f20..8f25768889 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 @@ This document mixes live and target-state control-plane surfaces. Current live b Read the pause/status/recovery APIs below as the target-state contract unless the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) explicitly records them as live. -The isolated created-owner consumer candidate contains Game Session migrations V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage. V1020's created-receipt branch does not supply either missing prerequisite. The created consumer and transfer semantics below remain unvalidated in this candidate, unregistered, and are not evidence of production custody or admission; the independently qualified public character-creation source-read contract above remains a separate boundary. +The current unregistered created-owner consumer composition contains Game Session migrations V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage; V1020's created-receipt branch does not supply either missing prerequisite. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [player-created roster consumer tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation). The full Game Session original-owner to Entity capture to Game Session receipt and transfer composition remains unrun; production source custody, real Account-protection settlement, production PKI, registration, activation and public admission remain unproved. The independently qualified public character-creation source-read contract above remains a separate boundary. For script transitions, the live boundary includes the exact `scriptPinEpoch` and an atomic current-pin/request-result ledger commit; bounded authoritative history readback and append-only rollout history remain target-state gaps. Target pin and rollback requests require the explicit tagged `expectedCurrentPin` precondition defined in the [Scripting Control Plane API](../../system-architecture-scripting-control-plane-api.md): exactly `UNCONDITIONAL`, `EXPECT_UNPINNED`, or `EXPECT_EPOCH(scriptPinEpoch)`, with the complete tag/value included in the normalized digest. Missing/unknown tags fail validation; a both-absent tuple for a never-pinned instance is valid semantic `UNPINNED` and matches only `EXPECT_UNPINNED`; a partial tuple is invalid owner state, cannot satisfy `EXPECT_UNPINNED` or `EXPECT_EPOCH`, and is rejected/fails closed even for an `UNCONDITIONAL` request. Missing or unreadable authority is not `UNPINNED` and remains unavailable. `UNCONDITIONAL` is only the explicit `platformAdmin` break-glass repair branch with the matrix's `privileged_control` authorization; it skips only current-pin comparison and does not bypass coherent owner state, readiness, or other validation. See [Rollout and Rollback](../../system-architecture-scripting-rollout-and-rollback.md#pin-compare-and-set-preconditions) for the owner semantics. A valid precondition mismatch is deterministic and non-mutating and follows the existing idempotency/history semantics. 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 f61d8c237b..ec2f493e23 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -43,7 +43,7 @@ The sections below define the target-state runtime contract. Current implementat - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). -- The isolated created-owner consumer candidate includes Game Session migration V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage. V1020's created-receipt fields do not supply either missing prerequisite. The created consumer and receipt transfer path remain unvalidated and unregistered in this candidate; no UUID-runtime, protection, authenticated-custody, or gameplay-admission proof is claimed. +- The current unregistered created-owner consumer composition includes Game Session migrations V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage; V1020's created-receipt fields do not supply either missing prerequisite. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [player-created roster consumer tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation). The full Game Session original-owner to Entity capture to Game Session receipt and transfer composition remains unrun; UUID runtime, real Account-protection settlement, production PKI, authenticated production custody, registration, activation and gameplay admission remain unproved. - The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. ## Runtime Details diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index accdfafc8b..a354012f51 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -6,11 +6,13 @@ This is a non-normative implementation tracker for gameplay rules, entities, and ## Current Status -### Player-created owner and roster candidate +### Player-created owner and roster preparation -The local, unregistered candidate adds Entity's `CHARACTER_CREATE` terminal writer and source-bound created-roster capture/readback, together with Common evidence and the immediate Game Session receipt consumer. Entity V1015 and V1016 retain the creation terminal and created snapshot branch; Game Session V1020 retains the distinct created receipt without changing the preseeded branch. Canonical behavior belongs to the [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) and [sealed roster storage](../../architecture/microservices/entity-management-service/runtime-and-data.md#player-created-snapshot-storage). +The unregistered composition implements Entity's `CHARACTER_CREATE` terminal writer and source-bound created-roster capture/readback, together with Common evidence and the immediate Game Session receipt consumer. Entity V1015 and V1016 retain the creation terminal and created snapshot branch; Game Session V1020 retains the distinct created receipt while preserving the strict preseeded branch. Canonical behavior belongs to the [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) and [sealed roster storage](../../architecture/microservices/entity-management-service/runtime-and-data.md#player-created-snapshot-storage). -This candidate has not yet passed its own consolidated qualification. Earlier source and mixed-worktree results retain their original attribution and do not qualify this isolated composition. Game Session UUID runtime and creation-protection storage remain separate receiving work; actual original Game Session creation-owner → Entity capture → Game Session receipt composition, genuine source custody, runtime registration, Account protection and settlement, region/execution handoffs, public admission and activation remain open. Controlled upstream facts and component or socket fixtures cannot close those gaps. +R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases with affected static analysis, formatting and documentation checks. Unchanged Common and broader Game Session physical proof retain R86 attribution: 1,020 Common unit cases, 364 Game Session PostgreSQL cases and 36 cross-service cases. R86's earlier 396 Entity and 2,565 Game Session unit counts are superseded by the new executions, rather than credited as fresh runs. Native Entity proof includes the actual retained creation writer feeding authenticated source-bound snapshot capture; socket fixtures use controlled PKI and owner facts, including a complete 5 MiB terminal rather than physical proof at every maximum purpose bound. After the documentation-only parent carry, R93 rebuilds fresh images at `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project inspection confirms no remaining containers, networks or volumes. The subsequent public-parent documentation carry is code-identical. This validates controlled components, storage, packaging and the isolated backend baseline; it does not exercise a registered production created-actor flow. + +The complete real Game Session original owner → Entity capture → Game Session receipt composition remains unrun. Existing controlled historical OPEN evidence is preseeded and lacks the coherent retained created-source candidate, original tuple/redemption/descriptor, sealed policy and World composition; a protobuf or changed policy cannot supply that custody. Fresh Human OPEN still requires the unavailable Account protection and settlement composition. Game Session UUID runtime and creation-protection storage remain separate receiving work. Genuine source custody, production PKI, registration, region/execution handoffs, public admission, activation and the genuine playable journey remain open; controlled upstream facts and component or socket fixtures do not close those gaps. ### Canonical sealed roster retention prerequisite @@ -58,7 +60,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for sealed-roster retention and exact canonical actor-repository read isolation. See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, created-roster handling, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Policy/descriptor/template resolution, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, complete created-roster owner/consumer composition, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | 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 d2cad92aed..496b4657f2 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,9 +6,11 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -### Player-created roster consumer candidate +### Player-created roster consumer preparation -The local, unregistered candidate consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. Consolidated proof of this isolated candidate is pending. Its V1020 receipt storage does not include the separate V1018 UUID runtime or V1019 creation-protection owners, and supplies no Account protection, admission, activation or genuine playable-journey proof. Qualified public source-read results below retain their original source attribution. +The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. + +The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the controlled qualification and limits: R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases; unchanged Common and broader Game Session physical/cross-service proof retain their R86 attribution. After the documentation-only parent carry, R93 freshly rebuilds `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code, passes held Gateway/Telnet denial and the isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline, and completes authenticated teardown with independent exact-project resource absence. Later parent documentation changes preserve that code. The complete real Game Session original owner → Entity capture → Game Session receipt composition remains unrun; genuine source custody, Account protection/settlement, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. ### Public character-creation and created-roster source preparation From c9bd1cebabcbd5c9d2f37084f8a728666d6c9674 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:32:55 +1300 Subject: [PATCH 04/22] test: compose player-created roster owners over authenticated transports --- .../build.gradle.kts | 3 + ...trolledPlayerCreatedOwnerStoreFixture.java | 846 +++++++++++++ .../game-session-service/build.gradle.kts | 4 + ...RosterOwnerCompositionIntegrationTest.java | 346 ++++++ ...lledPlayerCreatedOriginalOwnerFixture.java | 1059 +++++++++++++++++ 5 files changed, 2258 insertions(+) create mode 100644 services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java create mode 100644 services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java diff --git a/services/entity-management-service/build.gradle.kts b/services/entity-management-service/build.gradle.kts index ccf06239d0..0531a67f6c 100644 --- a/services/entity-management-service/build.gradle.kts +++ b/services/entity-management-service/build.gradle.kts @@ -13,6 +13,9 @@ firemudJooq { dependencies { testFixturesCompileOnly(libs.spotbugs.annotations) + testFixturesImplementation(libs.jooq) + testFixturesImplementation(libs.spring.boot.starter.jdbc) + testFixturesImplementation(libs.micrometer.core) implementation(project(":common-platform-core")) implementation(project(":common-security")) implementation(libs.spring.boot.starter.cache) diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java new file mode 100644 index 0000000000..0055ca400c --- /dev/null +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java @@ -0,0 +1,846 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import com.google.protobuf.ByteString; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection.AuthoredCore; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient.AuthenticatedSource; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CanonicalGameplayRosterRetentionRepository; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRecoveryService; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRetentionPolicy; +import net.firedevops.firemud.entitymanagement.service.impl.CanonicalGameplayRosterGrpcAdapter; +import net.firedevops.firemud.entitymanagement.service.impl.CanonicalGameplayRosterRecoveryGrpcAdapter; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture.WireFixture; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; +import net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Controlled PostgreSQL composition for the unregistered created-roster owner. Its upstream + * publication/source client is a real configured mTLS client; Account, Game Session creation + * protection, and World evidence used only by {@link #createActor} are controlled proof inputs. + */ +public final class ControlledPlayerCreatedOwnerStoreFixture { + private final WireFixture wireFixture; + private final EntityPlayerCreatedRosterSourceClient sourceClient; + private final EntityEmptySelectedSourceIntakeRepository sourceIntakes; + private final EntityCharacterCreateRepository characterCreateRepository; + private final CanonicalGameplayRosterRetentionRepository retentionRepository; + private final EntityPlayerCreatedRosterSnapshotRepository snapshotRepository; + private final EntityPlayerCreatedRosterService rosterService; + private final CanonicalGameplayRosterRecoveryService recoveryService; + private final CanonicalGameplayRosterGrpcAdapter rosterAdapter; + private final CanonicalGameplayRosterRecoveryGrpcAdapter recoveryAdapter; + private EntityEmptySelectedSourceIntakeReceipt sourceReceipt; + + public ControlledPlayerCreatedOwnerStoreFixture( + DSLContext dsl, + PlatformTransactionManager transactionManager, + String namespace, + WireFixture wireFixture, + EntityPlayerCreatedRosterSourceClient sourceClient, + GameSessionCanonicalGameplayRosterOwnerReadClient originalOwnerClient, + Clock clock, + CanonicalGameplayRosterRetentionPolicy retentionPolicy) { + Objects.requireNonNull(dsl, "dsl"); + Objects.requireNonNull(transactionManager, "transactionManager"); + Objects.requireNonNull(namespace, "namespace"); + this.wireFixture = Objects.requireNonNull(wireFixture, "wireFixture"); + this.sourceClient = Objects.requireNonNull(sourceClient, "sourceClient"); + Objects.requireNonNull(clock, "clock"); + Objects.requireNonNull(retentionPolicy, "retentionPolicy"); + Objects.requireNonNull(originalOwnerClient, "originalOwnerClient"); + if (!namespace.equals(wireFixture.request().getTargetNamespace())) { + throw new IllegalArgumentException( + "Controlled source namespace differs from owner namespace"); + } + + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + transactions.setReadOnly(false); + TransactionOperations transactionOperations = transactions; + sourceIntakes = new EntityEmptySelectedSourceIntakeRepository(dsl); + characterCreateRepository = new EntityCharacterCreateRepository(dsl, clock); + retentionRepository = new CanonicalGameplayRosterRetentionRepository(dsl); + snapshotRepository = new EntityPlayerCreatedRosterSnapshotRepository(dsl, transactionManager); + rosterService = + new EntityPlayerCreatedRosterService( + namespace, + sourceClient, + originalOwnerClient, + snapshotRepository, + retentionRepository, + transactionOperations); + recoveryService = + new CanonicalGameplayRosterRecoveryService( + retentionRepository, originalOwnerClient, transactionOperations, retentionPolicy); + rosterAdapter = + new CanonicalGameplayRosterGrpcAdapter( + null, null, rosterService, new SimpleMeterRegistry()); + recoveryAdapter = new CanonicalGameplayRosterRecoveryGrpcAdapter(recoveryService); + } + + /** Performs a fresh configured mTLS read; only the returned client capability is accepted. */ + public AuthenticatedSource readAuthenticatedSource() { + AuthenticatedSource source = sourceClient.read(wireFixture.request()); + if (!source.response().equals(wireFixture.response())) { + throw new IllegalStateException("Configured controlled source returned different evidence"); + } + return source; + } + + /** + * Uses the actual Entity creation writer to allocate one PLAYER_CREATED actor and persist its + * complete COMMITTED terminal. The owner protection inputs here are controlled evidence. + */ + public synchronized EntityCharacterCreateTerminal createActor( + UUID account, UUID operation, String displayName) throws Exception { + EntityCharacterCreateBindings.id(Objects.requireNonNull(account, "account").toString()); + EntityCharacterCreateBindings.id(Objects.requireNonNull(operation, "operation").toString()); + AuthenticatedSource source = readAuthenticatedSource(); + var projection = source.authored().projections().getFirst(); + String authoredName = new AuthoredCore(projection.core().canonicalJson()).displayName(); + if (!Objects.equals(authoredName, displayName)) { + throw new IllegalArgumentException("Display name must match the authenticated authored core"); + } + DraftCommitBinding selected = + GameDesignPublicationOperationBinding.fromStored( + source.publishedPolicySet().operationBytes()) + .account() + .input() + .selection() + .selectedCommit(); + if (!selected.target().canonicalTenantId().equals(source.target().tenantUuid()) + || !selected.target().canonicalVersionId().equals(source.target().canonicalVersionUuid())) { + throw new IllegalStateException("Controlled selected binding differs from source target"); + } + if (sourceReceipt == null) { + var intake = + ControlledIntakeBuilder.create( + "1", selected, source.response().getRequest().getTargetNamespace()); + var inputs = intake.inputs(); + String digest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + inputs.authorizationBinding().targetNamespace(), + inputs.authorizationBinding(), + inputs.worldInventoryReadEvidence().request().freezeEvidence()); + sourceReceipt = sourceIntakes.retainFresh(inputs, digest); + } + EntityCharacterCreateProofs proof = createProof(sourceReceipt, account, operation, source); + return characterCreateRepository.settle(proof, null); + } + + public CanonicalGameplayRosterGrpcAdapter rosterAdapter() { + return rosterAdapter; + } + + public CanonicalGameplayRosterRecoveryGrpcAdapter recoveryAdapter() { + return recoveryAdapter; + } + + public EntityPlayerCreatedRosterService rosterService() { + return rosterService; + } + + public CanonicalGameplayRosterRecoveryService recoveryService() { + return recoveryService; + } + + public CanonicalGameplayRosterRetentionRepository retentionRepository() { + return retentionRepository; + } + + public EntityPlayerCreatedRosterSnapshotRepository snapshotRepository() { + return snapshotRepository; + } + + public EntityCharacterCreateRepository characterCreateRepository() { + return characterCreateRepository; + } + + public WireFixture wireFixture() { + return wireFixture; + } + + private static EntityCharacterCreateProofs createProof( + EntityEmptySelectedSourceIntakeReceipt entitySource, + UUID accountId, + UUID operationId, + AuthenticatedSource rosterSource) + throws Exception { + CharacterCreateOperatorAction action = + rosterSourceAction(entitySource, accountId, rosterSource); + byte[] actionBytes = CharacterCreateOperatorActionCodec.encode(action); + Instant readAt = action.expectedVersion().evaluatedAt().plusSeconds(1); + var original = + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace(entitySource.targetNamespace()) + .setOperationId(operationId.toString()) + .setCreateCharacterRequestId(UUID.randomUUID().toString()) + .setConnectScopeId("Controlled.Owner.Scope-Exact") + .setAuthenticatedAccountId(accountId.toString()) + .setPurpose("CHARACTER_CREATE") + .setOriginalAction(ByteString.copyFrom(actionBytes)) + .setMutationDigest(CharacterCreateOperatorActionCodec.mutationDigest(action)) + .setOriginalSourceReadback( + ByteString.copyFromUtf8("controlled-upstream-source-readback")) + .build(); + ReadOriginalCharacterCreateRequest reference = + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace(entitySource.targetNamespace()) + .setOperationId(operationId.toString()) + .setMutationDigest(original.getMutationDigest()) + .build(); + CharacterCreateProtectionReference accountProtection = protectionReference(); + CharacterCreateProtectionReference gameSessionProtection = protectionReference(); + CharacterCreateProtectionReference worldProtection = protectionReference(); + var request = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal(reference) + .setAccountProtection(accountProtection) + .setGameSessionProtection(gameSessionProtection) + .setWorldProtection(worldProtection) + .build(); + var account = + ReadOriginalCharacterCreateProtectionResponse.newBuilder() + .setOriginal(original) + .setAccountProtectionId(accountProtection.getProtectionId()) + .setAccountProtectionFence(accountProtection.getProtectionFence()) + .setAcquiredAt(readAt.toString()) + .setOriginalMembershipSnapshot(ByteString.copyFromUtf8("controlled-membership")) + .setOriginalEntitlementSnapshot(ByteString.copyFromUtf8("controlled-entitlement")) + .build(); + var gameSession = + new GameSessionCharacterCreateProtectionReader.Readback( + account, + gameSessionProtection, + readAt.plusSeconds(1).toString(), + ByteString.copyFromUtf8("controlled-Game-Session-protection-readback")); + var world = + WorldCharacterCreateLifecycleProtection.newBuilder() + .setAccountProtection(account) + .setWorldProtectionId(worldProtection.getProtectionId()) + .setWorldProtectionFence(worldProtection.getProtectionFence()) + .setAcquiredAt(readAt.plusSeconds(2).toString()) + .setOriginalLifecycleEvidence( + ByteString.copyFrom( + creationLifecycleEvidence(rosterSource.world(), operationId).canonicalBytes())) + .build(); + return new EntityCharacterCreateProofs( + request, original, account, gameSession, world, entitySource); + } + + /** + * Rebinds only the controlled World lifecycle read correlation to the creation operation. The + * authenticated source's target, complete launch binding, and lifecycle facts remain intact. + */ + private static WorldCanonicalInstanceLifecycleEvidence creationLifecycleEvidence( + WorldCanonicalInstanceLifecycleEvidence source, UUID operationId) { + var sourceRequest = source.request(); + var creationRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + sourceRequest.schemaVersion(), + operationId, + sourceRequest.targetNamespace(), + sourceRequest.canonicalTenantId(), + sourceRequest.worldSlug(), + sourceRequest.canonicalGameInstanceId(), + sourceRequest.playableStateNamespaceId(), + sourceRequest.playableStateScope(), + sourceRequest.publicProduction(), + sourceRequest.controlPlaneRequestId(), + sourceRequest.canonicalVersionId(), + sourceRequest.expectedDescriptorRequestDigest(), + sourceRequest.expectedDescriptorResultDigest(), + sourceRequest.expectedReleaseAttestationDigest()); + return new WorldCanonicalInstanceLifecycleEvidence( + creationRequest, + source.launchBinding(), + source.startLocation(), + source.runtimeRoomInstanceId(), + source.lifecycleStatus(), + source.lifecycleEpoch(), + source.rowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + source.operationalRegionAssignments()); + } + + private static CharacterCreateProtectionReference protectionReference() { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(UUID.randomUUID().toString()) + .setProtectionFence(1L) + .build(); + } + + private static CharacterCreateOperatorAction rosterSourceAction( + EntityEmptySelectedSourceIntakeReceipt entitySource, + UUID accountId, + AuthenticatedSource source) { + var target = source.target(); + var request = source.response().getRequest(); + var catalog = source.response().getCatalog(); + var pointer = source.response().getPointer(); + var projection = source.authored().projections().getFirst(); + DraftCommitBinding sourceSelected = + GameDesignPublicationOperationBinding.fromStored( + source.publishedPolicySet().operationBytes()) + .account() + .input() + .selection() + .selectedCommit(); + if (!entitySource.targetNamespace().equals(request.getTargetNamespace()) + || !entitySource.canonicalTenantId().equals(target.tenantUuid()) + || !entitySource.canonicalVersionId().equals(target.canonicalVersionUuid()) + || !entitySource.selectedCommitId().equals(projection.selectedCommitId()) + || !sourceSelected.commitId().equals(projection.selectedCommitId()) + || !sourceSelected.digest().equals(projection.selectedCommitDigest()) + || !entitySource.authorizationBinding().selected().equals(sourceSelected)) { + throw new IllegalArgumentException( + "Controlled Entity writer fixture does not match authenticated source binding"); + } + Instant pointerUpdatedAt = EntityCharacterCreateBindings.instant(pointer.getUpdatedAt()); + return new CharacterCreateOperatorAction( + new CharacterCreateOperatorAction.Scope( + request.getTargetNamespace(), + target.tenantUuid().toString(), + target.playableStateNamespaceId().toString(), + CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), + new CharacterCreateOperatorAction.Target( + accountId.toString(), + target.realmUuid().toString(), + target.worldSlug(), + target.realmSlug(), + target.gameInstanceUuid().toString(), + target.canonicalVersionUuid().toString()), + new CharacterCreateOperatorAction.ExpectedVersion( + Long.toString(target.catalogRevision()), + Long.toString(target.pointerVersion()), + Long.toString(target.activeWorldEpoch()), + pointerUpdatedAt.plusSeconds(1), + pointerUpdatedAt.plusSeconds(301)), + new CharacterCreateOperatorAction.Mutation( + "CHARACTER_CREATE", + "PLAYER_CREATED", + new CharacterCreateOperatorAction.Catalog( + target.tenantUuid().toString(), + catalog.getTenantSlug(), + target.worldSlug(), + catalog.getWorldDisplayName(), + target.realmUuid().toString(), + target.realmSlug(), + catalog.getRealmDisplayName(), + catalog.getVisible(), + catalog.getPublicProduction(), + catalog.getStateScope(), + target.playableStateNamespaceId().toString(), + catalog.getCharacterCreationPolicy(), + Long.toString(target.catalogRevision())), + new CharacterCreateOperatorAction.Pointer( + target.tenantUuid().toString(), + target.realmUuid().toString(), + target.worldSlug(), + target.realmSlug(), + pointer.getAdmissionState(), + target.gameInstanceUuid().toString(), + Long.toString(target.pointerVersion()), + Long.toString(target.catalogRevision()), + pointerUpdatedAt), + authoredSource(projection), + "{}"), + CharacterCreateOperatorAction.AuditReason.ABSENT); + } + + private static CharacterCreateOperatorAction.AuthoredSource authoredSource( + AuthoredInitialActorCoreProjection projection) { + var policy = projection.policy(); + return new CharacterCreateOperatorAction.AuthoredSource( + AuthoredInitialActorCoreProjection.SCHEMA, + projection.bindingId().toString(), + projection.bindingDigest(), + projection.canonicalTenantId().toString(), + projection.canonicalVersionId().toString(), + projection.worldSourceOperationId().toString(), + projection.worldSourceEvidenceDigest(), + projection.worldSlug(), + projection.publicationWorkflowId(), + projection.selectedCommitId().toString(), + projection.selectedCommitDigest(), + new CharacterCreateOperatorAction.Policy( + policy.commitId().toString(), + policy.revisionId().toString(), + policy.logicalRevisionId(), + policy.canonicalJson(), + policy.contentDigest()), + new CharacterCreateOperatorAction.Core(projection.core().canonicalJson()), + new CharacterCreateOperatorAction.Descriptor( + projection.descriptor().canonicalJson(), projection.descriptor().digest()), + authoredRule(projection.disposition()), + authoredRule(projection.safeFeedback())); + } + + private static CharacterCreateOperatorAction.Rule authoredRule( + AuthoredInitialActorCoreProjection.RuleDefinition rule) { + return new CharacterCreateOperatorAction.Rule( + rule.key(), + rule.definitionJson(), + rule.definitionDigest(), + rule.sourceCommitId().toString(), + rule.sourceCommitDigest(), + rule.revisionId().toString(), + rule.revisionOrder()); + } + + /** Small typed fixture builder for a controlled fresh Entity owner source-intake receipt. */ + private static final class ControlledIntakeBuilder { + static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); + private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + private ControlledIntakeBuilder() {} + + public static Fixture create( + String sourceEpoch, DraftCommitBinding selected, String namespace) { + Objects.requireNonNull(selected, "selected"); + Objects.requireNonNull(namespace, "namespace"); + var target = selected.target(); + var scope = + new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + namespace, + OPERATION, + FENCE, + INTAKE_REQUEST, + ACTOR, + selected); + TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); + SelectedOwnerIntakeAuthorizationBinding authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(scope, templateSnapshot), accountSources(target)); + WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected, namespace); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(namespace, authorization, freeze); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + return new Fixture( + authorization, + freeze, + worldEvidence, + new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, String sourceEpoch) { + var declaration = + EntityAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); + String declarationPayload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration); + DraftCommitBinding authored = authoredBinding(declarationPayload, selected.target()); + TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind + .DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, + sourceEpoch, + authored.commitId(), + GENESIS_RECEIPT, + List.of(), + List.of(ownerDeclaration)); + } + + private static DraftCommitBinding authoredBinding(String payload, TargetProof target) { + return DraftCommitBinding.create( + target, + id("51515151-5151-4151-8151-515151515151"), + id("52525252-5252-4252-8252-525252525252"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("53535353-5353-4353-8353-535353535353"), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + target.canonicalVersionId().toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, + TemplateConfigSourceSnapshot templateSnapshot) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> + new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + GENESIS_RECEIPT.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) + .canonicalBytes(); + default -> + throw new IllegalArgumentException("Unsupported source family fixture: " + family); + }; + } + + private static List accountSources(TargetProof target) { + String tenant = target.canonicalTenantId().toString(); + return List.of( + source(SourceKind.TENANT, tenant, "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + tenant, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected, String namespace) { + var target = selected.target(); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + target.canonicalTenantId(), + target.canonicalVersionId(), + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var target = request.accountBinding().input().selection().selectedCommit().target(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + target.canonicalTenantId(), + target.canonicalVersionId(), + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + public record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence worldEvidence, + SelectedOwnerEmptySourceInputs inputs) {} + } +} diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index df2f962a85..fd3c97aa58 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -70,12 +70,16 @@ dependencies { runtimeOnly(libs.jjwt.impl) runtimeOnly(libs.jjwt.jackson) testFixturesImplementation(project(":entity-management-service")) + testFixturesApi(testFixtures(project(":entity-management-service"))) testFixturesImplementation(project(":game-logic-service")) testFixturesImplementation(project(":social-groups-service")) testFixturesImplementation(project(":world-management-service")) testFixturesImplementation(testFixtures(project(":common-test-support"))) + testFixturesImplementation(testFixtures(project(":common-platform-core"))) testFixturesImplementation(project(":common-security")) testFixturesImplementation(project(":common-data-runtime")) + testFixturesImplementation(libs.jooq) + testFixturesImplementation(libs.flyway.core) testFixturesImplementation(platform(libs.spring.boot.dependencies)) testFixturesImplementation("com.fasterxml.jackson.core:jackson-databind") testFixturesImplementation(libs.spring.boot.starter.actuator) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java new file mode 100644 index 0000000000..1b38166869 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -0,0 +1,346 @@ +package net.firedevops.firemud.gamesession.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.BindableService; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.entitymanagement.charactercreate.ControlledPlayerCreatedOwnerStoreFixture; +import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient; +import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRetentionPolicy; +import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient; +import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository.SelectionOutcome; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferencePolicy; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; +import net.firedevops.firemud.gamesession.testing.ControlledPlayerCreatedOriginalOwnerFixture; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real owner stores and authenticated transports with explicitly controlled upstream authority. + * This does not establish genuine Account ingress, production PKI, registration or player + * admission. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class PlayerCreatedRosterOwnerCompositionIntegrationTest { + private static final String NAMESPACE = "test"; + private static final Duration RETENTION = Duration.ofSeconds(20); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @TempDir Path directory; + + @Test + void actualCreatedTerminalCrossesAuthenticatedOwnersAndReplaysTheImmutableOriginal() + throws Exception { + try (var owners = new Owners(directory)) { + UUID account = UUID.randomUUID(); + UUID creation = UUID.randomUUID(); + String displayName = + new net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection + .AuthoredCore( + owners + .gs + .wireFixture() + .authored() + .projections() + .getFirst() + .core() + .canonicalJson()) + .displayName(); + var terminal = owners.entity.createActor(account, creation, displayName); + assertThat(terminal.getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED); + var source = + owners + .gs + .sourceReader() + .resolvePlayerCreatedRosterSource(owners.gs.wireFixture().request()); + var context = owners.context(account); + owners.roster.reserveSelectionInput(source, context, null, null, null); + var menu = owners.roster.listPlayerCreatedRoster(source, context); + assertThat(menu.actors()).hasSize(1); + assertThat(menu.actors().getFirst().getDisplayName()).isEqualTo(displayName); + assertThat(menu.actors().getFirst().getCharacterUuid()).isEqualTo(terminal.getCharacterId()); + var selectedContext = context.toBuilder().setCharacterId(terminal.getCharacterId()).build(); + var selected = owners.roster.readSelectedPlayerCreatedCharacter(menu, selectedContext); + assertThat(selected.creationOperationUuid()).isEqualTo(creation); + assertThat(selected.terminal()).isEqualTo(terminal); + owners.roster.completeSelection(source, context, SelectionOutcome.SELECTED); + + var retained = owners.gs.referenceOwner().read(menu.originalSelection()); + assertThat(CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(retained)) + .isEqualTo(menu.response()); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + retained)) + .isEqualTo(selected.response()); + var originalBytes = retained.toByteArray(); + // Actual current source is still the issued target: retirement must refuse. + assertThat(owners.gs.referenceOwner().retireTarget(menu.originalSelection())).isFalse(); + var replay = owners.roster.listPlayerCreatedRoster(source, context); + assertThat(replay.response()).isEqualTo(menu.response()); + assertThat( + owners.roster.readSelectedPlayerCreatedCharacter(replay, selectedContext).response()) + .isEqualTo(selected.response()); + assertThat(owners.gs.referenceOwner().read(menu.originalSelection()).toByteArray()) + .containsExactly(originalBytes); + + // A caller-selected actor absent from the actual frozen menu cannot become a receipt. + assertThatThrownBy( + () -> + owners.roster.readSelectedPlayerCreatedCharacter( + replay, + context.toBuilder().setCharacterId(UUID.randomUUID().toString()).build())) + .isInstanceOf(IllegalArgumentException.class); + assertThat(owners.gs.referenceOwner().read(menu.originalSelection()).toByteArray()) + .containsExactly(originalBytes); + var foreignContext = + context.toBuilder() + .setRequestId(UUID.randomUUID().toString()) + .setRealmId(UUID.randomUUID().toString()) + .build(); + assertThatThrownBy(() -> owners.roster.listPlayerCreatedRoster(source, foreignContext)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(owners.gs.dsl().fetchCount(DSL.table("game_session_canonical_roster_selection"))) + .isEqualTo(1); + assertThat( + owners.entityDsl.fetchCount(DSL.table("entity_canonical_roster_original_selections"))) + .isEqualTo(1); + } + } + + private static final class Owners implements AutoCloseable { + private final ArrayDeque resources = new ArrayDeque<>(); + private final DriverManagerDataSource gsData; + private final DriverManagerDataSource entityData; + private final org.jooq.DSLContext entityDsl; + private final ControlledPlayerCreatedOriginalOwnerFixture gs; + private final ControlledPlayerCreatedOwnerStoreFixture entity; + private final CanonicalPlayerCreatedRosterClient roster; + + private Owners(Path directory) throws Exception { + gsData = dataSource("created_owner_gs_" + UUID.randomUUID().toString().replace("-", "")); + entityData = + dataSource("created_owner_entity_" + UUID.randomUUID().toString().replace("-", "")); + try { + var pki = + LoopbackMtlsTestPki.create( + Files.createDirectories(directory.resolve("peers")), + "Created owner composition test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "gs-client", uri("game-session-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "gs-server", uri("game-session-service"), true), + new LoopbackMtlsTestPki.IdentitySpec( + "entity-client", uri("entity-management-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "entity-server", uri("entity-management-service"), true)); + var endpoints = new ServiceEndpointsProperties(); + var gsTls = pki.clientProperties(directory, pki.identity("gs-client")); + var entityTls = pki.clientProperties(directory, pki.identity("entity-client")); + var recovery = + own( + new CanonicalGameplayRosterRecoveryClient( + endpoints, gsTls, new GrpcChannelFactory(), NAMESPACE)); + var initial = + new ControlledPlayerCreatedRosterSourceFixture( + Files.createDirectories(directory.resolve("upstream"))) + .wireFixture(); + gs = + new ControlledPlayerCreatedOriginalOwnerFixture( + gsData, + initial, + recovery, + Clock.systemUTC(), + new CanonicalGameplayRosterReferencePolicy( + RETENTION, RETENTION, RETENTION, Duration.ofSeconds(1), 20)); + var beans = new StaticListableBeanFactory(); + beans.addBean("source", gs.publishedRouteReader()); + beans.addBean("reference", gs.referenceOwner()); + var gsServer = + server( + pki, + "gs-server", + new GameSessionCharacterCreatePublicSourceGrpcService(gs.sourceReader(), NAMESPACE), + new CanonicalGameplayRosterOwnerReadGrpcAdapter( + beans.getBeanProvider( + net.firedevops.firemud.gamesession.service + .CanonicalPublishedPlayerRouteReadService.class), + NAMESPACE, + beans.getBeanProvider( + net.firedevops.firemud.gamesession.service + .CanonicalGameplayRosterReferenceOwner.class))); + endpoints.setGameSessionService("127.0.0.1:" + gsServer.getPort()); + var sourceClient = + own( + new EntityPlayerCreatedRosterSourceClient( + endpoints, entityTls, new GrpcChannelFactory(), NAMESPACE)); + sourceClient.init(); + var originalClient = + own( + new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, entityTls, new GrpcChannelFactory(), NAMESPACE)); + originalClient.init(); + var migration = + Flyway.configure() + .dataSource(entityData) + .locations( + "filesystem:" + + Path.of("../entity-management-service/src/main/resources/db/migration") + .toAbsolutePath() + .normalize(), + "classpath:db/migration/saga") + .schemas(entityData.getSchema()) + .defaultSchema(entityData.getSchema()) + .placeholders(Map.of("serviceSchema", entityData.getSchema())); + migration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + migration.load().migrate(); + entityDsl = DSL.using(new TransactionAwareDataSourceProxy(entityData), SQLDialect.POSTGRES); + entity = + new ControlledPlayerCreatedOwnerStoreFixture( + entityDsl, + new DataSourceTransactionManager(entityData), + NAMESPACE, + gs.wireFixture(), + sourceClient, + originalClient, + Clock.systemUTC(), + new CanonicalGameplayRosterRetentionPolicy( + RETENTION, RETENTION, RETENTION, Duration.ofSeconds(1), 20)); + var entityServer = + server(pki, "entity-server", entity.rosterAdapter(), entity.recoveryAdapter()); + endpoints.setEntityManagementService("127.0.0.1:" + entityServer.getPort()); + recovery.init(); + roster = + own( + new CanonicalPlayerCreatedRosterClient( + endpoints, gsTls, new GrpcChannelFactory(), NAMESPACE, gs.referenceOwner())); + roster.init(); + } catch (Exception failure) { + try { + close(); + } catch (Exception cleanup) { + failure.addSuppressed(cleanup); + } + throw failure; + } + } + + private PlayerExecutionContext context(UUID account) { + var route = gs.routeReader().readCurrentTarget(gs.route().canonicalTenantId()); + return PlayerExecutionContext.newBuilder() + .setAccountId(account.toString()) + .setTenantId(route.canonicalTenantId().toString()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setGameInstanceId(route.canonicalGameInstanceId().toString()) + .setSessionId(UUID.randomUUID().toString()) + .setRealmId(route.realmId().toString()) + .setRequestId(UUID.randomUUID().toString()) + .setPlayableStateScope(route.playableStateScope()) + .build(); + } + + private T own(T resource) { + resources.push(resource); + return resource; + } + + private Server server(LoopbackMtlsTestPki.Pki pki, String alias, BindableService... services) + throws Exception { + var identity = pki.identity(alias); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var service : services) + builder.addService( + ServerInterceptors.intercept( + service, + new net.firedevops.firemud.entitymanagement.security + .CanonicalGameplayRosterPeerInterceptor(NAMESPACE), + new GrpcPeerIdentityInterceptor())); + var server = builder.build().start(); + own(() -> server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS)); + return server; + } + + @Override + public void close() throws Exception { + Exception failure = null; + while (!resources.isEmpty()) { + try { + resources.pop().close(); + } catch (Exception cleanup) { + if (failure == null) failure = cleanup; + else failure.addSuppressed(cleanup); + } + } + var admin = DSL.using(dataSource(null), SQLDialect.POSTGRES); + admin.execute("DROP SCHEMA IF EXISTS \"" + gsData.getSchema() + "\" CASCADE"); + admin.execute("DROP SCHEMA IF EXISTS \"" + entityData.getSchema() + "\" CASCADE"); + if (failure != null) throw failure; + } + } + + private static DriverManagerDataSource dataSource(String schema) { + var data = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + data.setSchema(schema); + return data; + } + + private static String uri(String service) { + return "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service; + } +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java new file mode 100644 index 0000000000..d0107c3e47 --- /dev/null +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java @@ -0,0 +1,1059 @@ +package net.firedevops.firemud.gamesession.testing; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; +import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec; +import net.firedevops.firemud.common.gamedesign.RealmPolicySource; +import net.firedevops.firemud.common.gamedesign.StartSessionLaunchDescriptorGrpcCodec; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture.WireFixture; +import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient; +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.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.dto.CreateCanonicalRealmCatalogRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionLaunchDescriptorRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionTemplateAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferencePolicy; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +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 tools.jackson.databind.json.JsonMapper; + +/** + * Controlled historical GS source for coupled owner tests, never production admission authority. + * + *

The caller owns an isolated PostgreSQL container and disposable schema, including cleanup. + * Catalog/launch/first-OPEN history is constructed in the real pre1006 layout with all installed + * guards, then upgraded through the actual migrations. Original attempt, Account-projection + * attachment, association/descriptor pins and authored-core retention use actual owner writers. The + * current route, complete public source, pointer verification/locks and roster original owner are + * real. Account authority and publication/World responses remain explicitly controlled. + */ +public final class ControlledPlayerCreatedOriginalOwnerFixture { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final DriverManagerDataSource dataSource; + private final String schema; + private final Path migrations; + private final CanonicalPlayerRouteReadService routeReader; + private final CanonicalPublishedPlayerRouteReadService publishedRouteReader; + private final DSLContext dsl; + private final TransactionTemplate transactions; + private final GameSessionCanonicalRealmCatalogRepository catalogs; + private final CanonicalInitialAdmissionRepository admissions; + private final CanonicalGameInstanceLaunchAssociationRepository launches; + private final GameSessionCharacterCreatePublicSourceService sourceReader; + private final CanonicalGameplayRosterReferenceRepository referenceRepository; + private final CanonicalGameplayRosterReferenceOwner referenceOwner; + private final CanonicalPlayableTarget route; + private final WireFixture wireFixture; + + public ControlledPlayerCreatedOriginalOwnerFixture( + DriverManagerDataSource dataSource, + WireFixture supplied, + CanonicalGameplayRosterRecoveryClient recovery, + Clock clock, + CanonicalGameplayRosterReferencePolicy policy) + throws Exception { + Objects.requireNonNull(supplied, "complete controlled publication fixture"); + this.dataSource = Objects.requireNonNull(dataSource); + Objects.requireNonNull(clock); + migrations = Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + schema = Objects.requireNonNull(dataSource.getSchema(), "caller-owned isolated schema"); + migrate("1005"); + var manager = new DataSourceTransactionManager(dataSource); + transactions = new TransactionTemplate(manager); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + catalogs = new GameSessionCanonicalRealmCatalogRepository(dsl); + var events = new GameplayAdmissionPointerEventRepository(dsl); + var pointers = new GameSessionCanonicalAdmissionPointerRepository(dsl, catalogs, events); + admissions = new CanonicalInitialAdmissionRepository(dsl, catalogs, pointers); + String namespace = supplied.request().getTargetNamespace(); + launches = new CanonicalGameInstanceLaunchAssociationRepository(dsl, namespace); + var upstream = supplied.authored(); + var original = + StartSessionPostAuthorizationExecutionTuple.decode( + upstream.request().canonicalPostAuthorizationTuple()); + var tuple = freshControlledTuple(original, clock); + var attempts = new GameSessionStartSessionOperatorAttemptRepository(dsl, Duration.ofMinutes(5)); + var claim = + Objects.requireNonNull(transactions.execute(ignored -> attempts.reserve(tuple))) + .claim() + .orElseThrow(); + var authority = + StartSessionAuthorityEvidenceBundle.decode(tuple.authorityEvidenceBundleBytes()); + var redemption = + new GameSessionStartSessionOperatorAttemptRepository.AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence()), + tuple.canonicalBytes()); + transactions.executeWithoutResult( + ignored -> attempts.attachAccountRedemptionProjection(claim, redemption)); + var association = upstream.associationRead().association(); + var initialRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + namespace, + upstream.request().readRequestId(), + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.InitialConfigured()); + var initial = + new StartSessionTemplateAssociationReadEvidence.Result( + initialRequest, + association, + upstream.associationRead().releaseBundle(), + upstream.associationRead().worldPublishedStartLocationEvidence(), + upstream.associationRead().phaseEpoch()); + var selections = new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); + transactions.execute(ignored -> selections.pinInitialOrValidateExactReplay(claim, initial)); + var exactRequest = + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + namespace, + initialRequest.readRequestId(), + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerFence(), + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + association.canonicalVersionId(), association.selectedCommitId(), + association.publishWorkflowId(), association.associationDigest())); + var exact = + new StartSessionTemplateAssociationReadEvidence.Result( + exactRequest, + association, + initial.releaseBundle(), + initial.worldPublishedStartLocationEvidence(), + initial.phaseEpoch()); + var authored = + new AuthoredInitialActorCoreReadEvidence.ReadResult( + exactRequest, exact, upstream.descriptor(), upstream.projections()); + var descriptors = new GameSessionStartSessionLaunchDescriptorRepository(dsl, selections); + transactions.execute( + ignored -> + descriptors.pin( + claim, + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + exact, + new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome( + authored.descriptor())))); + var source = association.worldReceipt().source(); + var intakeRepository = new GameSessionAuthoredWorldSourceRepository(dsl); + var intake = + Objects.requireNonNull( + transactions.execute(ignored -> intakeRepository.register(UUID.randomUUID(), source))); + var tenantAssociation = + Objects.requireNonNull( + transactions.execute( + ignored -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), namespace, intake, creationEvidence(source)))); + var policySet = supplied.policySet(); + var realmPolicy = + policySet.policies().stream() + .filter(item -> item.policy().realmSlug().equals(supplied.request().getRealmSlug())) + .findFirst() + .orElseThrow() + .policy(); + var catalogRequest = + new CreateCanonicalRealmCatalogRequest( + UUID.randomUUID(), + namespace, + source.canonicalTenantId(), + intake.operationId(), + realmPolicy.realmSlug(), + realmPolicy.realmDisplayName(), + true, + true, + "SHARED", + "PLAYER_CREATED", + null, + null); + var published = internalPolicies(policySet); + // Real owner preparation validates the complete PLAYER_CREATED source from the outset. + catalogs.prepareInitialPublicProduction(catalogRequest, published); + var catalog = + seedPriorCatalog( + catalogRequest, + intake, + UUID.fromString(supplied.request().getRealmId()), + supplied.world().request().playableStateNamespaceId(), + published); + var binding = supplied.world().launchBinding(); + UUID instance = supplied.world().request().canonicalGameInstanceId(); + long runtime = + seedPriorLaunch( + catalog, + tenantAssociation.legacyGameSessionTenantId(), + tenantAssociation.associationOperationId(), + tenantAssociation.sourceEvidence(), + tuple, + binding, + instance); + var captured = + new CanonicalGameInstanceLaunchAssociation( + namespace, + tenantAssociation.legacyGameSessionTenantId(), + tenantAssociation.associationOperationId(), + source.canonicalTenantId(), + instance, + source.worldSlug(), + catalog.playableStateNamespaceId(), + realmPolicy.stateScope(), + true, + tuple.controlPlaneRequestId(), + authored.descriptor().launchDescriptorId(), + 0L, + binding, + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING, + 0L); + var launch = + new CanonicalInitialAdmissionLaunchTarget( + captured, catalog.realmId(), runtime, authored.descriptor().versionId()); + seedPriorCommittedAdmission(catalog, launch, supplied.world().lifecycleEpoch(), events); + // Upgrade actual prior history before current source-retention and reference owner work. + migrate("1013"); + var retention = new GameSessionAuthoredActorCoreRetentionRepository(dsl, manager, namespace); + var currentAttemptRequest = + new net.firedevops.firemud.common.gamesession.OriginalStartSessionCurrentAttemptEvidence + .Request( + UUID.randomUUID(), + namespace, + tuple.canonicalBytes(), + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence()); + var attempt = + transactions.execute(ignored -> attempts.readCurrentOriginalAttempt(currentAttemptRequest)); + var retained = + new GameSessionAuthoredActorCoreRetentionRepository.Candidate( + namespace, + tuple.controlPlaneRequestId(), + source.canonicalTenantId(), + instance, + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence(), + Objects.requireNonNull(attempt).leaseExpiresAt(), + tuple.canonicalBytes(), + redemption.originalAccountPostAuthorizationTuple(), + hash(redemption.originalAccountPostAuthorizationTuple(), false), + association.canonicalVersionId(), + association.selectedCommitId(), + association.publishWorkflowId(), + association.associationDigest(), + association.sourceOperationId(), + association.sourceEvidenceDigest(), + source.worldSlug(), + authored.descriptor().launchDescriptorId(), + authored.descriptor().requestDigest(), + authored.descriptor().resultDigest(), + binding.releaseAttestation().evidenceDigest(), + StartSessionTemplateAssociationReadGrpcCodec.toRequest(exactRequest).toByteArray(), + authored.canonicalBytes(), + authored.digest()); + transactions.execute( + ignored -> { + attempts.readCurrentOriginalAttempt(currentAttemptRequest); + return retention.retainInOwnerTransaction(retained); + }); + migrate("1020"); + routeReader = new CanonicalPlayerRouteReadService(namespace, catalogs, admissions, launches); + var gameDesign = mock(AuthoredInitialActorCoreReadClient.class); + when(gameDesign.read(any())) + .thenAnswer( + call -> { + requireOutsideSql(); + if (!new AuthoredInitialActorCoreReadEvidence.ReadRequest(authored.request()) + .equals(call.getArgument(0))) + throw new IllegalArgumentException("Controlled authored replay selector changed"); + return authored; + }); + var world = mock(WorldCanonicalInstanceLifecycleClient.class); + when(world.read(any())) + .thenAnswer( + call -> { + requireOutsideSql(); + var requested = (WorldCanonicalInstanceLifecycleEvidence.Request) call.getArgument(0); + var base = supplied.world(); + var expected = base.request(); + if (!requested.equals( + new WorldCanonicalInstanceLifecycleEvidence.Request( + expected.schemaVersion(), + requested.readRequestId(), + expected.targetNamespace(), + expected.canonicalTenantId(), + expected.worldSlug(), + expected.canonicalGameInstanceId(), + expected.playableStateNamespaceId(), + expected.playableStateScope(), + expected.publicProduction(), + expected.controlPlaneRequestId(), + expected.canonicalVersionId(), + expected.expectedDescriptorRequestDigest(), + expected.expectedDescriptorResultDigest(), + expected.expectedReleaseAttestationDigest()))) + throw new IllegalArgumentException("Controlled World selector changed"); + return new WorldCanonicalInstanceLifecycleEvidence( + requested, + base.launchBinding(), + base.startLocation(), + base.runtimeRoomInstanceId(), + base.lifecycleStatus(), + base.lifecycleEpoch(), + base.rowVersion(), + base.captureId(), + base.graphSha256(), + base.preparationInputDigest(), + base.operationalRegionAssignments()); + }); + var policies = mock(GameDesignPublishedRealmPolicyClient.class); + when(policies.listPublishedRealmEntryPolicies(any(), any())) + .thenAnswer( + call -> { + requireOutsideSql(); + if (!source.canonicalTenantId().equals(call.getArgument(0)) + || !association.canonicalVersionId().equals(call.getArgument(1))) + throw new IllegalArgumentException("Controlled published policy selector changed"); + return policySet; + }); + sourceReader = + new GameSessionCharacterCreatePublicSourceService( + namespace, + routeReader, + catalogs, + admissions, + launches, + retention, + gameDesign, + world, + policies); + route = routeReader.readCurrentTarget(source.canonicalTenantId()); + var request = + supplied.request().toBuilder() + .setWorldSlug(route.worldSlug()) + .setRealmSlug(route.realmSlug()) + .setRealmId(route.realmId().toString()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setCatalogRevision(route.catalogRevision()) + .setPointerVersion(route.pointerVersion()) + .setCanonicalGameInstanceId(route.canonicalGameInstanceId().toString()) + .setExpectedCanonicalVersionId(route.canonicalVersionId().toString()) + .setActiveWorldEpoch(route.activeWorldEpoch()) + .build(); + var response = sourceReader.readPlayerCreatedRosterSource(request); + var actualWorld = + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence.fromStored( + response.getWorldLifecycleEvidence().toByteArray()); + wireFixture = new WireFixture(request, response, authored, actualWorld, policySet); + referenceRepository = + new CanonicalGameplayRosterReferenceRepository(dsl, Objects.requireNonNull(policy)); + publishedRouteReader = + new CanonicalPublishedPlayerRouteReadService( + namespace, routeReader, catalogs, launches, policies); + referenceOwner = + new CanonicalGameplayRosterReferenceOwner( + referenceRepository, + transactions, + publishedRouteReader, + routeReader, + admissions, + Objects.requireNonNull(recovery), + sourceReader); + } + + public GameSessionCharacterCreatePublicSourceService sourceReader() { + return sourceReader; + } + + public CanonicalGameplayRosterReferenceOwner referenceOwner() { + return referenceOwner; + } + + public CanonicalGameplayRosterReferenceRepository referenceRepository() { + return referenceRepository; + } + + public CanonicalPlayableTarget route() { + return route; + } + + public WireFixture wireFixture() { + return wireFixture; + } + + public CanonicalPlayerRouteReadService routeReader() { + return routeReader; + } + + public CanonicalPublishedPlayerRouteReadService publishedRouteReader() { + return publishedRouteReader; + } + + public DSLContext dsl() { + return dsl; + } + + public TransactionTemplate transactions() { + return transactions; + } + + private void migrate(String version) { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations("filesystem:" + migrations) + .target(MigrationVersion.fromVersion(version)) + .load() + .migrate(); + } + + private static StartSessionPostAuthorizationExecutionTuple freshControlledTuple( + StartSessionPostAuthorizationExecutionTuple original, Clock clock) throws Exception { + var bundle = + StartSessionAuthorityEvidenceBundle.decode(original.authorityEvidenceBundleBytes()); + Map values = new LinkedHashMap<>(bundle.jsonValue()); + @SuppressWarnings("unchecked") + var oldProjection = (Map) values.get("accountProjectionEvidence"); + var projection = new LinkedHashMap<>(oldProjection); + Instant evaluated = clock.instant().truncatedTo(ChronoUnit.MILLIS); + projection.put("evaluatedAt", evaluated.toString()); + projection.put("expiresAt", evaluated.plus(Duration.ofMinutes(5)).toString()); + values.put("accountProjectionEvidence", projection); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + original.preAuthorizationTuple(), + original.authenticatedWorkloadIdentity(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(values)), + original.bundleReference()); + } + + private static RealmPolicyPublishedEvidence.PublishedSet internalPolicies( + PublishedRealmEntryPolicySetEvidence set) { + return new RealmPolicyPublishedEvidence.PublishedSet( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies().stream() + .map( + item -> + new RealmPolicyPublishedEvidence.Policy( + item.policyId(), + new RealmPolicySource.Policy( + item.sourceCommitId(), + item.sourceRevisionId(), + item.logicalRevisionId(), + item.policy()), + item.policyDigest())) + .toList()); + } + + private static FreshTenantCreationEvidence creationEvidence(AuthoredWorldSourceEvidence source) { + UUID request = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String digest = + GameTenantCreationDigest.requestDigest( + source.targetNamespace(), + request, + source.sourceGameTenantKey(), + source.worldDisplayName(), + null); + return new FreshTenantCreationEvidence( + 1, + source.targetNamespace(), + request, + operation, + digest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + GameTenantCreationDigest.evidenceDigest( + source.targetNamespace(), + request, + operation, + digest, + source.canonicalTenantId(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind())); + } + + private CanonicalRealmCatalogSnapshot seedPriorCatalog( + CreateCanonicalRealmCatalogRequest request, + GameSessionAuthoredWorldSourceRepository.IntakeReceipt intake, + UUID realm, + UUID playableNamespace, + RealmPolicyPublishedEvidence.PublishedSet policies) { + var source = intake.source(); + byte[] policyBytes = RealmPolicyPublishedEvidenceCodec.encode(policies); + String base = + decimalFrame( + "game-session-canonical-realm-catalog-request/v1", + "1", + request.requestId().toString(), + request.targetNamespace(), + request.canonicalTenantId().toString(), + intake.operationId().toString(), + intake.intakeRequestId().toString(), + intake.requestDigest(), + intake.receiptDigest(), + Integer.toString(source.schemaVersion()), + source.registrationRequestId().toString(), + source.operationId().toString(), + source.requestDigest(), + source.canonicalTenantId().toString(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + Long.toString(source.sourceGameRowId()), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest(), + request.realmSlug(), + request.realmDisplayName(), + "true", + "true", + "SHARED", + "PLAYER_CREATED", + "ABSENT", + "ABSENT"); + String requestDigest = + decimalFrame( + "game-session-complete-catalog-request/v1", + base, + HexFormat.of().formatHex(policyBytes)); + String receipt = + decimalFrame( + "game-session-canonical-realm-catalog-receipt/v1", + "1", + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.requestId().toString(), + requestDigest, + realm.toString(), + playableNamespace.toString(), + "1", + intake.operationId().toString(), + intake.receiptDigest()); + var sourceColumns = + map( + "source_intake_operation_id", + intake.operationId(), + "source_intake_schema_version", + 1, + "source_intake_request_id", + intake.intakeRequestId(), + "source_intake_request_digest", + intake.requestDigest(), + "source_intake_receipt_digest", + intake.receiptDigest(), + "source_schema_version", + source.schemaVersion(), + "source_registration_request_id", + source.registrationRequestId(), + "source_operation_id", + source.operationId(), + "source_request_digest", + source.requestDigest(), + "source_game_row_id", + source.sourceGameRowId(), + "source_game_tenant_key", + source.sourceGameTenantKey(), + "source_provenance_kind", + source.provenanceKind(), + "source_evidence_digest", + source.evidenceDigest()); + transactions.executeWithoutResult( + ignored -> { + var shared = new LinkedHashMap<>(sourceColumns); + shared.putAll( + map( + "tenant_id", + null, + "playable_state_namespace_id", + playableNamespace, + "canonical_tenant_id", + request.canonicalTenantId(), + "target_namespace", + request.targetNamespace())); + insert("gameplay_tenant_shared_playable_state_namespace", shared); + var catalog = new LinkedHashMap<>(sourceColumns); + catalog.putAll( + map( + "target_namespace", + request.targetNamespace(), + "canonical_tenant_id", + request.canonicalTenantId(), + "tenant_slug", + source.tenantSlug(), + "world_slug", + source.worldSlug(), + "realm_id", + realm, + "realm_slug", + request.realmSlug(), + "realm_display_name", + request.realmDisplayName(), + "visible", + true, + "public_production", + true, + "state_scope", + "SHARED", + "playable_state_namespace_id", + playableNamespace, + "character_creation_policy", + "PLAYER_CREATED", + "catalog_revision", + 1L, + "creation_request_id", + request.requestId(), + "request_digest", + requestDigest, + "receipt_digest", + receipt, + "source_world_display_name", + source.worldDisplayName(), + "complete_policy_set_evidence", + policyBytes)); + insert("game_session_canonical_realm_catalog", catalog); + }); + return new CanonicalRealmCatalogSnapshot( + request.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + realm, + request.realmSlug(), + request.realmDisplayName(), + true, + true, + "SHARED", + playableNamespace, + "PLAYER_CREATED", + 1L, + request.requestId(), + requestDigest, + receipt, + intake); + } + + private long seedPriorLaunch( + CanonicalRealmCatalogSnapshot catalog, + long tenantId, + UUID associationOperation, + net.firedevops.firemud.common.tenant.RuntimeTenantIdentityEvidence tenantSource, + StartSessionPostAuthorizationExecutionTuple tuple, + net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence binding, + UUID instance) + throws Exception { + var descriptor = binding.descriptor(); + var tupleSource = catalog.sourceIntakeReceipt(); + String bindingJson = JSON.writeValueAsString(binding); + return Objects.requireNonNull( + transactions.execute( + ignored -> { + var runtime = + map( + "tenant_id", + tenantId, + "runtime_version", + Long.toString(descriptor.versionId()), + "owner_account_uuid", + tuple.preAuthorizationTuple().actor().accountId(), + "status", + "STARTING", + "row_version", + 0L, + "game_template_id", + descriptor.gameTemplateId(), + "launch_descriptor_id", + descriptor.launchDescriptorId(), + "version_id", + descriptor.versionId(), + "release_bundle_id", + descriptor.releaseBundleId(), + "version_state_epoch", + descriptor.versionStateEpoch(), + "generation_config_revision", + descriptor.generationConfigRevision(), + "run_owned_start_request_id", + tuple.controlPlaneRequestId(), + "run_owned_start_request_digest", + tuple.mutationDigest(), + "run_owned_start_published_release_bundle_ref", + descriptor.publishedReleaseBundleRef(), + "game_instance_uuid", + instance); + var fields = new LinkedHashMap, Object>(); + runtime.forEach((key, value) -> fields.put(DSL.field(DSL.name(key)), value)); + long allocated = + dsl.insertInto(DSL.table("game_instances")) + .set(fields) + .returning(DSL.field("id", Long.class)) + .fetchSingle() + .get("id", Long.class); + insert( + "game_session_canonical_instance_launch", + map( + "target_namespace", + catalog.targetNamespace(), + "control_plane_request_id", + tuple.controlPlaneRequestId(), + "game_session_tenant_id", + tenantId, + "canonical_tenant_id", + catalog.tenantId(), + "tenant_association_operation_id", + associationOperation, + "tenant_association_request_id", + tenantSource.requestId(), + "tenant_source_schema_version", + tenantSource.schemaVersion(), + "tenant_source_target_namespace", + tenantSource.targetNamespace(), + "tenant_source_request_id", + tenantSource.requestId(), + "tenant_source_canonical_tenant_id", + tenantSource.canonicalTenantId(), + "tenant_source_game_row_id", + tenantSource.sourceGameRowId(), + "tenant_source_game_tenant_key", + tenantSource.sourceGameTenantKey(), + "tenant_source_provenance_kind", + tenantSource.provenanceKind(), + "tenant_association_kind", + "FRESH_SOURCE_BOUND", + "game_instance_id", + allocated, + "game_instance_uuid", + instance, + "canonical_realm_id", + catalog.realmId(), + "world_slug", + catalog.worldSlug(), + "playable_state_namespace_id", + catalog.playableStateNamespaceId(), + "playable_state_scope", + "SHARED", + "public_production", + true, + "captured_starting_row_version", + 0L, + "game_template_id", + descriptor.gameTemplateId(), + "launch_descriptor_id", + descriptor.launchDescriptorId(), + "version_id", + descriptor.versionId(), + "release_bundle_id", + descriptor.releaseBundleId(), + "generation_config_revision", + descriptor.generationConfigRevision(), + "version_state_epoch", + descriptor.versionStateEpoch(), + "complete_launch_binding_evidence", + org.jooq.JSONB.valueOf(bindingJson), + "original_start_session_tuple", + tuple.canonicalBytes(), + "catalog_creation_request_id", + catalog.creationRequestId(), + "catalog_revision", + catalog.catalogRevision(), + "catalog_source_intake_operation_id", + tupleSource.operationId(), + "catalog_source_intake_request_id", + tupleSource.intakeRequestId())); + dsl.execute("UPDATE game_instances SET status='RUNNING' WHERE id=?", allocated); + return allocated; + })); + } + + private void seedPriorCommittedAdmission( + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launch, + long epoch, + GameplayAdmissionPointerEventRepository events) { + var association = launch.association(); + String requestId = "controlled-initial-" + catalog.realmId(); + UUID version = association.launchBindingEvidence().releaseAttestation().canonicalVersionId(); + String digest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + "SHARED", + association.gameInstanceUuid(), + version, + epoch, + 1L, + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId); + var request = + new CanonicalInitialAdmissionRequest( + catalog.targetNamespace(), + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + "SHARED", + association.gameInstanceUuid(), + version, + epoch, + 1L, + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId, + digest, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "e".repeat(64)); + transactions.executeWithoutResult( + ignored -> { + var pendingAt = dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); + insert( + "game_session_canonical_initial_admission_attempt", + map( + "target_namespace", + request.targetNamespace(), + "initial_admission_request_id", + requestId, + "request_digest", + digest, + "canonical_tenant_id", + catalog.tenantId(), + "world_slug", + catalog.worldSlug(), + "realm_id", + catalog.realmId(), + "playable_state_namespace_id", + catalog.playableStateNamespaceId(), + "playable_state_scope", + "SHARED", + "canonical_game_instance_id", + association.gameInstanceUuid(), + "game_session_tenant_id", + association.gameSessionTenantId(), + "game_instance_id", + launch.gameInstanceId(), + "canonical_version_id", + version, + "runtime_version_id", + launch.runtimeVersionId(), + "expected_catalog_revision", + 1L, + "origin_kind", + request.originKind().name(), + "active_lifecycle_epoch", + epoch, + "hold_id", + request.holdId(), + "hold_fence", + request.holdFence(), + "hold_binding_digest", + request.holdBindingDigest(), + "status", + "PENDING", + "created_at", + pendingAt, + "updated_at", + pendingAt)); + var now = + dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant(); + long audit = + events.appendCanonicalInitialAdmissionOpen(request, catalog, launch, 1L, 1L, now); + String columns = + "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"; + String eventColumns = + columns + .replace("last_updated_by", "actor_principal") + .replace("last_update_reason", "reason") + .replace("created_at", "occurred_at") + .replace("updated_at", "occurred_at"); + long pointer = + dsl.fetchSingle( + "INSERT INTO gameplay_admission_pointer (" + + columns + + ") SELECT " + + eventColumns + + " FROM gameplay_admission_pointer_event WHERE id=? RETURNING id", + audit) + .get("id", Long.class); + String proof = + binaryFrame( + "gs-canonical-initial-admission-commit-proof/v1", + digest, + requestId, + request.targetNamespace(), + catalog.tenantId().toString(), + catalog.worldSlug(), + catalog.realmId().toString(), + catalog.playableStateNamespaceId().toString(), + "SHARED", + association.gameInstanceUuid().toString(), + version.toString(), + Long.toString(launch.runtimeVersionId()), + Long.toString(epoch), + "1", + request.originKind().name(), + "", + request.holdId().toString(), + request.holdFence().toString(), + request.holdBindingDigest(), + "1", + Long.toString(audit), + "", + "", + "", + now.toString()); + dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET status='COMMITTED',pointer_id=?," + + "pointer_version=1,audit_event_id=?,commit_proof_digest=?,terminal_at=?::timestamptz,updated_at=?::timestamptz " + + "WHERE target_namespace=? AND initial_admission_request_id=?", + pointer, + audit, + proof, + now.atOffset(ZoneOffset.UTC), + now.atOffset(ZoneOffset.UTC), + request.targetNamespace(), + requestId); + }); + } + + private void insert(String table, Map values) { + var fields = new LinkedHashMap, Object>(); + values.forEach((key, value) -> fields.put(DSL.field(DSL.name(key)), value)); + dsl.insertInto(DSL.table(DSL.name(table))).set(fields).execute(); + } + + private static Map map(Object... values) { + var result = new LinkedHashMap(); + for (int i = 0; i < values.length; i += 2) result.put((String) values[i], values[i + 1]); + return result; + } + + private static String decimalFrame(String... fields) { + var bytes = new ByteArrayOutputStream(); + for (String field : fields) { + byte[] value = field.getBytes(StandardCharsets.UTF_8); + bytes.writeBytes((value.length + ":").getBytes(StandardCharsets.US_ASCII)); + bytes.writeBytes(value); + } + return hash(bytes.toByteArray(), true); + } + + private static String binaryFrame(String... fields) { + try { + var bytes = new ByteArrayOutputStream(); + var frame = new DataOutputStream(bytes); + for (String field : fields) { + byte[] value = field.getBytes(StandardCharsets.UTF_8); + frame.writeInt(value.length); + frame.write(value); + } + return hash(bytes.toByteArray(), true); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static String hash(byte[] bytes, boolean prefix) { + try { + return (prefix ? "sha256:" : "") + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static void requireOutsideSql() { + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive() + || org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + throw new IllegalStateException("Controlled upstream call entered GS SQL"); + } +} From 36305ddd428173cce6a4ca2811ac9fc51a39001f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:55:42 +1300 Subject: [PATCH 05/22] Record initial created-roster composition proof and narrow fixture access --- .../entity-management-service/api-contracts.md | 4 ++-- .../entity-management-service/runtime-and-data.md | 2 +- .../game-session-service/api-contracts.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 6 ++++-- .../player-access-and-session.md | 2 +- .../ControlledPlayerCreatedOwnerStoreFixture.java | 4 ---- ...reatedRosterOwnerCompositionIntegrationTest.java | 2 +- ...ControlledPlayerCreatedOriginalOwnerFixture.java | 13 +++++++------ 9 files changed, 18 insertions(+), 19 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index fa8268029e..6b336d18ae 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -12,7 +12,7 @@ The prepared selected-source command and immutable receipt/digest reads remain s Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has manually composed certificate-guarded client, peer-interceptor, and read-adapter source definitions, but no automatic runtime handler, client, or service-bean registration. Default component scanning and legacy activation flags leave this family unregistered; [Runtime and Data](./runtime-and-data.md#implementation-status) owns its registration prerequisites. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. -Forward V1016 adds the created snapshot branch to the existing sealed-roster family. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The complete Game Session original-owner to Entity capture to Game Session receipt composition remains unrun; the API, handler and caller remain unregistered, and no production source-custody, Account-protection settlement, gameplay-admission or activation proof is established. +Forward V1016 adds the created snapshot branch to the existing sealed-roster family. Controlled initial owner-to-owner capture, selected read and original-receipt/replay qualification is recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The test uses actual current owner stores and authenticated transports with coherent controlled historical source; Account, publication and World inputs and test PKI remain controlled. Current guarded post-issuance supersession through recovery/retirement remains unrun. The API, handler and caller remain unregistered; production custody, Account settlement, gameplay admission and activation are unproved. The manually composed Account/Game Session evidence bridge currently supports `SHARED` only; the assignment bridge requires already canonical, non-nil UUID game-instance text under the existing bridge contract. Those bounded adapters supply no owner proof outside their declared scope. They do not narrow the passive assignment core, which supports `SHARED` and `ISOLATED` and hashes exact bounded opaque game-instance text without parsing or normalization. @@ -61,7 +61,7 @@ curl http://localhost:8080/ping - `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in `entity_management_service.proto`. - `CanonicalGameplayRosterService.ListPreseededRoster` and `ReadSelectedPreseededAssignment` – target `PRESEEDED_ONLY` pre-admission wire contract described in [Implementation Status](#implementation-status). Source models and manually composed certificate-guarded handler, peer-interceptor, client, and read-adapter source definitions are present; none of these or callers is registered. The result is discovery evidence, not actor admission or a session-binding shortcut. -- `CanonicalGameplayRosterService.ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter` – distinct non-admitting `PLAYER_CREATED` reads with the target contract described in [Player-created roster and selected character](#player-created-roster-and-selected-character). They do not change either preseeded method. Controlled component and isolated backend qualification is recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation); the full original-owner composition remains unrun and this path remains unregistered. +- `CanonicalGameplayRosterService.ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter` – distinct non-admitting `PLAYER_CREATED` reads with the target contract described in [Player-created roster and selected character](#player-created-roster-and-selected-character). They do not change either preseeded method. The initial controlled source-to-receipt/replay composition passes; the guarded supersession-to-recovery/retirement causal composition remains unrun (see the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation)). This path remains unregistered. - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains 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. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `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/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 3f1cef7553..9a4c422b0c 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -23,7 +23,7 @@ This document defines Entity Management’s runtime model, persistence ownership - Entity V1003–V1005 adds independent opaque actor UUIDs, quarantine metadata, exact namespace/scope constraints, and canonical lookup indexes without inferring Account or tenant UUID provenance. Legacy values are retained. The exact canonical repository reader excludes quarantined rows. Existing legacy consumers retain develop behavior for legacy rows, while numeric character, inventory, equipment, friend, resource and condition predicates exclude actors carrying canonical `tenant_uuid` provenance even when their status becomes `QUARANTINED`, including updates and condition expiry. Legitimate legacy/quarantined rows with null canonical tenant provenance retain legacy behavior. Entity's private tenant-row association is not a platform numeric tenant identity; equal numeric values do not authorize legacy access to a canonical actor. Canonical UUID assignment, receipt and roster predicates remain separate. This narrow storage bridge boundary does not activate runtime quarantine enforcement or canonical player admission. - Entity V1006–V1010 adds committed assignment/receipt and sealed roster-snapshot storage with canonical publication identity and exact owner counters. The services and certificate-guarded client/read-adapter source definitions are manually composed and unregistered; neither default scanning nor an optional flag registers them. No authenticated production transport, actor promotion of retained legacy rows, or runtime admission is activated. The detailed assignment/roster contract remains in [Entity API Contracts](./api-contracts.md#implementation-status). -- Forward V1016 adds the immutable `PLAYER_CREATED` source identity and created-receipt branch to the shared snapshot family while preserving the `PRESEEDED_ONLY` guards and budgets. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [Entity player-created owner and roster tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The complete Game Session original-owner to Entity capture to Game Session receipt composition remains unrun and unregistered; production source custody, Account-protection settlement, production PKI, actor admission and `PLAY` remain unproved. +- Forward V1016 adds the immutable `PLAYER_CREATED` source identity and created-receipt branch while preserving the `PRESEEDED_ONLY` guards and budgets. The [owning tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records qualified controlled initial storage/transport composition and separate retention components. Full guarded post-issuance supersession through retirement remains unrun; the path stays unregistered, with production custody, Account settlement, admission and activation unproved. - Sealed canonical roster snapshots and their actor references are immutable Entity-owned records: append a new snapshot/reference set when the canonical target or roster changes, preserving the existing deletion guards. The [family retention declaration](#sealed-canonical-roster-retention) defines its ADR 0163 obligations. Before any handler, service, or alternative snapshot writer is registered, owner-local disposal must be proved with authoritative terminal/reference/hold carriers and compatible configured horizons. Local carrier and disposal source is prepared with focused qualification; genuine producer composition and registration remain unavailable. See the [implementation tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). This does not set a numeric horizon, authorize deletion, or establish indefinite retention. The current passive writer has no registered production call chain; its pending implementation obligation is tracked under #2967 and is not completion or merge proof. - Standard, production, and test Flyway profiles use PostgreSQL `transactional-lock=false` for V1004's concurrent index builds. Entity V1003–V1010 follows unchanged develop Saga V1000–V1002 under the default combined migration locations. Current storage, fresh packaged legacy player-flow, and actual-parent upgrade qualification and its local infrastructure limits are recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). - Actual authenticated owner provenance and the real Game Session caller/controller/execution replacement remain incomplete. Test-created `OWNER_RESOLVED` rows establish bounded storage isolation only; legacy names, numeric IDs, `shared-live`, `instance:`, and runtime pointers never fill missing canonical owner evidence. Runtime quarantine guards, cleanup holds, and condition-expiry retention belong to the later runtime boundary. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 8f25768889..7f94e05333 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 @@ This document mixes live and target-state control-plane surfaces. Current live b Read the pause/status/recovery APIs below as the target-state contract unless the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) explicitly records them as live. -The current unregistered created-owner consumer composition contains Game Session migrations V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage; V1020's created-receipt branch does not supply either missing prerequisite. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [player-created roster consumer tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation). The full Game Session original-owner to Entity capture to Game Session receipt and transfer composition remains unrun; production source custody, real Account-protection settlement, production PKI, registration, activation and public admission remain unproved. The independently qualified public character-creation source-read contract above remains a separate boundary. +The unregistered created-owner consumer contains V1017 and V1020; V1020's created-receipt branch does not supply the separate canonical UUID runtime or creation-protection prerequisites. The [player-created roster consumer tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) records controlled initial source/receipt/replay qualification, separate recovery/retirement/ACK components and the still-unrun guarded post-issuance supersession composition. Production custody, Account settlement, production PKI, registration, activation and public admission remain unproved. The independently qualified public character-creation source-read contract above remains a separate boundary. For script transitions, the live boundary includes the exact `scriptPinEpoch` and an atomic current-pin/request-result ledger commit; bounded authoritative history readback and append-only rollout history remain target-state gaps. Target pin and rollback requests require the explicit tagged `expectedCurrentPin` precondition defined in the [Scripting Control Plane API](../../system-architecture-scripting-control-plane-api.md): exactly `UNCONDITIONAL`, `EXPECT_UNPINNED`, or `EXPECT_EPOCH(scriptPinEpoch)`, with the complete tag/value included in the normalized digest. Missing/unknown tags fail validation; a both-absent tuple for a never-pinned instance is valid semantic `UNPINNED` and matches only `EXPECT_UNPINNED`; a partial tuple is invalid owner state, cannot satisfy `EXPECT_UNPINNED` or `EXPECT_EPOCH`, and is rejected/fails closed even for an `UNCONDITIONAL` request. Missing or unreadable authority is not `UNPINNED` and remains unavailable. `UNCONDITIONAL` is only the explicit `platformAdmin` break-glass repair branch with the matrix's `privileged_control` authorization; it skips only current-pin comparison and does not bypass coherent owner state, readiness, or other validation. See [Rollout and Rollback](../../system-architecture-scripting-rollout-and-rollback.md#pin-compare-and-set-preconditions) for the owner semantics. A valid precondition mismatch is deterministic and non-mutating and follows the existing idempotency/history semantics. 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 ec2f493e23..c0ce97c546 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -43,7 +43,7 @@ The sections below define the target-state runtime contract. Current implementat - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. - Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). -- The current unregistered created-owner consumer composition includes Game Session migrations V1017 and V1020, but omits V1018's separate canonical Game Session UUID storage and V1019's creation-protection storage; V1020's created-receipt fields do not supply either missing prerequisite. Focused controlled component and isolated backend packaging/runtime qualifications are recorded in the [player-created roster consumer tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation). The full Game Session original-owner to Entity capture to Game Session receipt and transfer composition remains unrun; UUID runtime, real Account-protection settlement, production PKI, authenticated production custody, registration, activation and gameplay admission remain unproved. +- The unregistered created-owner consumer includes V1017/V1020 but omits the separate canonical UUID runtime and creation-protection storage; created-receipt fields supply neither prerequisite. The [owning tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) records controlled initial receipt/replay and separate retention-component proof, with current guarded post-issuance supersession through retirement still unrun. Production custody, Account settlement, production PKI, registration, activation and gameplay admission remain unproved. - The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. ## Runtime Details diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index a354012f51..b57c9c042b 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -12,7 +12,9 @@ The unregistered composition implements Entity's `CHARACTER_CREATE` terminal wri R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases with affected static analysis, formatting and documentation checks. Unchanged Common and broader Game Session physical proof retain R86 attribution: 1,020 Common unit cases, 364 Game Session PostgreSQL cases and 36 cross-service cases. R86's earlier 396 Entity and 2,565 Game Session unit counts are superseded by the new executions, rather than credited as fresh runs. Native Entity proof includes the actual retained creation writer feeding authenticated source-bound snapshot capture; socket fixtures use controlled PKI and owner facts, including a complete 5 MiB terminal rather than physical proof at every maximum purpose bound. After the documentation-only parent carry, R93 rebuilds fresh images at `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project inspection confirms no remaining containers, networks or volumes. The subsequent public-parent documentation carry is code-identical. This validates controlled components, storage, packaging and the isolated backend baseline; it does not exercise a registered production created-actor flow. -The complete real Game Session original owner → Entity capture → Game Session receipt composition remains unrun. Existing controlled historical OPEN evidence is preseeded and lacks the coherent retained created-source candidate, original tuple/redemption/descriptor, sealed policy and World composition; a protobuf or changed policy cannot supply that custody. Fresh Human OPEN still requires the unavailable Account protection and settlement composition. Game Session UUID runtime and creation-protection storage remain separate receiving work. Genuine source custody, production PKI, registration, region/execution handoffs, public admission, activation and the genuine playable journey remain open; controlled upstream facts and component or socket fixtures do not close those gaps. +R110 verifies the controlled initial owner-to-owner composition retained at `c9bd1cebabcbd5c9d2f37084f8a728666d6c9674`: the actual Game Session source and durable original `ROSTER` owner connect through authenticated gRPC to Entity's actual creation writer, immutable created snapshot and selected-owner read, then persist and replay the exact full terminal in Game Session. The one coupled case also rejects a foreign selected actor and mismatched context without changing the original receipt, and the real current-source retirement owner refuses to retire the still-current target. R105 separately passes four Entity created-retention cases, six Game Session created-reference recovery/retirement/ACK cases with controlled upstream source facts, and the current Human reserve/commit/abort refusal case. These component results do not prove the missing current supersession writer. + +The full causal current supersession after original issuance → recovery/retirement closure composition remains unrun. The Account terminal-protection authority and settlement composition needed by the guarded Human OPEN writer remain unavailable; that source/admission work stays with the remaining Game Session and Account prerequisites. The controlled initial fixture constructs coherent historical `PLAYER_CREATED` source from the outset, preserving complete authored/original/descriptor/policy/World bindings through actual migration and current readers. It neither changes a preseeded policy nor bypasses the current writer. Game Session UUID runtime and creation-protection storage remain separate receiving work. Genuine source custody, production PKI, registration, region/execution handoffs, public admission, activation and the genuine playable journey remain open. ### Canonical sealed roster retention prerequisite @@ -60,7 +62,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, complete created-roster owner/consumer composition, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | 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 496b4657f2..21a26330a1 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. -The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the controlled qualification and limits: R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases; unchanged Common and broader Game Session physical/cross-service proof retain their R86 attribution. After the documentation-only parent carry, R93 freshly rebuilds `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code, passes held Gateway/Telnet denial and the isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline, and completes authenticated teardown with independent exact-project resource absence. Later parent documentation changes preserve that code. The complete real Game Session original owner → Entity capture → Game Session receipt composition remains unrun; genuine source custody, Account protection/settlement, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. +The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the controlled qualification and limits: R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases; unchanged Common and broader Game Session physical/cross-service proof retain their R86 attribution. After the documentation-only parent carry, R93 freshly rebuilds `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code, passes held Gateway/Telnet denial and the isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline, and completes authenticated teardown with independent exact-project resource absence. Later parent documentation changes preserve that code. R110 verifies the controlled initial owner-to-owner composition retained at `c9bd1cebabcbd5c9d2f37084f8a728666d6c9674`: actual source and original-reference owners, authenticated Entity created capture and selected-owner read, and Game Session durable full receipt/replay. The same test proves mismatched actor/context denial and real current-target retirement refusal; created recovery/retirement/ACK and Human writer-refusal components retain their separate R105 attribution. Full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. ### Public character-creation and created-roster source preparation diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java index 0055ca400c..6d5018bae7 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java @@ -221,10 +221,6 @@ public EntityPlayerCreatedRosterSnapshotRepository snapshotRepository() { return snapshotRepository; } - public EntityCharacterCreateRepository characterCreateRepository() { - return characterCreateRepository; - } - public WireFixture wireFixture() { return wireFixture; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java index 1b38166869..cbb88dfb0d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -141,7 +141,7 @@ void actualCreatedTerminalCrossesAuthenticatedOwnersAndReplaysTheImmutableOrigin .build(); assertThatThrownBy(() -> owners.roster.listPlayerCreatedRoster(source, foreignContext)) .isInstanceOf(IllegalArgumentException.class); - assertThat(owners.gs.dsl().fetchCount(DSL.table("game_session_canonical_roster_selection"))) + assertThat(owners.gs.retainedOriginalReferenceCount()) .isEqualTo(1); assertThat( owners.entityDsl.fetchCount(DSL.table("entity_canonical_roster_original_selections"))) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java index d0107c3e47..94d6baa64f 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.nio.charset.StandardCharsets; @@ -103,6 +104,10 @@ public final class ControlledPlayerCreatedOriginalOwnerFixture { private final CanonicalPlayableTarget route; private final WireFixture wireFixture; + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The caller and fixture intentionally share the isolated DataSource and schema lifecycle.") public ControlledPlayerCreatedOriginalOwnerFixture( DriverManagerDataSource dataSource, WireFixture supplied, @@ -449,12 +454,8 @@ public CanonicalPublishedPlayerRouteReadService publishedRouteReader() { return publishedRouteReader; } - public DSLContext dsl() { - return dsl; - } - - public TransactionTemplate transactions() { - return transactions; + public int retainedOriginalReferenceCount() { + return dsl.fetchCount(DSL.table("game_session_canonical_roster_selection")); } private void migrate(String version) { From c9774094d76097ade5dcc5530d346e4960e613d8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:25:10 +1300 Subject: [PATCH 06/22] Apply canonical formatting to coupled owner proof --- .../PlayerCreatedRosterOwnerCompositionIntegrationTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java index cbb88dfb0d..605122a121 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -141,8 +141,7 @@ void actualCreatedTerminalCrossesAuthenticatedOwnersAndReplaysTheImmutableOrigin .build(); assertThatThrownBy(() -> owners.roster.listPlayerCreatedRoster(source, foreignContext)) .isInstanceOf(IllegalArgumentException.class); - assertThat(owners.gs.retainedOriginalReferenceCount()) - .isEqualTo(1); + assertThat(owners.gs.retainedOriginalReferenceCount()).isEqualTo(1); assertThat( owners.entityDsl.fetchCount(DSL.table("entity_canonical_roster_original_selections"))) .isEqualTo(1); From 4920bcefc961f679d2243b16695af74cc22695cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:31:08 +1300 Subject: [PATCH 07/22] Record current-parent created-roster qualification and remaining admission gap --- .../gameplay-rules-entities-and-effects.md | 4 +++- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index b57c9c042b..56cceab33e 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -10,7 +10,9 @@ This is a non-normative implementation tracker for gameplay rules, entities, and The unregistered composition implements Entity's `CHARACTER_CREATE` terminal writer and source-bound created-roster capture/readback, together with Common evidence and the immediate Game Session receipt consumer. Entity V1015 and V1016 retain the creation terminal and created snapshot branch; Game Session V1020 retains the distinct created receipt while preserving the strict preseeded branch. Canonical behavior belongs to the [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) and [sealed roster storage](../../architecture/microservices/entity-management-service/runtime-and-data.md#player-created-snapshot-storage). -R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases with affected static analysis, formatting and documentation checks. Unchanged Common and broader Game Session physical proof retain R86 attribution: 1,020 Common unit cases, 364 Game Session PostgreSQL cases and 36 cross-service cases. R86's earlier 396 Entity and 2,565 Game Session unit counts are superseded by the new executions, rather than credited as fresh runs. Native Entity proof includes the actual retained creation writer feeding authenticated source-bound snapshot capture; socket fixtures use controlled PKI and owner facts, including a complete 5 MiB terminal rather than physical proof at every maximum purpose bound. After the documentation-only parent carry, R93 rebuilds fresh images at `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project inspection confirms no remaining containers, networks or volumes. The subsequent public-parent documentation carry is code-identical. This validates controlled components, storage, packaging and the isolated backend baseline; it does not exercise a registered production created-actor flow. +Current-parent qualification receives #3295 at `cc33169ca1354872e101c4ef42777b0e79032473`, including its complete release/World validation correction. R116 passes the full Game Session check, formatting and affected static analysis with 2,568 unit cases, 365 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. This includes the actual initial owner-to-owner composition, which freshly passes in 30.763 seconds. The tested postimages are retained at `c9774094d76097ade5dcc5530d346e4960e613d8` after canonical fixture formatting. Unchanged Entity production source retains R113’s 402 unit and 94 PostgreSQL executions; R116 also passes both affected fixture static checks after correcting the earlier fixture-only SpotBugs failures. R117 freshly rebuilds that checkpoint and passes held Gateway/Telnet denial and isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK`, followed by authenticated teardown and independently confirmed exact-project container, network and volume absence. + +Prior component qualification R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases with affected static analysis, formatting and documentation checks. Unchanged Common and broader Game Session physical proof retain R86 attribution: 1,020 Common unit cases, 364 Game Session PostgreSQL cases and 36 cross-service cases. R86's earlier 396 Entity and 2,565 Game Session unit counts are superseded by the new executions, rather than credited as fresh runs. Native Entity proof includes the actual retained creation writer feeding authenticated source-bound snapshot capture; socket fixtures use controlled PKI and owner facts, including a complete 5 MiB terminal rather than physical proof at every maximum purpose bound. After the documentation-only parent carry, R93 rebuilds fresh images at `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project inspection confirms no remaining containers, networks or volumes. The documentation-only carry through parent `2aa25d9327bd9c15698c69168f2c96254f0fa732` preserves that code; the later release/World correction is qualified by R116 and R117 above. This validates controlled components, storage, packaging and the isolated backend baseline; it does not exercise a registered production created-actor flow. R110 verifies the controlled initial owner-to-owner composition retained at `c9bd1cebabcbd5c9d2f37084f8a728666d6c9674`: the actual Game Session source and durable original `ROSTER` owner connect through authenticated gRPC to Entity's actual creation writer, immutable created snapshot and selected-owner read, then persist and replay the exact full terminal in Game Session. The one coupled case also rejects a foreign selected actor and mismatched context without changing the original receipt, and the real current-source retirement owner refuses to retire the still-current target. R105 separately passes four Entity created-retention cases, six Game Session created-reference recovery/retirement/ACK cases with controlled upstream source facts, and the current Human reserve/commit/abort refusal case. These component results do not prove the missing current supersession writer. 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 ddd67fb79d..aa26d6d0bf 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. -The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the controlled qualification and limits: R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases; unchanged Common and broader Game Session physical/cross-service proof retain their R86 attribution. After the documentation-only parent carry, R93 freshly rebuilds `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code, passes held Gateway/Telnet denial and the isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline, and completes authenticated teardown with independent exact-project resource absence. Later parent documentation changes preserve that code. R110 verifies the controlled initial owner-to-owner composition retained at `c9bd1cebabcbd5c9d2f37084f8a728666d6c9674`: actual source and original-reference owners, authenticated Entity created capture and selected-owner read, and Game Session durable full receipt/replay. The same test proves mismatched actor/context denial and real current-target retirement refusal; created recovery/retirement/ACK and Human writer-refusal components retain their separate R105 attribution. Full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. +The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records current-parent qualification at `c9774094d76097ade5dcc5530d346e4960e613d8`, including #3295’s complete release/World validation correction. The full Game Session check and initial authenticated source → Entity created capture/selected read → durable Game Session receipt/replay composition pass, together with affected fixture static checks; fresh rebuilt held-edge denial, isolated backend transport checks and authenticated teardown also pass. Entity and Common component results retain their explicitly recorded source attribution. Created recovery/retirement/ACK and current Human writer-refusal components remain separate proof: full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. ### Public character-creation and created-roster source preparation From 1f421963530b6523e0b74b96c0a5f0684c42d2aa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:15:08 +1300 Subject: [PATCH 08/22] Bound physical created-roster composition RPCs for CI --- ...RosterOwnerCompositionIntegrationTest.java | 84 ++++++++++++++++++- 1 file changed, 80 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java index 605122a121..94d0b15f67 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -4,6 +4,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.grpc.BindableService; +import io.grpc.CallOptions; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; @@ -17,9 +21,12 @@ import java.time.Duration; import java.util.ArrayDeque; import java.util.Map; +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.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; @@ -28,6 +35,7 @@ import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRetentionPolicy; import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient; import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient; @@ -35,6 +43,8 @@ import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferencePolicy; import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; import net.firedevops.firemud.gamesession.testing.ControlledPlayerCreatedOriginalOwnerFixture; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.TestContainerImages; @@ -55,13 +65,21 @@ /** * Real owner stores and authenticated transports with explicitly controlled upstream authority. * This does not establish genuine Account ingress, production PKI, registration or player - * admission. + * admission, nor the production five-second RPC latency budget. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class PlayerCreatedRosterOwnerCompositionIntegrationTest { private static final String NAMESPACE = "test"; private static final Duration RETENTION = Duration.ofSeconds(20); + private static final long COUPLED_OWNER_TEST_RPC_SECONDS = 30L; + private static final Set COUPLED_OWNER_TEST_RPCS = + Set.of( + CanonicalGameplayRosterServiceGrpc.SERVICE_NAME + "/ListPlayerCreatedRoster", + CanonicalGameplayRosterServiceGrpc.SERVICE_NAME + "/ReadSelectedPlayerCreatedCharacter", + CharacterCreatePublicSourceServiceGrpc.SERVICE_NAME + "/ReadPlayerCreatedRosterSource", + CanonicalGameplayRosterOwnerReadServiceGrpc.SERVICE_NAME + + "/GetCanonicalGameplayRosterReference"); @Container static PostgreSQLContainer postgres = @@ -213,12 +231,12 @@ private Owners(Path directory) throws Exception { var sourceClient = own( new EntityPlayerCreatedRosterSourceClient( - endpoints, entityTls, new GrpcChannelFactory(), NAMESPACE)); + endpoints, entityTls, coupledOwnerTestChannels(), NAMESPACE)); sourceClient.init(); var originalClient = own( new GameSessionCanonicalGameplayRosterOwnerReadClient( - endpoints, entityTls, new GrpcChannelFactory(), NAMESPACE)); + endpoints, entityTls, coupledOwnerTestChannels(), NAMESPACE)); originalClient.init(); var migration = Flyway.configure() @@ -255,7 +273,7 @@ private Owners(Path directory) throws Exception { roster = own( new CanonicalPlayerCreatedRosterClient( - endpoints, gsTls, new GrpcChannelFactory(), NAMESPACE, gs.referenceOwner())); + endpoints, gsTls, coupledOwnerTestChannels(), NAMESPACE, gs.referenceOwner())); roster.init(); } catch (Exception failure) { try { @@ -331,6 +349,64 @@ public void close() throws Exception { } } + /** + * Keep real network, TLS and peer validation while allowing cold physical owner composition a + * bounded test-only budget. There are no retries; all other RPC call options remain unchanged. + */ + private static GrpcChannelFactory coupledOwnerTestChannels() { + return new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + var transport = super.buildChannel(target, defaultPort, properties, keepAlive); + return new ManagedChannel() { + @Override + public ClientCall newCall( + MethodDescriptor method, CallOptions options) { + var testOptions = + COUPLED_OWNER_TEST_RPCS.contains(method.getFullMethodName()) + ? options.withDeadlineAfter(COUPLED_OWNER_TEST_RPC_SECONDS, TimeUnit.SECONDS) + : options; + return transport.newCall(method, testOptions); + } + + @Override + public String authority() { + return transport.authority(); + } + + @Override + public ManagedChannel shutdown() { + transport.shutdown(); + return this; + } + + @Override + public ManagedChannel shutdownNow() { + transport.shutdownNow(); + return this; + } + + @Override + public boolean isShutdown() { + return transport.isShutdown(); + } + + @Override + public boolean isTerminated() { + return transport.isTerminated(); + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return transport.awaitTermination(timeout, unit); + } + }; + } + }; + } + private static DriverManagerDataSource dataSource(String schema) { var data = new DriverManagerDataSource( From 914f1ec20395360f68ebf0d9017b58ae37e9881c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:52:40 +1300 Subject: [PATCH 09/22] Document shutdown side effects in coupled roster test channel --- ...ayerCreatedRosterOwnerCompositionIntegrationTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java index 94d0b15f67..dd6d82d0ee 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.BindableService; import io.grpc.CallOptions; import io.grpc.ClientCall; @@ -377,12 +378,20 @@ public String authority() { } @Override + @SuppressFBWarnings( + value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", + justification = + "ManagedChannel.shutdown initiates shutdown; returning this preserves the wrapper's fluent identity.") public ManagedChannel shutdown() { transport.shutdown(); return this; } @Override + @SuppressFBWarnings( + value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", + justification = + "ManagedChannel.shutdownNow initiates shutdown; returning this preserves the wrapper's fluent identity.") public ManagedChannel shutdownNow() { transport.shutdownNow(); return this; From ec73c1264215bd4821f90e10c7974287b90ee649 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:29:20 +1300 Subject: [PATCH 10/22] fix(gameplay): preserve created roster failure and retirement contracts --- .../game-session-service/api-contracts.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- ...onicalGameplayRosterReferenceEvidence.java | 122 +++++-- ...nicalGameplayRosterRetirementEvidence.java | 112 ++++-- ...lGameplayRosterRetirementEvidenceTest.java | 75 ++++ .../EntityCharacterCreateRepository.java | 17 +- .../EntityCharacterCreateSource.java | 10 +- .../CanonicalGameplayRosterGrpcAdapter.java | 27 +- ...haracterCreatePostgresIntegrationTest.java | 136 ++++++- ...ayerCreatedRosterSourceClientMtlsTest.java | 332 ++---------------- ...anonicalGameplayRosterGrpcAdapterTest.java | 68 +++- ...olledPlayerCreatedRosterSourceFixture.java | 22 +- ...ionCharacterCreatePublicSourceService.java | 29 +- ...osterReferencePostgresIntegrationTest.java | 8 +- ...haracterCreatePublicSourceServiceTest.java | 22 +- 15 files changed, 587 insertions(+), 397 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 7f94e05333..2707b95cc2 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 @@ This document mixes live and target-state control-plane surfaces. Current live b Read the pause/status/recovery APIs below as the target-state contract unless the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) explicitly records them as live. -The unregistered created-owner consumer contains V1017 and V1020; V1020's created-receipt branch does not supply the separate canonical UUID runtime or creation-protection prerequisites. The [player-created roster consumer tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) records controlled initial source/receipt/replay qualification, separate recovery/retirement/ACK components and the still-unrun guarded post-issuance supersession composition. Production custody, Account settlement, production PKI, registration, activation and public admission remain unproved. The independently qualified public character-creation source-read contract above remains a separate boundary. +The unregistered created-owner consumer contains V1017 and V1020; V1020's created-receipt branch does not supply the separate canonical UUID runtime or creation-protection prerequisites. The [player-created roster consumer tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) records controlled initial source/receipt/replay qualification, separate recovery/retirement/ACK components and the still-unrun guarded post-issuance supersession composition. Production custody, Account settlement, production PKI, registration, activation and public admission remain unproved. The independently qualified [public character-creation source-read contract](#public-character-creation-source-read) remains a separate boundary. For script transitions, the live boundary includes the exact `scriptPinEpoch` and an atomic current-pin/request-result ledger commit; bounded authoritative history readback and append-only rollout history remain target-state gaps. Target pin and rollback requests require the explicit tagged `expectedCurrentPin` precondition defined in the [Scripting Control Plane API](../../system-architecture-scripting-control-plane-api.md): exactly `UNCONDITIONAL`, `EXPECT_UNPINNED`, or `EXPECT_EPOCH(scriptPinEpoch)`, with the complete tag/value included in the normalized digest. Missing/unknown tags fail validation; a both-absent tuple for a never-pinned instance is valid semantic `UNPINNED` and matches only `EXPECT_UNPINNED`; a partial tuple is invalid owner state, cannot satisfy `EXPECT_UNPINNED` or `EXPECT_EPOCH`, and is rejected/fails closed even for an `UNCONDITIONAL` request. Missing or unreadable authority is not `UNPINNED` and remains unavailable. `UNCONDITIONAL` is only the explicit `platformAdmin` break-glass repair branch with the matrix's `privileged_control` authorization; it skips only current-pin comparison and does not bypass coherent owner state, readiness, or other validation. See [Rollout and Rollback](../../system-architecture-scripting-rollout-and-rollback.md#pin-compare-and-set-preconditions) for the owner semantics. A valid precondition mismatch is deterministic and non-mutating and follows the existing idempotency/history semantics. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 56cceab33e..dcfb6a3db8 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -64,7 +64,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java index d60dc1a5e4..cd156a16ec 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java @@ -1,7 +1,14 @@ package net.firedevops.firemud.common.world; import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.MessageLite; +import java.io.IOException; +import java.io.OutputStream; +import java.security.DigestOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Objects; import java.util.UUID; @@ -76,6 +83,12 @@ public static GetCanonicalGameplayRosterReferenceRequest playerCreatedRequest( public static GetCanonicalGameplayRosterReferenceRequest requireRequest( GetCanonicalGameplayRosterReferenceRequest request) { + requireRequestTarget(request); + return request; + } + + private static CanonicalGameplayRosterTarget requireRequestTarget( + GetCanonicalGameplayRosterReferenceRequest request) { Objects.requireNonNull(request, "request"); if (request.getSerializedSize() > MAX_REQUEST_BYTES || !request.getUnknownFields().asMap().isEmpty() @@ -86,14 +99,14 @@ public static GetCanonicalGameplayRosterReferenceRequest requireRequest( uuid(request.getOperationUuid()); uuid(request.getCanonicalAccountUuid()); uuid(request.getSessionUuid()); - var target = target(request); + CanonicalGameplayRosterTarget target = target(request); if (isCreated(target)) { playerCreatedSourceIdentity(request); } else if (!request.getCanonicalPlayerCreatedSourceIdentity().isEmpty()) { throw new IllegalArgumentException( "PRESEEDED_ONLY original cannot carry PLAYER_CREATED source identity"); } - return request; + return target; } public static CanonicalGameplayRosterTarget target( @@ -239,6 +252,13 @@ public static CanonicalGameplayRosterResponse snapshotReceipt( public static CanonicalSelectedPlayerCreatedCharacterResponse selectedPlayerCreatedCharacterReceipt(GetCanonicalGameplayRosterReferenceResponse response) { var roster = playerCreatedReceipt(response).getRoster(); + return selectedPlayerCreatedCharacterReceipt(response, roster); + } + + private static CanonicalSelectedPlayerCreatedCharacterResponse + selectedPlayerCreatedCharacterReceipt( + GetCanonicalGameplayRosterReferenceResponse response, + CanonicalGameplayRosterResponse roster) { try { var bytes = response.getCanonicalSelectedPlayerCreatedCharacterReceipt(); if (bytes.isEmpty() || bytes.size() > MAX_SELECTED_PLAYER_CREATED_BYTES) { @@ -352,6 +372,19 @@ private static void requirePreseeded(CanonicalGameplayRosterTarget target) { selectedAssignmentReceipt(GetCanonicalGameplayRosterReferenceResponse response) { requirePreseeded(target(requireRequest(response.getRequest()))); rejectCreatedFields(response); + if (response.getCanonicalSelectedAssignmentReceipt().isEmpty() + || response.getCanonicalSelectedAssignmentReceipt().size() + > MAX_SELECTED_ASSIGNMENT_BYTES) { + throw new IllegalArgumentException("Complete original selected assignment receipt required"); + } + return selectedAssignmentReceipt(response, receipt(response)); + } + + private static net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSelectedAssignmentResponse + selectedAssignmentReceipt( + GetCanonicalGameplayRosterReferenceResponse response, + CanonicalGameplayRosterResponse roster) { try { if (response.getCanonicalSelectedAssignmentReceipt().isEmpty() || response.getCanonicalSelectedAssignmentReceipt().size() @@ -363,7 +396,6 @@ private static void requirePreseeded(CanonicalGameplayRosterTarget target) { net.firedevops.firemud.entitymanagement.v1 .CanonicalGameplayRosterSelectedAssignmentResponse.parseFrom( response.getCanonicalSelectedAssignmentReceipt()); - var roster = receipt(response); if (!selected.getUnknownFields().asMap().isEmpty() || !selected.getSnapshot().getUnknownFields().asMap().isEmpty() || !selected.toByteString().equals(response.getCanonicalSelectedAssignmentReceipt()) @@ -389,9 +421,21 @@ private static void requirePreseeded(CanonicalGameplayRosterTarget target) { public static GetCanonicalGameplayRosterReferenceResponse requireResponse( GetCanonicalGameplayRosterReferenceRequest expected, GetCanonicalGameplayRosterReferenceResponse response) { - requireRequest(expected); + return validateResponse(expected, response).response(); + } + + static CanonicalGameplayRosterResponse requireResponseSnapshot( + GetCanonicalGameplayRosterReferenceRequest expected, + GetCanonicalGameplayRosterReferenceResponse response) { + return validateResponse(expected, response).snapshotReceipt(); + } + + private static ValidatedResponse validateResponse( + GetCanonicalGameplayRosterReferenceRequest expected, + GetCanonicalGameplayRosterReferenceResponse response) { + CanonicalGameplayRosterTarget expectedTarget = requireRequestTarget(expected); Objects.requireNonNull(response, "response"); - boolean created = isCreated(target(expected)); + boolean created = isCreated(expectedTarget); if (created) { if (!response.getCanonicalRosterReceipt().isEmpty() || !response.getCanonicalSelectedAssignmentReceipt().isEmpty()) { @@ -409,31 +453,39 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( > MAX_SELECTED_PLAYER_CREATED_BYTES || !response.getUnknownFields().asMap().isEmpty() || !response.hasRequest() - || !expected.equals(requireRequest(response.getRequest())) || response.getOwnerFence() <= 0 || response.getCanonicalRosterReceipt().size() > MAX_RECEIPT_BYTES) { throw new IllegalArgumentException("Original roster selection owner binding is invalid"); } + if (!expected.equals(response.getRequest())) { + throw new IllegalArgumentException("Original roster selection owner binding is invalid"); + } boolean hasRoster = !response.getCanonicalRosterReceipt().isEmpty() || !response.getCanonicalPlayerCreatedRosterReceipt().isEmpty(); - if (hasRoster) snapshotReceipt(response); + CanonicalGameplayRosterResponse validatedRoster = hasRoster ? snapshotReceipt(response) : null; switch (response.getState()) { case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RESERVED -> { if (hasRoster) { throw new IllegalArgumentException("Reserved original selection cannot carry a receipt"); } } - case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED -> snapshotReceipt(response); + case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED -> { + if (!hasRoster) snapshotReceipt(response); + } case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_REPLAY_CLOSED -> { if (response.getTerminalOutcome().isEmpty()) { throw new IllegalArgumentException("Closed replay requires original terminal outcome"); } } - case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED -> requireRetirement(response); + case CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED -> + requireRetirementValidated(response, expectedTarget); default -> throw new IllegalArgumentException("Unknown original selection state"); } - uuid(response.getTargetFenceUuid()); + if (response.getState() + != CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) { + uuid(response.getTargetFenceUuid()); + } if (!response.getRecoveryUuid().isEmpty()) { uuid(response.getRecoveryUuid()); } @@ -458,7 +510,8 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( if (!response.getSelectedCharacterUuid().isEmpty()) { uuid(response.getSelectedCharacterUuid()); if (!response.hasSelectionInput() - || snapshotReceipt(response).getActorsList().stream() + || validatedRoster == null + || validatedRoster.getActorsList().stream() .filter( actor -> actor.getCharacterUuid().equals(response.getSelectedCharacterUuid())) .count() @@ -473,12 +526,16 @@ public static GetCanonicalGameplayRosterReferenceResponse requireResponse( throw new IllegalArgumentException( "Original assignment receipt requires a frozen chosen actor"); } - if (created) selectedPlayerCreatedCharacterReceipt(response); - else selectedAssignmentReceipt(response); + if (created) selectedPlayerCreatedCharacterReceipt(response, validatedRoster); + else selectedAssignmentReceipt(response, validatedRoster); } - return response; + return new ValidatedResponse(response, validatedRoster); } + private record ValidatedResponse( + GetCanonicalGameplayRosterReferenceResponse response, + CanonicalGameplayRosterResponse snapshotReceipt) {} + public static CanonicalGameplayRosterResponse receipt( GetCanonicalGameplayRosterReferenceResponse response) { requirePreseeded(target(requireRequest(response.getRequest()))); @@ -545,29 +602,30 @@ public static void requireDereference(GetCanonicalGameplayRosterReferenceRespons public static GetCanonicalGameplayRosterReferenceResponse sealRetirement( GetCanonicalGameplayRosterReferenceResponse response) { var unsigned = response.toBuilder().clearRetirementProofDigest().build(); - var sealed = - unsigned.toBuilder().setRetirementProofDigest(digest(unsigned.toByteArray())).build(); + var sealed = unsigned.toBuilder().setRetirementProofDigest(digest(unsigned)).build(); return requireResponse(response.getRequest(), sealed); } public static GetCanonicalGameplayRosterReferenceResponse requireRetirement( GetCanonicalGameplayRosterReferenceResponse response) { - requireRequest(response.getRequest()); + CanonicalGameplayRosterTarget target = requireRequestTarget(response.getRequest()); + return requireRetirementValidated(response, target); + } + + private static GetCanonicalGameplayRosterReferenceResponse requireRetirementValidated( + GetCanonicalGameplayRosterReferenceResponse response, CanonicalGameplayRosterTarget target) { if (!response.getUnknownFields().asMap().isEmpty() || response.getOwnerFence() <= 0 || response.getState() != CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED || !java.util.Set.of("MENU", "SELECTED", "DENIED").contains(response.getTerminalOutcome()) || !response.getSupersedingPointerDigest().matches("[0-9a-f]{64}") - || response.getSupersedingPointerVersion() - <= target(response.getRequest()).getPointerVersion() - || response.getSupersedingCatalogRevision() - < target(response.getRequest()).getCatalogRevision() - || response.getSupersedingWorldEpoch() < target(response.getRequest()).getActiveWorldEpoch() + || response.getSupersedingPointerVersion() <= target.getPointerVersion() + || response.getSupersedingCatalogRevision() < target.getCatalogRevision() + || response.getSupersedingWorldEpoch() < target.getActiveWorldEpoch() || !response .getRetirementProofDigest() - .equals( - digest(response.toBuilder().clearRetirementProofDigest().build().toByteArray()))) { + .equals(digest(response.toBuilder().clearRetirementProofDigest().build()))) { throw new IllegalArgumentException("Complete exact owner retirement proof required"); } uuid(response.getRetirementUuid()); @@ -575,12 +633,20 @@ < target(response.getRequest()).getCatalogRevision() return response; } - private static String digest(byte[] bytes) { + private static String digest(MessageLite message) { try { - return java.util.HexFormat.of() - .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); - } catch (java.security.NoSuchAlgorithmException unavailable) { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (DigestOutputStream digestOutput = + new DigestOutputStream(OutputStream.nullOutputStream(), digest)) { + CodedOutputStream codedOutput = CodedOutputStream.newInstance(digestOutput); + message.writeTo(codedOutput); + codedOutput.flush(); + } + return java.util.HexFormat.of().formatHex(digest.digest()); + } catch (NoSuchAlgorithmException unavailable) { throw new IllegalStateException(unavailable); + } catch (IOException failure) { + throw new IllegalStateException("Unable to hash canonical protobuf", failure); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java index cf61b5fc0d..07a1ebd273 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java @@ -1,5 +1,10 @@ package net.firedevops.firemud.common.world; +import com.google.protobuf.CodedOutputStream; +import com.google.protobuf.MessageLite; +import java.io.IOException; +import java.io.OutputStream; +import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Objects; @@ -7,6 +12,7 @@ import java.util.regex.Pattern; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationRequest; @@ -49,10 +55,13 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck if (!observed.hasRequest()) { throw new IllegalArgumentException("Complete observed retirement proof required"); } - GetCanonicalGameplayRosterReferenceRequest observedRequest = - CanonicalGameplayRosterReferenceEvidence.requireRequest(observed.getRequest()); - CanonicalGameplayRosterReferenceEvidence.requireResponse(observedRequest, observed); - CanonicalGameplayRosterReferenceEvidence.requireRetirement(observed); + if (observed.getState() + != CanonicalGameplayRosterReferenceState.CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) { + throw new IllegalArgumentException("Complete exact owner retirement proof required"); + } + GetCanonicalGameplayRosterReferenceRequest observedRequest = observed.getRequest(); + CanonicalGameplayRosterResponse observedRoster = + CanonicalGameplayRosterReferenceEvidence.requireResponseSnapshot(observedRequest, observed); CanonicalGameplayRosterRetirementEvidence.uuid(request.getObservationUuid()); CanonicalGameplayRosterRetirementEvidence.uuid(request.getAdmissionUuid()); @@ -78,8 +87,12 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck if (hasSnapshotUuid) { CanonicalGameplayRosterReferenceEvidence.uuid(request.getSnapshotUuid()); requireDigest(request.getSnapshotDigest()); - CanonicalGameplayRosterResponse roster = - CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(observed); + CanonicalGameplayRosterResponse roster = observedRoster; + if (roster == null) { + CanonicalGameplayRosterReferenceEvidence.snapshotReceipt(observed); + throw new IllegalArgumentException( + "Observed retirement does not bind the exact roster snapshot"); + } if (!roster.getSnapshotUuid().equals(request.getSnapshotUuid()) || !roster.getSnapshotDigest().equals(request.getSnapshotDigest()) || !roster.getCanonicalAccountUuid().equals(original.getCanonicalAccountUuid()) @@ -103,41 +116,51 @@ public static CanonicalGameplayRosterRetirementAcknowledgementRequest requireAck public static String requestDigest( CanonicalGameplayRosterRetirementAcknowledgementRequest request) { - return digest(requireAcknowledgement(request).toByteArray()); + return digest(requireAcknowledgement(request)); } public static CanonicalGameplayRosterRetirementAcknowledgementResponse response( CanonicalGameplayRosterRetirementAcknowledgementRequest request, UUID acknowledgementId, long effectiveMinimum) { - requireAcknowledgement(request); + var validatedRequest = requireAcknowledgement(request); requireUuid(acknowledgementId, "acknowledgementId"); - if (effectiveMinimum < request.getMinimumRetentionMillis()) { + if (effectiveMinimum < validatedRequest.getMinimumRetentionMillis()) { throw new IllegalArgumentException( "Effective retention minimum is below the requested minimum"); } - return requireAcknowledgementResponse( - request, + String requestDigest = digest(validatedRequest); + var response = CanonicalGameplayRosterRetirementAcknowledgementResponse.newBuilder() .setSchemaVersion(1) - .setObservationUuid(request.getObservationUuid()) + .setObservationUuid(validatedRequest.getObservationUuid()) .setAcknowledgementUuid(acknowledgementId.toString()) - .setRequestDigest(requestDigest(request)) + .setRequestDigest(requestDigest) .setMinimumRetentionMillis(effectiveMinimum) - .build()); + .build(); + return requireAcknowledgementResponseValidated(validatedRequest, response, requestDigest); } public static CanonicalGameplayRosterRetirementAcknowledgementResponse requireAcknowledgementResponse( CanonicalGameplayRosterRetirementAcknowledgementRequest request, CanonicalGameplayRosterRetirementAcknowledgementResponse response) { - requireAcknowledgement(request); + var validatedRequest = requireAcknowledgement(request); + return requireAcknowledgementResponseValidated( + validatedRequest, response, digest(validatedRequest)); + } + + private static CanonicalGameplayRosterRetirementAcknowledgementResponse + requireAcknowledgementResponseValidated( + CanonicalGameplayRosterRetirementAcknowledgementRequest request, + CanonicalGameplayRosterRetirementAcknowledgementResponse response, + String requestDigest) { Objects.requireNonNull(response, "response"); if (response.getSchemaVersion() != 1 || !response.getUnknownFields().asMap().isEmpty() || response.getSerializedSize() > MAX_RESPONSE_BYTES || !response.getObservationUuid().equals(request.getObservationUuid()) - || !response.getRequestDigest().equals(requestDigest(request)) + || !response.getRequestDigest().equals(requestDigest) || response.getMinimumRetentionMillis() < request.getMinimumRetentionMillis()) { throw new IllegalArgumentException("Retirement acknowledgement response binding is invalid"); } @@ -151,16 +174,28 @@ public static CanonicalGameplayRosterRetirementConfirmationRequest confirmation( CanonicalGameplayRosterRetirementAcknowledgementRequest request, CanonicalGameplayRosterRetirementAcknowledgementResponse response) { requireAcknowledgementResponse(request, response); - return requireConfirmation( + var confirmation = CanonicalGameplayRosterRetirementConfirmationRequest.newBuilder() .setSchemaVersion(1) .setAcknowledgementRequest(request) .setAcknowledgement(response) - .build()); + .build(); + requireConfirmationShape(confirmation); + requireConfirmationPolicyBound(confirmation); + return confirmation; } public static CanonicalGameplayRosterRetirementConfirmationRequest requireConfirmation( CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { + requireConfirmationShape(confirmation); + requireAcknowledgementResponse( + confirmation.getAcknowledgementRequest(), confirmation.getAcknowledgement()); + requireConfirmationPolicyBound(confirmation); + return confirmation; + } + + private static void requireConfirmationShape( + CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { Objects.requireNonNull(confirmation, "confirmation"); if (confirmation.getSchemaVersion() != 1 || !confirmation.getUnknownFields().asMap().isEmpty() @@ -169,8 +204,10 @@ public static CanonicalGameplayRosterRetirementConfirmationRequest requireConfir || !confirmation.hasAcknowledgement()) { throw new IllegalArgumentException("Closed bounded roster-retirement confirmation required"); } - requireAcknowledgementResponse( - confirmation.getAcknowledgementRequest(), confirmation.getAcknowledgement()); + } + + private static void requireConfirmationPolicyBound( + CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { if (confirmation.getSerializedSize() > acknowledgementLimit(confirmation.getAcknowledgementRequest().getOriginalSelection()) + MAX_RESPONSE_BYTES @@ -178,29 +215,35 @@ > acknowledgementLimit(confirmation.getAcknowledgementRequest().getOriginalSelec throw new IllegalArgumentException( "Retirement confirmation exceeds its policy-specific bound"); } - return confirmation; } public static CanonicalGameplayRosterRetirementConfirmationResponse confirmationResponse( CanonicalGameplayRosterRetirementConfirmationRequest confirmation) { - requireConfirmation(confirmation); - return requireConfirmationResponse( - confirmation, + var validatedConfirmation = requireConfirmation(confirmation); + String requestDigest = digest(validatedConfirmation); + var response = CanonicalGameplayRosterRetirementConfirmationResponse.newBuilder() .setSchemaVersion(1) - .setRequestDigest(digest(confirmation.toByteArray())) - .build()); + .setRequestDigest(requestDigest) + .build(); + return requireConfirmationResponseValidated(response, requestDigest); } public static CanonicalGameplayRosterRetirementConfirmationResponse requireConfirmationResponse( CanonicalGameplayRosterRetirementConfirmationRequest confirmation, CanonicalGameplayRosterRetirementConfirmationResponse response) { - requireConfirmation(confirmation); + var validatedConfirmation = requireConfirmation(confirmation); + return requireConfirmationResponseValidated(response, digest(validatedConfirmation)); + } + + private static CanonicalGameplayRosterRetirementConfirmationResponse + requireConfirmationResponseValidated( + CanonicalGameplayRosterRetirementConfirmationResponse response, String requestDigest) { Objects.requireNonNull(response, "response"); if (response.getSchemaVersion() != 1 || !response.getUnknownFields().asMap().isEmpty() || response.getSerializedSize() > MAX_RESPONSE_BYTES - || !response.getRequestDigest().equals(digest(confirmation.toByteArray()))) { + || !response.getRequestDigest().equals(requestDigest)) { throw new IllegalArgumentException("Retirement confirmation response binding is invalid"); } requireDigest(response.getRequestDigest()); @@ -231,11 +274,20 @@ private static void requireDigest(String digest) { } } - private static String digest(byte[] bytes) { + private static String digest(MessageLite message) { try { - return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (DigestOutputStream digestOutput = + new DigestOutputStream(OutputStream.nullOutputStream(), digest)) { + CodedOutputStream codedOutput = CodedOutputStream.newInstance(digestOutput); + message.writeTo(codedOutput); + codedOutput.flush(); + } + return java.util.HexFormat.of().formatHex(digest.digest()); } catch (NoSuchAlgorithmException unavailable) { throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } catch (IOException failure) { + throw new IllegalStateException("Unable to hash canonical protobuf", failure); } } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java index 195b5693f6..a0ea03a441 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java @@ -8,6 +8,7 @@ import java.security.MessageDigest; import java.util.HexFormat; import java.util.UUID; +import net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; @@ -60,6 +61,19 @@ void acceptsDifferentAnchorOperationOnlyForTheExactSharedSnapshotAndFence() { acknowledgement(original, anchorProof, "", ""))); } + @Test + void acknowledgementRequiresRetiredStateEvenWhenTheOwnerResponseBindingsMatch() { + var original = original(OPERATION, target()); + var reserved = + CanonicalGameplayRosterReferenceEvidence.response(original, 17L, TARGET_FENCE, null); + + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + acknowledgement(original, reserved, "", ""))); + } + @Test void rejectsChangedAccountTargetPolicyAndSnapshotPair() { var original = original(OPERATION, target()); @@ -170,6 +184,10 @@ void acknowledgementAndConfirmationBindExactRequestHashesAndHorizons() throws Ex var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation(request, response); var confirmationResponse = CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation); + assertEquals( + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(confirmation.toByteArray())), + confirmationResponse.getRequestDigest()); assertEquals( confirmationResponse, CanonicalGameplayRosterRetirementEvidence.requireConfirmationResponse( @@ -189,6 +207,63 @@ void acknowledgementAndConfirmationBindExactRequestHashesAndHorizons() throws Ex .build())); } + @Test + void createdFiveMebibyteAcknowledgementStreamsExactDigestsAndRejectsNestedTampering() + throws Exception { + var fixture = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection("gameplay"); + var request = fixture.acknowledgementRequest(); + var acknowledgement = fixture.acknowledgement(); + var confirmation = fixture.confirmation(); + + assertTrue(request.getSerializedSize() > 5 * 1024 * 1024); + var unsignedRetirement = + request.getObservedRetirement().toBuilder().clearRetirementProofDigest().build(); + assertEquals( + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(unsignedRetirement.toByteArray())), + request.getObservedRetirement().getRetirementProofDigest()); + assertEquals( + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(request.toByteArray())), + CanonicalGameplayRosterRetirementEvidence.requestDigest(request)); + assertEquals( + acknowledgement, + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgementResponse( + request, acknowledgement)); + var confirmationResponse = + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation); + assertEquals( + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(confirmation.toByteArray())), + confirmationResponse.getRequestDigest()); + assertEquals( + confirmationResponse, + CanonicalGameplayRosterRetirementEvidence.requireConfirmationResponse( + confirmation, confirmationResponse)); + + var changedRetirement = + request.toBuilder() + .setObservedRetirement( + request.getObservedRetirement().toBuilder() + .setSupersedingPointerVersion( + request.getObservedRetirement().getSupersedingPointerVersion() + 1L)) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(changedRetirement)); + + var changedConfirmation = + confirmation.toBuilder() + .setAcknowledgement( + acknowledgement.toBuilder().setRequestDigest("0".repeat(64)).build()) + .build(); + assertThrows( + IllegalArgumentException.class, + () -> CanonicalGameplayRosterRetirementEvidence.requireConfirmation(changedConfirmation)); + } + @Test void createdRetirementCarriesTheCompleteSelectedTerminalAndBindsCrossOriginalSourceIdentity() { var fixture = CanonicalGameplayRosterReferenceEvidenceTest.createdFixture(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java index 7558020a3a..80e8ef053e 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java @@ -183,7 +183,7 @@ private static EntityCharacterCreateTerminal readStoredPlayerCreatedTerminal( EntityCharacterCreateBindings.requireOriginal( creation.getOriginalRequest().getOriginal(), creation.getAccountOriginal()); } catch (RuntimeException malformed) { - throw corruptRoster(); + throw corruptRoster(malformed); } if (creation.getOutcome() != EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED @@ -218,7 +218,7 @@ private static EntityCharacterCreateTerminal readStoredPlayerCreatedTerminal( .equals(actor.get("creation_descriptor_digest", String.class))) throw corruptRoster(); if (!published.matches(action) || !published.targetNamespace().equals(operationNamespace)) { if (sourceMismatchIsUnavailable) throw selectedPlayerCreatedActorUnavailable(); - throw corruptRoster(); + throw publishedPlayerCreatedSourceMismatch(); } return creation; } @@ -234,12 +234,25 @@ private static RuntimeException selectedPlayerCreatedActorUnavailable() { .asRuntimeException(); } + private static RuntimeException publishedPlayerCreatedSourceMismatch() { + return Status.FAILED_PRECONDITION + .withDescription("Current PLAYER_CREATED source does not match the retained character") + .asRuntimeException(); + } + private static RuntimeException corruptRoster() { return Status.DATA_LOSS .withDescription("Stored PLAYER_CREATED roster provenance is inconsistent") .asRuntimeException(); } + private static RuntimeException corruptRoster(Throwable cause) { + return Status.DATA_LOSS + .withDescription("Stored PLAYER_CREATED roster provenance is inconsistent") + .withCause(cause) + .asRuntimeException(); + } + EntityCharacterCreateTerminal settle(EntityCharacterCreateProofs proof, String abortRequestId) { outsideTransaction(); if (abortRequestId != null) EntityCharacterCreateBindings.id(abortRequestId); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java index dadf2687a5..059aa42815 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.entitymanagement.charactercreate; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; @@ -32,12 +33,17 @@ public EntityEmptySelectedSourceIntakeReceipt read(CharacterCreateOperatorAction UUID.fromString(action.scope().tenantId()), UUID.fromString(action.target().versionId())); if (association == null) - throw new IllegalStateException("Genuine Entity selected source is unavailable"); + throw Status.UNAVAILABLE + .withDescription("Genuine Entity selected source association is unavailable") + .asRuntimeException(); var receipt = intakes .read(action.scope().targetNamespace(), association.get(0, UUID.class)) .orElseThrow( - () -> new IllegalStateException("Entity selected source receipt is unavailable")); + () -> + Status.UNAVAILABLE + .withDescription("Entity selected source receipt is unavailable") + .asRuntimeException()); var owner = receipt.inputs().worldInventoryReadEvidence().inventory().publicEvidence().ownerScope(); if (!action.scope().targetNamespace().equals(receipt.targetNamespace()) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java index e0998f9778..b6e8392aa6 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java @@ -66,7 +66,11 @@ public final class CanonicalGameplayRosterGrpcAdapter "CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED", "CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT", "CANONICAL_ROSTER_ORIGINAL_SELECTION_CHANGED", - "CANONICAL_ROSTER_SNAPSHOT_STALE"); + "CANONICAL_ROSTER_SNAPSHOT_STALE", + "CANONICAL_ROSTER_ORIGINAL_DEREFERENCE_CLOSED", + "CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT", + "CANONICAL_ROSTER_LOCAL_ADMISSION_DISPOSED", + "CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT"); private final CanonicalGameplayRosterService rosterService; private final CanonicalGameplayRosterSelectedAssignmentService selectedAssignmentService; @@ -104,9 +108,13 @@ public void listPlayerCreatedRoster( requireTrustedPeer(); CanonicalPlayerCreatedRosterEvidence.requireRequest(request); if (playerCreatedRosterService == null) throw new PlayerCreatedRosterUnavailableException(); - response = - CanonicalPlayerCreatedRosterEvidence.requireResponse( - request, playerCreatedRosterService.list(request)); + var serviceResponse = playerCreatedRosterService.list(request); + try { + response = CanonicalPlayerCreatedRosterEvidence.requireResponse(request, serviceResponse); + } catch (IllegalArgumentException invalidOutput) { + throw new IllegalStateException( + "PLAYER_CREATED roster service returned an invalid response", invalidOutput); + } } catch (Exception failure) { responseObserver.onError( toPlayerCreatedStatus(failure, "CanonicalGameplayRoster.ListPlayerCreatedRoster")); @@ -126,9 +134,14 @@ public void readSelectedPlayerCreatedCharacter( requireTrustedPeer(); CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest(request); if (playerCreatedRosterService == null) throw new PlayerCreatedRosterUnavailableException(); - response = - CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( - request, playerCreatedRosterService.selected(request)); + var serviceResponse = playerCreatedRosterService.selected(request); + try { + response = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, serviceResponse); + } catch (IllegalArgumentException invalidOutput) { + throw new IllegalStateException( + "PLAYER_CREATED roster service returned an invalid selected response", invalidOutput); + } } catch (Exception failure) { responseObserver.onError( toPlayerCreatedStatus( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index c831a5db95..d912f2b826 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -358,11 +358,80 @@ void emptyDiscoveryAllocatesNothingAndOmitsLegacyQuarantinedDecoys() throws Exce } @Test - void rejectsCurrentIdentityAndRetainedDescriptorProvenanceMismatch() throws Exception { + void missingSelectedSourceIsUnavailableButAChangedSourceBindingConflicts() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID()); + var action = proof.action(); + var sourceReader = + new EntityCharacterCreateSource(dsl, new EntityEmptySelectedSourceIntakeRepository(dsl)); + var missingAssociationAction = + new CharacterCreateOperatorAction( + new CharacterCreateOperatorAction.Scope( + "missing", + action.scope().tenantId(), + action.scope().playableStateNamespaceId(), + action.scope().playableStateScope()), + action.target(), + action.expectedVersion(), + action.mutation(), + action.auditReason()); + assertThatThrownBy(() -> sourceReader.read(missingAssociationAction)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("UNAVAILABLE"); + + var missingReceiptIntakes = mock(EntityEmptySelectedSourceIntakeRepository.class); + when(missingReceiptIntakes.read(source.targetNamespace(), source.intakeRequestId())) + .thenReturn(java.util.Optional.empty()); + var missingReceiptReader = new EntityCharacterCreateSource(dsl, missingReceiptIntakes); + assertThatThrownBy(() -> missingReceiptReader.read(action)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("UNAVAILABLE"); + + var authored = action.mutation().authoredSource(); + var changedAuthored = + new CharacterCreateOperatorAction.AuthoredSource( + authored.schema(), + authored.bindingId(), + authored.bindingDigest(), + authored.canonicalTenantId(), + authored.canonicalVersionId(), + authored.worldSourceOperationId(), + authored.worldSourceEvidenceDigest(), + authored.worldSlug(), + authored.publicationWorkflowId(), + authored.selectedCommitId(), + "sha256:" + "f".repeat(64), + authored.policy(), + authored.core(), + authored.descriptor(), + authored.disposition(), + authored.safeFeedback()); + var changedBindingAction = + new CharacterCreateOperatorAction( + action.scope(), + action.target(), + action.expectedVersion(), + new CharacterCreateOperatorAction.Mutation( + action.mutation().purpose(), + action.mutation().entryPolicy(), + action.mutation().catalog(), + action.mutation().pointer(), + changedAuthored, + action.mutation().canonicalCreationInput()), + action.auditReason()); + assertThatThrownBy(() -> sourceReader.read(changedBindingAction)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("ALREADY_EXISTS"); + } + + @Test + void changedPublishedProjectionFailsClosedAndStoredProvenanceCorruptionIsDataLoss() + throws Exception { UUID account = UUID.randomUUID(); var proof = proof(account, UUID.randomUUID()); var terminal = repository.settle(proof, null); var published = published(proof); + var changedPublishedSource = publishedWithChangedWorkflow(proof); + assertThat(changedPublishedSource.matches(proof.action())).isFalse(); var changedRealm = new PublishedIdentity( published.targetNamespace(), @@ -373,18 +442,63 @@ void rejectsCurrentIdentityAndRetainedDescriptorProvenanceMismatch() throws Exce published.playableStateNamespaceId(), published.canonicalVersionId(), published.projection()); + UUID characterId = UUID.fromString(terminal.getCharacterId()); + var actorBefore = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, to_jsonb(c)::text AS retained_row FROM characters c WHERE character_uuid = ?", + characterId)); + var operationBefore = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, to_jsonb(o)::text AS retained_row FROM entity_character_create_operations o WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))); + int actorCountBefore = dsl.fetchCount(DSL.table("characters")); + assertThatThrownBy( + () -> + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(account), changedPublishedSource)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("FAILED_PRECONDITION"); + assertThatThrownBy( + () -> + repository.readSelectedPlayerCreatedTerminal( + new AuthenticatedAccountSelector(account), changedPublishedSource, characterId)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("FAILED_PRECONDITION"); assertThatThrownBy( () -> repository.readPlayerCreatedRoster( new AuthenticatedAccountSelector(account), changedRealm)) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .hasMessageContaining("DATA_LOSS"); + .hasMessageContaining("FAILED_PRECONDITION"); + var actorAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, to_jsonb(c)::text AS retained_row FROM characters c WHERE character_uuid = ?", + characterId)); + var operationAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, to_jsonb(o)::text AS retained_row FROM entity_character_create_operations o WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))); + assertThat(actorAfter.get("row_version", String.class)) + .isEqualTo(actorBefore.get("row_version", String.class)); + assertThat(actorAfter.get("retained_row", String.class)) + .isEqualTo(actorBefore.get("retained_row", String.class)); + assertThat(operationAfter.get("row_version", String.class)) + .isEqualTo(operationBefore.get("row_version", String.class)); + assertThat(operationAfter.get("retained_row", String.class)) + .isEqualTo(operationBefore.get("retained_row", String.class)); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(actorCountBefore); dsl.execute("ALTER TABLE characters DISABLE TRIGGER trg_entity_created_actor_immutable"); try { dsl.execute( "UPDATE characters SET creation_descriptor_json = '{}' WHERE character_uuid = ?", - UUID.fromString(terminal.getCharacterId())); + characterId); assertThatThrownBy( () -> repository.readPlayerCreatedRoster( @@ -806,13 +920,27 @@ private static CharacterCreateOperatorAction.Rule authoredRule( } private static PublishedIdentity published(EntityCharacterCreateProofs proof) throws Exception { + return published(proof, null); + } + + private static PublishedIdentity publishedWithChangedWorkflow(EntityCharacterCreateProofs proof) + throws Exception { + return published(proof, UUID.randomUUID().toString()); + } + + private static PublishedIdentity published( + EntityCharacterCreateProofs proof, String currentPublicationWorkflowId) throws Exception { var json = tools.jackson.databind.json.JsonMapper.builder().build(); var root = json.readTree(proof.original().getOriginalAction().toByteArray()); var action = proof.action(); var authored = action.mutation().authoredSource(); var projectionNode = (tools.jackson.databind.node.ObjectNode) root.get("mutation").get("authoredSource"); - projectionNode.put("publicationWorkflowId", authored.publicationWorkflowId()); + projectionNode.put( + "publicationWorkflowId", + currentPublicationWorkflowId == null + ? authored.publicationWorkflowId() + : currentPublicationWorkflowId); ((tools.jackson.databind.node.ObjectNode) projectionNode.get("policy")) .put("logicalRevisionId", authored.policy().logicalRevisionId()) .put("canonicalPolicyJson", authored.policy().canonicalPolicyJson()); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java index 281775cdc8..4eca2550bf 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java @@ -10,42 +10,20 @@ import com.google.protobuf.UnknownFieldSet; import io.grpc.Status; import io.grpc.StatusRuntimeException; -import java.io.IOException; import java.nio.file.Path; import java.util.List; -import java.util.Map; import java.util.UUID; -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 java.util.stream.Stream; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; -import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreSourceBinding; import net.firedevops.firemud.common.gamedesign.CommandSource; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; -import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; -import net.firedevops.firemud.common.gamedesign.RealmPolicySource; -import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; -import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; -import net.firedevops.firemud.common.operator.StartSessionOperatorAction; -import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; -import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; -import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.testing.PlayerCreatedPublishedPolicyFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient.InvalidOwnerEvidenceException; @@ -58,6 +36,9 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -283,14 +264,14 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws List.of( AuthoredInitialActorCoreProjection.fromValidatedBinding( FIXTURE_ID, - sourceBinding( + ControlledPlayerCreatedRosterSourceFixture.sourceBinding( authored.associationRead().association(), authored.associationRead().association().sourceOperationId(), false))))); var extraProjection = AuthoredInitialActorCoreProjection.fromValidatedBinding( UUID.randomUUID(), - sourceBinding( + ControlledPlayerCreatedRosterSourceFixture.sourceBinding( authored.associationRead().association(), authored.associationRead().association().sourceOperationId())); var ambiguousProjections = @@ -432,7 +413,8 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws .build(), good.toBuilder() .setAuthoredSource( - good.getAuthoredSource().toBuilder().setResultDigest(digest('0'))) + good.getAuthoredSource().toBuilder() + .setResultDigest(ControlledPlayerCreatedRosterSourceFixture.digest('0'))) .build(), good.toBuilder() .setAuthoredSource( @@ -542,6 +524,33 @@ void unavailableTransportIsNotReclassifiedAsInvalidOwnerEvidence() throws Except } } + @ParameterizedTest + @MethodSource("ownerFailures") + void ownerGrpcFailuresRemainTransportStatuses(Status status, String description) + throws Exception { + try (var owner = controlled.owner("server"); + var client = controlled.client(owner)) { + client.init(); + owner.failWith(status.withDescription(description).asRuntimeException()); + + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()).isEqualTo(status.getCode()); + assertThat(failure.getStatus().getDescription()).isEqualTo(description); + }); + assertThat(owner.receivedRequests()).containsExactly(fixture.request()); + } + } + + private static Stream ownerFailures() { + return Stream.of( + Arguments.of(Status.UNAVAILABLE, "owner temporarily unavailable"), + Arguments.of(Status.FAILED_PRECONDITION, "owner source is not ready"), + Arguments.of(Status.INVALID_ARGUMENT, "owner rejected the source request")); + } + @Test void inboundTransportRejectsResponseBeyond32MiBBeforeSourceDecoding() throws Exception { try (var owner = controlled.owner("server"); @@ -568,275 +577,4 @@ private static UnknownFieldSet unknown() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); } - - private static StartSessionPostAuthorizationExecutionTuple postTuple( - UUID tenant, String namespace) { - StartSessionPreAuthorizationReservationTuple pre = - StartSessionPreAuthorizationReservationTuple.createHuman( - "world-lifecycle-control-request", - FIXTURE_ID, - new StartSessionOperatorAction( - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, - StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(tenant, namespace), - new StartSessionOperatorAction.Target(19L, FIXTURE_ID), - StartSessionOperatorAction.ExpectedVersion.ABSENT, - new StartSessionOperatorAction.Mutation( - StartSessionOperatorAction.ClientIp.absent()), - "exact original selected authored actor core")); - return StartSessionPostAuthorizationExecutionTuple.createHuman( - pre, - "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", - "arfp/v1/test-key/" + "b".repeat(64), - FIXTURE_ID, - 19L, - authorityBundle(pre, tenant, namespace), - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "17", - "23", - "18446744073709551615")); - } - - private static byte[] authorityBundle( - StartSessionPreAuthorizationReservationTuple tuple, UUID tenant, String namespace) { - String tenantText = tenant.toString(); - Map value = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", Map.of("tenantId", tenantText, "targetNamespace", namespace), - "actionFamily", tuple.actionFamily(), - "applicableAccountId", FIXTURE_ID.toString(), - "applicableTenantId", tenantText), - "accountProjectionEvidence", - Map.of( - "sourceType", "ACCOUNT", - "sourceEvidenceId", digest('a'), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", "2026-10-09T00:00:00Z", - "expiresAt", "2026-10-09T00:05:00Z"), - "issuanceOperationIdentity", - Map.of( - "issuanceOperationId", FIXTURE_ID.toString(), - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()), - "issuanceKind", - "human_operator", - "authorityTuple", - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenantText, 3L), - "membershipAuthorityGeneration", Map.of(tenantText, 4L), - "privateRealmGrantVersions", List.of()), - "membershipVersion", - Map.of(tenantText, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - Map.of( - "evidenceType", - StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", - FIXTURE_ID.toString(), - "controlUiTokenJti", - FIXTURE_ID.toString(), - "role", - "tenantAdmin", - "accountGeneration", - "2", - "tenantGeneration", - "3")); - try { - return net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( - tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(value)); - } catch (IOException invalid) { - throw new IllegalStateException(invalid); - } - } - - private static AuthoredInitialActorCoreSourceBinding sourceBinding( - StartSessionTemplateAssociationReadEvidence.Association association, - UUID worldSourceOperationId) - throws Exception { - return sourceBinding(association, worldSourceOperationId, true); - } - - private static AuthoredInitialActorCoreSourceBinding sourceBinding( - StartSessionTemplateAssociationReadEvidence.Association association, - UUID worldSourceOperationId, - boolean visible) - throws Exception { - var policy = - RealmEntryPolicy.parse( - "{\"schemaVersion\":3,\"worldSlug\":\"" - + association.worldSlug() - + "\",\"worldDisplayName\":\"Synthetic World\"," - + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":" - + visible - + "," - + "\"publicProduction\":true,\"stateScope\":\"SHARED\"," - + "\"entryPolicy\":\"PLAYER_CREATED\",\"creationDescriptor\":{" - + "\"schemaVersion\":1,\"descriptorId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\"," - + "\"descriptorRevisionId\":\"bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb\"," - + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," - + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}", - tools.jackson.databind.json.JsonMapper.builder().build()); - var policyPayload = - RealmPolicySource.canonical( - Map.of( - "revisionKind", - RealmPolicySource.REVISION_KIND, - "logicalRevisionId", - "policy-logical-r1", - "policy", - RealmPolicySource.tree(policy.canonicalJson()))); - var disposition = new Disposition("newcomer", List.of(), "welcome"); - var feedback = - new Feedback( - "welcome", - "actor_created", - Audience.SOURCE_ACTOR, - "welcome_message", - "Welcome, traveler.", - List.of(), - Visibility.PUBLIC, - GameplayRuleManifest.ReplayPolicy.EFFECT_IDEMPOTENT); - List revisions = - List.of( - new RevisionPayload( - "0", - UUID.fromString("13333333-3333-4333-8333-333333333333"), - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - policyPayload), - new RevisionPayload( - "1", - UUID.fromString("14444444-4444-4444-8444-444444444444"), - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.upsertPayload(disposition)), - new RevisionPayload( - "2", - UUID.fromString("15555555-5555-4555-8555-555555555555"), - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.upsertPayload(feedback))); - TargetProof target = - new TargetProof( - association.canonicalTenantId(), - association.canonicalVersionId(), - 42L, - "tenant-key", - 42L, - "tenant-key", - "NEW_GAME_ROW"); - DraftCommitBinding commit = - DraftCommitBinding.create( - target, - UUID.fromString("1eeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - association.selectedCommitId(), - "base-0", - revisions, - List.of( - new AffectedUnit( - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - RealmPolicySource.SCOPE, - association.canonicalVersionId().toString(), - RealmPolicySource.SCOPE, - "effective", - "0"), - new AffectedUnit( - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - GameplayRuleSource.SCOPE, - association.canonicalVersionId().toString(), - GameplayRuleSource.SCOPE, - GameplayRuleSource.SCOPE_ID, - "0"))); - commit = PlayerCreatedPublishedPolicyFixtures.withWorldSource(commit); - var selectedPolicy = RealmPolicySource.revision(commit, revisions.getFirst()); - var policySnapshot = new RealmPolicySnapshot(commit, "1", List.of(selectedPolicy)); - var dispositionEntry = - new GameplayRuleSource.Entry( - Family.DISPOSITIONS, - disposition, - commit, - "1", - UUID.fromString("14444444-4444-4444-8444-444444444444")); - var feedbackEntry = - new GameplayRuleSource.Entry( - Family.FEEDBACK, - feedback, - commit, - "2", - UUID.fromString("15555555-5555-4555-8555-555555555555")); - var gameplay = - new GameplayRuleSelectedSource( - gameplaySnapshot(commit, List.of(dispositionEntry, feedbackEntry))); - return AuthoredInitialActorCoreSourceBinding.resolveAll( - worldSourceOperationId, - association.sourceEvidenceDigest(), - association.worldSlug(), - association.publishWorkflowId(), - bytes("selected publication operation bytes"), - bytes("selected release terminal evidence"), - commit, - policySnapshot, - gameplay) - .getFirst(); - } - - private static String gameplaySnapshot( - DraftCommitBinding binding, List entries) { - Map families = new java.util.LinkedHashMap<>(); - for (Family family : Family.values()) { - families.put( - family.name(), - entries.stream() - .filter(value -> value.family() == family) - .map(GameplayRuleSource.Entry::definition) - .toList()); - } - var manifest = - GameplayRuleManifest.fromStored( - GameplayRuleManifest.canonical( - Map.of("schema", GameplayRuleManifest.SCHEMA, "families", families))); - Map snapshot = new java.util.LinkedHashMap<>(); - snapshot.put("schema", "game-design-gameplay-rule-source-snapshot/v1"); - snapshot.put("bindingJson", binding.canonicalJson()); - snapshot.put("bindingDigest", binding.digest()); - snapshot.put("sourceEpoch", "1"); - snapshot.put("inheritedCommitId", ""); - snapshot.put("genesisReceiptId", "77777777-7777-4777-8777-777777777777"); - snapshot.put("manifestJson", manifest.canonicalJson()); - snapshot.put( - "entries", - entries.stream() - .map( - entry -> - Map.of( - "family", entry.family().name(), - "definitionJson", GameplayRuleManifest.canonical(entry.definition()), - "sourceBindingJson", entry.sourceBinding().canonicalJson(), - "sourceBindingDigest", entry.sourceBinding().digest(), - "revisionOrder", entry.revisionOrder(), - "revisionId", entry.revisionId().toString())) - .toList()); - return CommandSource.canonical(snapshot); - } - - private static byte[] bytes(String value) { - return value.getBytes(java.nio.charset.StandardCharsets.UTF_8); - } - - private static String digest(char value) { - return "sha256:" + String.valueOf(value).repeat(64); - } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java index 41dacccf2e..1c5e81d5ef 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java @@ -456,12 +456,13 @@ void legacyConstructorReturnsUnavailableForBothUnregisteredCreatedMethods() { @Test void createdMethodsValidateFullServiceResponsesBeforeReturningThem() { var createdService = mock(EntityPlayerCreatedRosterService.class); + var meterRegistry = new SimpleMeterRegistry(); var adapter = new CanonicalGameplayRosterGrpcAdapter( mock(CanonicalGameplayRosterService.class), mock(CanonicalGameplayRosterSelectedAssignmentService.class), createdService, - new SimpleMeterRegistry()); + meterRegistry); var request = playerCreatedRequest(); when(createdService.list(request)) .thenReturn( @@ -473,7 +474,7 @@ void createdMethodsValidateFullServiceResponsesBeforeReturningThem() { withTrustedPeer( CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, () -> adapter.listPlayerCreatedRoster(request, listObserver)); - assertOnlyStatus(listObserver, Status.Code.INVALID_ARGUMENT); + assertOnlyStatus(listObserver, Status.Code.INTERNAL); verify(createdService).list(request); var selectedRequest = selectedCreatedRequest(); @@ -488,8 +489,69 @@ void createdMethodsValidateFullServiceResponsesBeforeReturningThem() { withTrustedPeer( CanonicalGameplayRosterPeerInterceptor.SELECTED_PLAYER_CREATED_METHOD_NAME, () -> adapter.readSelectedPlayerCreatedCharacter(selectedRequest, selectedObserver)); - assertOnlyStatus(selectedObserver, Status.Code.INVALID_ARGUMENT); + assertOnlyStatus(selectedObserver, Status.Code.INTERNAL); verify(createdService).selected(selectedRequest); + assertThat(meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count()).isEqualTo(2.0); + + var malformedCallerService = mock(EntityPlayerCreatedRosterService.class); + var malformedCallerAdapter = + new CanonicalGameplayRosterGrpcAdapter( + mock(CanonicalGameplayRosterService.class), + mock(CanonicalGameplayRosterSelectedAssignmentService.class), + malformedCallerService, + new SimpleMeterRegistry()); + var malformedListObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, + () -> + malformedCallerAdapter.listPlayerCreatedRoster( + playerCreatedRequest().toBuilder().setCanonicalAccountUuid("malformed").build(), + malformedListObserver)); + assertOnlyStatus(malformedListObserver, Status.Code.INVALID_ARGUMENT); + + var malformedSelectedObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1 + .CanonicalSelectedPlayerCreatedCharacterResponse>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.SELECTED_PLAYER_CREATED_METHOD_NAME, + () -> + malformedCallerAdapter.readSelectedPlayerCreatedCharacter( + selectedCreatedRequest().toBuilder().setCanonicalAccountUuid("malformed").build(), + malformedSelectedObserver)); + assertOnlyStatus(malformedSelectedObserver, Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(malformedCallerService); + } + + @Test + void expectedOwnerRejectionsReturnFailedPreconditionWithoutPartialResponse() { + for (String reasonCode : + java.util.List.of( + "CANONICAL_ROSTER_ORIGINAL_DEREFERENCE_CLOSED", + "CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT", + "CANONICAL_ROSTER_LOCAL_ADMISSION_DISPOSED", + "CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT")) { + var createdService = mock(EntityPlayerCreatedRosterService.class); + when(createdService.list(any())).thenThrow(new IllegalStateException(reasonCode)); + var adapter = + new CanonicalGameplayRosterGrpcAdapter( + mock(CanonicalGameplayRosterService.class), + mock(CanonicalGameplayRosterSelectedAssignmentService.class), + createdService, + new SimpleMeterRegistry()); + var observer = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse>(); + + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, + () -> adapter.listPlayerCreatedRoster(playerCreatedRequest(), observer)); + + assertOnlyStatus(observer, Status.Code.FAILED_PRECONDITION); + verify(createdService).list(any()); + } } @Test diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java index 98f49c6f34..4ea2d7b673 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java @@ -4,6 +4,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; @@ -123,6 +124,7 @@ public CommonGrpcClientProperties clientProperties(String identityName) public Owner owner(String identityName) throws Exception { var response = new AtomicReference<>(fixture.response()); + var failure = new AtomicReference(); var received = new CopyOnWriteArrayList(); var observedPeer = new AtomicReference(); var identity = pki.identity(identityName); @@ -144,6 +146,11 @@ public void readPlayerCreatedRosterSource( StreamObserver observer) { observedPeer.set(GrpcPeerIdentity.current().uri()); received.add(request); + StatusRuntimeException nextFailure = failure.get(); + if (nextFailure != null) { + observer.onError(nextFailure); + return; + } observer.onNext(response.get()); observer.onCompleted(); } @@ -151,7 +158,7 @@ public void readPlayerCreatedRosterSource( new GrpcPeerIdentityInterceptor())) .build() .start(); - return new Owner(server, response, received, observedPeer); + return new Owner(server, response, failure, received, observedPeer); } public EntityPlayerCreatedRosterSourceClient client(Owner owner) throws Exception { @@ -165,16 +172,19 @@ public EntityPlayerCreatedRosterSourceClient client(Owner owner) throws Exceptio public static final class Owner implements AutoCloseable { private final Server server; private final AtomicReference response; + private final AtomicReference failure; private final List received; private final AtomicReference observedPeer; private Owner( Server server, AtomicReference response, + AtomicReference failure, List received, AtomicReference observedPeer) { this.server = server; this.response = response; + this.failure = failure; this.received = received; this.observedPeer = observedPeer; } @@ -191,6 +201,10 @@ public void respondWith(ReadPlayerCreatedRosterSourceResponse nextResponse) { response.set(Objects.requireNonNull(nextResponse, "nextResponse")); } + public void failWith(StatusRuntimeException nextFailure) { + failure.set(Objects.requireNonNull(nextFailure, "nextFailure")); + } + @Override public void close() throws InterruptedException { server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); @@ -621,14 +635,14 @@ private static byte[] authorityBundle( } } - private static AuthoredInitialActorCoreSourceBinding sourceBinding( + public static AuthoredInitialActorCoreSourceBinding sourceBinding( StartSessionTemplateAssociationReadEvidence.Association association, UUID worldSourceOperationId) throws Exception { return sourceBinding(association, worldSourceOperationId, true); } - private static AuthoredInitialActorCoreSourceBinding sourceBinding( + public static AuthoredInitialActorCoreSourceBinding sourceBinding( StartSessionTemplateAssociationReadEvidence.Association association, UUID worldSourceOperationId, boolean visible) @@ -792,7 +806,7 @@ private static byte[] bytes(String value) { return value.getBytes(StandardCharsets.UTF_8); } - private static String digest(char value) { + public static String digest(char value) { return "sha256:" + String.valueOf(value).repeat(64); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java index 098be81f15..201dd909a3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java @@ -215,18 +215,23 @@ public ResolvedPlayerCreatedRosterSource resolvePlayerCreatedRosterSource( .setPublishedPolicySetEvidence(ByteString.copyFrom(facts.policySet().canonicalBytes())) .build(); if (response.getSerializedSize() > MAX_RESPONSE_BYTES) throw missing(); - var descriptor = - PlayerCreationDescriptor.parse(facts.projection().descriptor().canonicalJson()); - var sourceIdentity = - CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( - CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() - .setSchemaVersion(1) - .setDescriptorUuid(descriptor.descriptorId()) - .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) - .setDescriptorDigest(descriptor.digest()) - .setAuthoredBindingUuid(facts.projection().bindingId().toString()) - .setAuthoredBindingDigest(facts.projection().bindingDigest()) - .build()); + final PlayerCreationDescriptor descriptor; + final CanonicalPlayerCreatedRosterSourceIdentity sourceIdentity; + try { + descriptor = PlayerCreationDescriptor.parse(facts.projection().descriptor().canonicalJson()); + sourceIdentity = + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(descriptor.descriptorId()) + .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) + .setDescriptorDigest(descriptor.digest()) + .setAuthoredBindingUuid(facts.projection().bindingId().toString()) + .setAuthoredBindingDigest(facts.projection().bindingDigest()) + .build()); + } catch (IllegalArgumentException malformedSourceIdentity) { + throw missing(); + } var route = facts.route(); var target = CanonicalGameplayRosterTarget.newBuilder() diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index a3cae68689..1fbae283d2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -2053,7 +2053,7 @@ void createdRecoveryClosesMissingSelectedReceiptAndRequiresEveryExactEntityAck() @Test void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterReceipt() throws Exception { - repository = new CanonicalGameplayRosterReferenceRepository(dsl, policy(5000L, 5000L, 5000L)); + repository = repository(policy(500L, 500L, 500L)); var fixture = createdFixture(false); var original = fixture.original(); transaction.executeWithoutResult( @@ -2062,7 +2062,7 @@ void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterR repository.reserveSelectionInput(original, selectionInput()); repository.markRosterReadStarted(original); }); - Thread.sleep(5500L); + Thread.sleep(550L); var recovery = transaction .execute(ignored -> repository.beginRecoveries(original, current(original))) @@ -2087,7 +2087,7 @@ void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterR transaction.execute( ignored -> repository.recordPlayerCreated(original, fixture.roster()))) .hasMessageContaining("RECOVERY_FENCED"); - Thread.sleep(5500L); + Thread.sleep(550L); assertThat( transaction.execute( ignored -> repository.sealTargetRetirement(original, current(original)))) @@ -2097,7 +2097,7 @@ void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterR assertThat(acknowledgement.getSnapshotUuid()).isEmpty(); transaction.execute( ignored -> repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original))); - Thread.sleep(5500L); + Thread.sleep(550L); var candidate = new CanonicalGameplayRosterReferenceRepository.TargetCandidate( UUID.fromString(proof.getTargetFenceUuid()), original, "RETIRED"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java index 1566075849..da0686a450 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java @@ -147,11 +147,29 @@ void resolvedCreatedSourceBindsActualSelectedTargetDescriptorAndAuthoredIdentity @Test void resolvedCreatedSourceRejectsMalformedDescriptorBindingAndChangedAuthoredReadback() { - List> invalidations = + List> malformedSourceIdentities = List.of( fixture -> when(fixture.projection.descriptor().canonicalJson()).thenReturn("{}"), + fixture -> when(fixture.projection.bindingDigest()).thenReturn("d".repeat(64))); + for (var invalidate : malformedSourceIdentities) { + try (var fixture = new Fixture()) { + invalidate.accept(fixture); + assertThatThrownBy(() -> fixture.service.resolvePlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo( + "Exact original public CHARACTER_CREATE source is unavailable or changed"); + }); + } + } + + List> invalidations = + List.of( fixture -> when(fixture.projection.bindingId()).thenReturn(new UUID(0L, 0L)), - fixture -> when(fixture.projection.bindingDigest()).thenReturn("d".repeat(64)), fixture -> when(fixture.policyEvidence.policyDigest()).thenReturn("c".repeat(64)), fixture -> when(fixture.authored.canonicalBytes()).thenReturn(new byte[] {9}), fixture -> when(fixture.projection.canonicalTenantId()).thenReturn(UUID.randomUUID()), From ebf1950e07e312ce71572d2d5c82be6551047ba2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 22:31:00 +1300 Subject: [PATCH 11/22] Fix created-roster source errors and bounded receipt validation --- .../api-contracts.md | 2 +- ...onicalGameplayRosterReferenceEvidence.java | 57 ++- ...alGameplayRosterReferenceEvidenceTest.java | 73 +++ ...lGameplayRosterRetirementEvidenceTest.java | 50 ++ .../EntityCharacterCreateRepository.java | 5 +- .../EntityPlayerCreatedRosterService.java | 2 +- ...PlayerCreatedRosterSnapshotRepository.java | 8 +- .../CanonicalGameplayRosterGrpcAdapter.java | 7 +- ...haracterCreatePostgresIntegrationTest.java | 70 +++ ...RosterSnapshotPostgresIntegrationTest.java | 21 +- ...tySelectedSourceIntakePostgresFixture.java | 412 +---------------- ...anonicalGameplayRosterGrpcAdapterTest.java | 28 +- ...trolledPlayerCreatedOwnerStoreFixture.java | 437 +----------------- ...ledSelectedSourceIntakeFixtureBuilder.java | 429 +++++++++++++++++ ...osterReferencePostgresIntegrationTest.java | 12 +- 15 files changed, 751 insertions(+), 862 deletions(-) create mode 100644 services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 6b336d18ae..75d55fa02d 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -65,7 +65,7 @@ curl http://localhost:8080/ping - `CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse)` – Current behavior: the scalar-only request validates tenant, account, and scope, then Entity returns an application `FAILED_PRECONDITION` before `CharacterService` allocation because the request cannot carry the authenticated owner proof and durable operation binding. Target behavior remains 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. This target boundary remains an implementation/proof gap; current implementation proves denial only. - `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` (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. +- `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 specifies the existing `PRESEEDED_ONLY` branch and the distinct, unregistered `PLAYER_CREATED` methods `ListPlayerCreatedRoster` and `ReadSelectedPlayerCreatedCharacter`. `AUTO_PROVISIONED` remains a later-owned target branch, 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/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java index cd156a16ec..23be502f67 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidence.java @@ -9,7 +9,6 @@ import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.Arrays; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; @@ -39,6 +38,7 @@ public final class CanonicalGameplayRosterReferenceEvidence { public static final int MAX_SELECTED_PLAYER_CREATED_BYTES = CanonicalPlayerCreatedRosterEvidence.MAX_SELECTED_RECEIPT_BYTES; public static final int MAX_PLAYER_CREATED_RESPONSE_BYTES = 194 * 1024 * 1024; + private static final int CANONICAL_COMPARISON_BUFFER_BYTES = 4096; private CanonicalGameplayRosterReferenceEvidence() {} @@ -115,7 +115,7 @@ public static CanonicalGameplayRosterTarget target( CanonicalGameplayRosterTarget target = CanonicalGameplayRosterTarget.parseFrom(request.getCanonicalTarget()); if (!target.getUnknownFields().asMap().isEmpty() - || !Arrays.equals(target.toByteArray(), request.getCanonicalTarget().toByteArray()) + || !hasCanonicalEncoding(target, request.getCanonicalTarget()) || target.getCatalogRevision() <= 0 || target.getPointerVersion() <= 0 || target.getActiveWorldEpoch() <= 0 @@ -207,7 +207,7 @@ public static CanonicalPlayerCreatedRosterSourceIdentity playerCreatedSourceIden var source = CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( CanonicalPlayerCreatedRosterSourceIdentity.parseFrom(bytes)); - if (!bytes.equals(source.toByteString())) { + if (!hasCanonicalEncoding(source, bytes)) { throw new IllegalArgumentException( "PLAYER_CREATED source identity bytes are not canonical"); } @@ -231,7 +231,7 @@ public static CanonicalPlayerCreatedRosterResponse playerCreatedReceipt( "Complete bounded PLAYER_CREATED roster receipt required"); } var roster = CanonicalPlayerCreatedRosterResponse.parseFrom(bytes); - if (!bytes.equals(roster.toByteString())) { + if (!hasCanonicalEncoding(roster, bytes)) { throw new IllegalArgumentException("PLAYER_CREATED roster receipt bytes are not canonical"); } return CanonicalPlayerCreatedRosterEvidence.requireResponse( @@ -266,7 +266,7 @@ public static CanonicalGameplayRosterResponse snapshotReceipt( "Complete bounded selected PLAYER_CREATED terminal required"); } var selected = CanonicalSelectedPlayerCreatedCharacterResponse.parseFrom(bytes); - if (!bytes.equals(selected.toByteString())) { + if (!hasCanonicalEncoding(selected, bytes)) { throw new IllegalArgumentException( "Selected PLAYER_CREATED receipt bytes are not canonical"); } @@ -398,7 +398,7 @@ private static void requirePreseeded(CanonicalGameplayRosterTarget target) { response.getCanonicalSelectedAssignmentReceipt()); if (!selected.getUnknownFields().asMap().isEmpty() || !selected.getSnapshot().getUnknownFields().asMap().isEmpty() - || !selected.toByteString().equals(response.getCanonicalSelectedAssignmentReceipt()) + || !hasCanonicalEncoding(selected, response.getCanonicalSelectedAssignmentReceipt()) || !selected.getRequestUuid().equals(response.getRequest().getOperationUuid()) || !selected .getCanonicalAccountUuid() @@ -547,7 +547,7 @@ public static CanonicalGameplayRosterResponse receipt( } var receipt = CanonicalGameplayRosterResponse.parseFrom(bytes); if (!receipt.getUnknownFields().asMap().isEmpty() - || !bytes.equals(receipt.toByteString()) + || !hasCanonicalEncoding(receipt, bytes) || !receipt .getCanonicalAccountUuid() .equals(response.getRequest().getCanonicalAccountUuid()) @@ -585,6 +585,49 @@ private static void rejectCreatedFields(GetCanonicalGameplayRosterReferenceRespo } } + /** Compares canonical protobuf output byte-for-byte without materializing a second wire value. */ + private static boolean hasCanonicalEncoding(MessageLite message, ByteString bytes) { + if (message.getSerializedSize() != bytes.size()) return false; + ByteString.ByteIterator expected = bytes.iterator(); + final class ComparingOutputStream extends OutputStream { + private long offset; + private boolean matches = true; + + @Override + public void write(int value) { + if (!expected.hasNext()) { + matches = false; + } else if (expected.nextByte() != (byte) value) { + matches = false; + } + offset++; + } + + @Override + public void write(byte[] values, int start, int length) { + for (int index = 0; index < length; index++) { + if (!expected.hasNext()) { + matches = false; + } else if (expected.nextByte() != values[start + index]) { + matches = false; + } + offset++; + } + } + } + + ComparingOutputStream comparison = new ComparingOutputStream(); + try { + CodedOutputStream codedOutput = + CodedOutputStream.newInstance(comparison, CANONICAL_COMPARISON_BUFFER_BYTES); + message.writeTo(codedOutput); + codedOutput.flush(); + return comparison.matches && comparison.offset == bytes.size() && !expected.hasNext(); + } catch (IOException failure) { + throw new IllegalStateException("Unable to compare canonical protobuf", failure); + } + } + public static void requireDereference(GetCanonicalGameplayRosterReferenceResponse response) { requireResponse(response.getRequest(), response); if (!response.getRecoveryUuid().isEmpty() diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java index e975c759d8..391e0759ba 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java @@ -8,6 +8,7 @@ import com.google.protobuf.UnknownFieldSet; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; @@ -324,6 +325,78 @@ void createdMenuAndSelectedReplayRetainTheDistinctCompleteOriginalCreationReceip } } + @Test + void fiveMebibyteSelectedReceiptRequiresExactCanonicalBytesAndRejectsTamperingAndOversize() + throws Exception { + var fixture = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection("gameplay"); + var original = fixture.original(); + var canonicalSelectedBytes = original.getCanonicalSelectedPlayerCreatedCharacterReceipt(); + + assertThat(canonicalSelectedBytes.size()).isGreaterThan(5 * 1024 * 1024); + int midpoint = canonicalSelectedBytes.size() / 2; + var ropeBackedCanonicalBytes = + canonicalSelectedBytes + .substring(0, midpoint) + .concat(canonicalSelectedBytes.substring(midpoint, canonicalSelectedBytes.size())); + var ropeBackedOriginal = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt(ropeBackedCanonicalBytes) + .build(); + assertThat( + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), ropeBackedOriginal)) + .isEqualTo(ropeBackedOriginal); + + var duplicateRequestField = + new byte[CodedOutputStream.computeStringSize(1, fixture.selected().getRequestUuid())]; + var codedOutput = CodedOutputStream.newInstance(duplicateRequestField); + codedOutput.writeString(1, fixture.selected().getRequestUuid()); + codedOutput.checkNoSpaceLeft(); + var noncanonical = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + canonicalSelectedBytes.concat(ByteString.copyFrom(duplicateRequestField))) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), noncanonical)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Selected PLAYER_CREATED receipt bytes are not canonical"); + + var tamperedSelected = + fixture.selected().toBuilder() + .setTarget( + fixture.selected().getTarget().toBuilder() + .setPointerVersion(fixture.selected().getTarget().getPointerVersion() + 1L) + .build()) + .build(); + var tampered = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt(tamperedSelected.toByteString()) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), tampered)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("binding changed"); + + var oversized = + original.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + logicalBytes( + CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES + 1)) + .build(); + assertThatThrownBy( + () -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), oversized)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Original roster selection owner binding is invalid"); + } + @Test void createdSourceBytesAndPolicyBranchesAreClosedAndMutuallyExclusive() { var fixture = createdFixture(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java index a0ea03a441..05435d4845 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidenceTest.java @@ -4,7 +4,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.UnknownFieldSet; +import java.io.OutputStream; +import java.security.DigestOutputStream; import java.security.MessageDigest; import java.util.HexFormat; import java.util.UUID; @@ -243,6 +247,40 @@ void createdFiveMebibyteAcknowledgementStreamsExactDigestsAndRejectsNestedTamper CanonicalGameplayRosterRetirementEvidence.requireConfirmationResponse( confirmation, confirmationResponse)); + var duplicateRequestField = + new byte[CodedOutputStream.computeStringSize(1, fixture.selected().getRequestUuid())]; + var codedOutput = CodedOutputStream.newInstance(duplicateRequestField); + codedOutput.writeString(1, fixture.selected().getRequestUuid()); + codedOutput.checkNoSpaceLeft(); + var observedRetirement = request.getObservedRetirement(); + var noncanonicalRetirement = + observedRetirement.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + observedRetirement + .getCanonicalSelectedPlayerCreatedCharacterReceipt() + .concat(ByteString.copyFrom(duplicateRequestField))) + .build(); + // Recompute the wire seal so ACK validation reaches the canonical receipt check. This is a + // controlled value fixture and does not establish the owner authority of the proof. + var unsignedNoncanonicalRetirement = + noncanonicalRetirement.toBuilder().clearRetirementProofDigest().build(); + var sealedNoncanonicalRetirement = + unsignedNoncanonicalRetirement.toBuilder() + .setRetirementProofDigest(streamedDigest(unsignedNoncanonicalRetirement)) + .build(); + var noncanonicalFailure = + assertThrows( + IllegalArgumentException.class, + () -> + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement( + request.toBuilder() + .setObservedRetirement(sealedNoncanonicalRetirement) + .build())); + assertTrue( + noncanonicalFailure + .getMessage() + .contains("Selected PLAYER_CREATED receipt bytes are not canonical")); + var changedRetirement = request.toBuilder() .setObservedRetirement( @@ -481,4 +519,16 @@ private static CanonicalGameplayRosterTarget target(int variant) { private static UUID uuid(long value) { return new UUID(0L, value); } + + private static String streamedDigest(GetCanonicalGameplayRosterReferenceResponse response) + throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + try (DigestOutputStream digestOutput = + new DigestOutputStream(OutputStream.nullOutputStream(), digest)) { + CodedOutputStream codedOutput = CodedOutputStream.newInstance(digestOutput); + response.writeTo(codedOutput); + codedOutput.flush(); + } + return HexFormat.of().formatHex(digest.digest()); + } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java index 80e8ef053e..07d7c5f2e1 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java @@ -552,9 +552,12 @@ private static EntityCharacterCreateTerminal terminal(Record row) { throw new IllegalStateException("Corrupt abort terminal"); } return terminal; - } catch (InvalidProtocolBufferException | IllegalArgumentException corrupt) { + } catch (InvalidProtocolBufferException + | IllegalArgumentException + | IllegalStateException corrupt) { throw Status.DATA_LOSS .withDescription("Stored creation terminal is invalid") + .withCause(corrupt) .asRuntimeException(); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java index 143913b310..488249edc1 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java @@ -90,7 +90,7 @@ public CanonicalSelectedPlayerCreatedCharacterResponse selected( var sourceIdentity = EntityPlayerCreatedRosterSnapshotRepository.sourceIdentity(source); if (!source.target().toWire().equals(request.getExpectedTarget()) || !sourceIdentity.equals(request.getExpectedSource())) { - throw new IllegalArgumentException("Current PLAYER_CREATED source binding changed"); + throw new IllegalStateException("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); } var published = EntityPlayerCreatedRosterReadService.PublishedIdentity.from(source); var expectedOriginal = diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java index 5a343b6ac4..c23e44afa2 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java @@ -63,11 +63,11 @@ public CanonicalPlayerCreatedRosterResponse capture( var target = request.getExpectedTarget(); if (!source.target().toWire().equals(target)) { - throw new IllegalArgumentException("Current PLAYER_CREATED target changed"); + throw new IllegalStateException("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); } var sourceIdentity = sourceIdentity(source); if (!request.getExpectedSource().equals(sourceIdentity)) { - throw new IllegalArgumentException("Current PLAYER_CREATED source identity changed"); + throw new IllegalStateException("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); } var published = EntityPlayerCreatedRosterReadService.PublishedIdentity.from(source); var expectedOriginal = @@ -173,11 +173,11 @@ public CanonicalSelectedPlayerCreatedCharacterResponse readSelected( var target = request.getExpectedTarget(); if (!source.target().toWire().equals(target)) { - throw new IllegalArgumentException("Current PLAYER_CREATED target changed"); + throw new IllegalStateException("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); } var sourceIdentity = sourceIdentity(source); if (!request.getExpectedSource().equals(sourceIdentity)) { - throw new IllegalArgumentException("Current PLAYER_CREATED source identity changed"); + throw new IllegalStateException("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); } var published = EntityPlayerCreatedRosterReadService.PublishedIdentity.from(source); var createdRequest = diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java index b6e8392aa6..fbedc06d9b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java @@ -70,7 +70,8 @@ public final class CanonicalGameplayRosterGrpcAdapter "CANONICAL_ROSTER_ORIGINAL_DEREFERENCE_CLOSED", "CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT", "CANONICAL_ROSTER_LOCAL_ADMISSION_DISPOSED", - "CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT"); + "CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT", + "CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); private final CanonicalGameplayRosterService rosterService; private final CanonicalGameplayRosterSelectedAssignmentService selectedAssignmentService; @@ -410,6 +411,10 @@ private RuntimeException toPlayerCreatedStatus(Exception failure, String operati Status.UNAVAILABLE .withDescription("Owner evidence is unavailable") .asRuntimeException(); + case DEADLINE_EXCEEDED -> + Status.UNAVAILABLE + .withDescription("Owner evidence is unavailable") + .asRuntimeException(); case RESOURCE_EXHAUSTED -> Status.RESOURCE_EXHAUSTED .withDescription("PLAYER_CREATED roster exceeds its bounded size") diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index d912f2b826..22daa073c3 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -251,6 +251,76 @@ void actualWriterFeedsDeterministicReadWithoutChangingRetainedRows() throws Exce .containsExactly(beforeOperation.get("terminal_bytes", byte[].class)); } + @Test + void storedSourceMismatchReturnsDataLossWithCauseAndNoReadEffects() throws Exception { + UUID accountId = UUID.randomUUID(); + var proof = proof(accountId, UUID.randomUUID()); + var terminal = repository.settle(proof, null); + UUID characterId = UUID.fromString(terminal.getCharacterId()); + byte[] corruptedTerminal = + terminal.toBuilder() + .setEntitySourceReceiptDigest(terminal.getEntitySourceReceiptDigest() + "x") + .build() + .toByteArray(); + + dsl.execute( + "ALTER TABLE entity_character_create_operations DISABLE TRIGGER trg_entity_character_create_operation_immutable"); + try { + dsl.execute( + "UPDATE entity_character_create_operations SET terminal_bytes = ? WHERE target_namespace = ? AND operation_id = ?", + corruptedTerminal, + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId())); + } finally { + dsl.execute( + "ALTER TABLE entity_character_create_operations ENABLE TRIGGER trg_entity_character_create_operation_immutable"); + } + + var actorBefore = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, to_jsonb(c)::text AS retained_row FROM characters c WHERE character_uuid = ?", + characterId)); + var operationBefore = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, encode(terminal_bytes, 'hex') AS terminal_hex FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))); + int actorCountBefore = dsl.fetchCount(DSL.table("characters")); + + assertThatThrownBy( + () -> + repository.readSelectedPlayerCreatedTerminal( + new AuthenticatedAccountSelector(accountId), published(proof), characterId)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> { + var status = (io.grpc.StatusRuntimeException) failure; + assertThat(status.getStatus().getCode()).isEqualTo(io.grpc.Status.Code.DATA_LOSS); + assertThat(status.getStatus().getDescription()) + .isEqualTo("Stored creation terminal is invalid"); + assertThat(status.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Corrupt creation source identity"); + }); + + var actorAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, to_jsonb(c)::text AS retained_row FROM characters c WHERE character_uuid = ?", + characterId)); + var operationAfter = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT xmin::text AS row_version, encode(terminal_bytes, 'hex') AS terminal_hex FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))); + assertThat(actorAfter.intoMap()).isEqualTo(actorBefore.intoMap()); + assertThat(operationAfter.intoMap()).isEqualTo(operationBefore.intoMap()); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(actorCountBefore); + } + @Test void selectedReadReturnsExactCommittedTerminalAndRejectsOutOfRosterActors() throws Exception { UUID accountId = UUID.randomUUID(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java index 2e5c14737f..b7bd026084 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java @@ -335,11 +335,14 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E inputs.request().getExpectedSource().toBuilder() .setDescriptorUuid(UUID.randomUUID().toString())) .build(); + var beforeSelectedSourceMismatch = rosterRowCounts(); assertThatThrownBy( () -> snapshotRepository.readSelected( substitutedSource, inputs.source(), selectedOriginal)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); + assertThat(rosterRowCounts()).isEqualTo(beforeSelectedSourceMismatch); UUID otherAccount = UUID.randomUUID(); var substitutedAccount = selectedRequest.toBuilder() @@ -498,12 +501,14 @@ void substitutedSourceAccountSessionAndOriginalNamespaceRefuseBeforeSnapshotWrit UUID.fromString(inputs.request().getCanonicalAccountUuid()), UUID.fromString(inputs.request().getPlayerExecutionContext().getSessionId()), changedSource); + var beforeSourceSubstitution = rosterRowCounts(); assertThatThrownBy( () -> repository.capture( sourceSubstitution, inputs.source(), inputs.original(), admission)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("source identity changed"); + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); + assertThat(rosterRowCounts()).isEqualTo(beforeSourceSubstitution); UUID otherAccount = UUID.randomUUID(); var accountSubstitution = @@ -617,6 +622,16 @@ private void enroll(UUID tenant, UUID namespace) { namespace); } + private Map rosterRowCounts() { + var counts = + dsl.fetchSingle( + "SELECT (SELECT count(*) FROM entity_canonical_gameplay_roster_snapshots) AS snapshots, (SELECT count(*) FROM entity_canonical_gameplay_roster_snapshot_actors) AS actors, (SELECT count(*) FROM entity_canonical_roster_original_selections) AS originals"); + return Map.of( + "snapshots", counts.get("snapshots", Long.class), + "actors", counts.get("actors", Long.class), + "originals", counts.get("originals", Long.class)); + } + private void insertBuildingSnapshot(UUID snapshot, UUID tenant, UUID namespace, byte[] source) { dsl.execute( "INSERT INTO entity_canonical_gameplay_roster_snapshots (snapshot_uuid, snapshot_digest, canonical_account_uuid, tenant_uuid, realm_uuid, world_slug, realm_slug, game_instance_uuid, catalog_revision, canonical_version_uuid, pointer_version, active_world_epoch, published_policy_digest, published_release_bundle_ref, admission_pointer_snapshot_digest, published_owner_proof_digest, playable_state_namespace_uuid, playable_state_scope, entry_policy, publication_evidence_format, canonical_player_created_source_identity, roster_count, construction_state) VALUES (?, ?, ?, ?, ?, 'world', 'realm', ?, 3, ?, 5, 7, ?, 'published-release', ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 'PLAYER_CREATED', 'CANONICAL_UUID_V2', ?, 0, 'BUILDING')", diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java index 1b3b353c46..9dcf853c80 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java @@ -1,81 +1,24 @@ package net.firedevops.firemud.entitymanagement.repository; -import java.io.ByteArrayOutputStream; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.time.OffsetDateTime; import java.util.List; -import java.util.Map; -import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; -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.Owner; import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; -import net.firedevops.firemud.common.gamedesign.AssetSnapshot; -import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSnapshot; -import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; -import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; -import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; -import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; -import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; +import net.firedevops.firemud.entitymanagement.testing.ControlledSelectedSourceIntakeFixtureBuilder; -/** - * Test-only synthetic inputs built through the same typed Common decoders as the shared fixture. - * They are not authenticated Account or World producer evidence or physical owner proof. - */ +/** Integration-test facade preserving the selected-source fixture's established defaults. */ public final class EntityEmptySelectedSourceIntakePostgresFixture { static final String NAMESPACE = "test"; static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); - private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); - private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); - private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); - private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - - private static final String TEMPLATE_CONFIG = - "{\"schemaVersion\":1,\"baseVersionId\":\"" - + VERSION - + "\",\"world\":{\"regions\":[],\"rooms\":[]}," - + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," - + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," - + "\"supportedSettings\":[]}"; - private EntityEmptySelectedSourceIntakePostgresFixture() {} public static Fixture create(String sourceEpoch) { @@ -83,26 +26,14 @@ public static Fixture create(String sourceEpoch) { } public static Fixture create(String sourceEpoch, DraftCommitBinding selected) { - Objects.requireNonNull(selected, "selected"); - var scope = - new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( - Owner.ENTITY_MANAGEMENT, NAMESPACE, OPERATION, FENCE, INTAKE_REQUEST, ACTOR, selected); - TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); - SelectedOwnerIntakeAuthorizationBinding authorization = - new SelectedOwnerIntakeAuthorizationBinding( - sourceContent(scope, templateSnapshot), accountSources()); - WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected); - var inventory = - WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( - freeze, publicInventory(freeze)); - var worldRequest = - SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freeze); - var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + return create(sourceEpoch, selected, NAMESPACE); + } + + public static Fixture create(String sourceEpoch, DraftCommitBinding selected, String namespace) { + var shared = + ControlledSelectedSourceIntakeFixtureBuilder.create(sourceEpoch, selected, namespace); return new Fixture( - authorization, - freeze, - worldEvidence, - new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + shared.authorization(), shared.freezeEvidence(), shared.worldEvidence(), shared.inputs()); } static Fixture withFreshWorldReadCorrelation(Fixture original) { @@ -118,139 +49,6 @@ static Fixture withFreshWorldReadCorrelation(Fixture original) { new SelectedOwnerEmptySourceInputs(original.authorization(), evidence)); } - private static TemplateConfigSourceSnapshot templateSnapshot( - DraftCommitBinding selected, String sourceEpoch) { - var declaration = - EntityAuthoredSourceInventoryDeclaration.parse( - "{\"schema\":\"entity-authored-source-inventory/v1\"," - + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" - + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," - + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," - + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," - + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," - + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," - + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," - + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," - + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," - + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," - + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," - + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," - + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); - String declarationPayload = - TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration); - DraftCommitBinding authored = authoredBinding(declarationPayload, selected.target()); - TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = - TemplateConfigSourceValues.mutations(authored).stream() - .filter( - mutation -> - mutation.operation() - == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) - .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) - .findFirst() - .orElseThrow(); - return new TemplateConfigSourceSnapshot( - selected, - sourceEpoch, - authored.commitId(), - GENESIS_RECEIPT, - List.of(), - List.of(ownerDeclaration)); - } - - private static DraftCommitBinding authoredBinding(String payload, TargetProof target) { - return DraftCommitBinding.create( - target, - id("51515151-5151-4151-8151-515151515151"), - id("52525252-5252-4252-8252-525252525252"), - "base-commit-0", - List.of( - new RevisionPayload( - "0", - id("53535353-5353-4353-8353-535353535353"), - Owner.GAME_DESIGN_CONTROL_PLANE, - payload)), - List.of( - new DraftCommitBinding.AffectedUnit( - Owner.GAME_DESIGN_CONTROL_PLANE, - TemplateConfigSourceValues.SCOPE, - VERSION.toString(), - TemplateConfigSourceValues.SCOPE, - TemplateConfigSourceValues.SCOPE_ID, - "0"))); - } - - private static SelectedOwnerIntakeSourceContent sourceContent( - net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, - TemplateConfigSourceSnapshot templateSnapshot) { - var out = new ByteArrayOutputStream(); - frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - frame(out, scope.canonicalBytes()); - frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = - "TEMPLATE_CONFIG".equals(family) - ? templateSnapshot.canonicalBytes() - : sourceSnapshot(family, scope.selected()); - frame(out, family); - frame(out, snapshot); - frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { - // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. - return switch (family) { - case "COMMAND" -> - new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) - .canonicalBytes(); - case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); - case "ASSET" -> - new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); - case "GAMEPLAY_RULE" -> - new GameplayRuleSelectedSource( - GameplayRuleManifest.canonical( - Map.of( - "schema", - "game-design-gameplay-rule-source-snapshot/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "sourceEpoch", - "0", - "inheritedCommitId", - "", - "genesisReceiptId", - GENESIS_RECEIPT.toString(), - "manifestJson", - GameplayRuleManifest.explicitEmpty().canonicalJson(), - "entries", - List.of()))) - .canonicalBytes(); - case "BRANDING" -> - new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) - .canonicalBytes(); - default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family); - }; - } - - private static List accountSources() { - return List.of( - source(SourceKind.TENANT, TENANT.toString(), "tenant"), - source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), - source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); - } - - private static SourceEvidence source(SourceKind kind, String scope, String marker) { - return new SourceEvidence( - kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); - } - private static DraftCommitBinding selected(UUID selectedCommitId) { return DraftCommitBinding.create( target(), @@ -269,198 +67,6 @@ private static TargetProof target() { return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); } - private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( - DraftCommitBinding selected) { - var selection = - AuthoredDraftPublishSelectionBinding.capture( - new PublishIntent( - TENANT, - VERSION, - "publication-request", - "9", - "synthetic selected-owner intake fixture", - selected.requestId(), - selected.commitId(), - selected.digest()), - selected.target(), - selected, - new VisibilityFence( - selected.target(), - selected.requestId(), - selected.commitId(), - selected.digest(), - "[]", - OffsetDateTime.parse("2026-10-01T00:00:00Z"))); - var account = - new AccountPublicationAuthorizationBinding( - id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - id("ffffffff-ffff-4fff-8fff-ffffffffffff"), - new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), - List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); - var request = - WorldSelectedDraftPublicationFreezeEvidence.Request.create( - NAMESPACE, - TENANT, - VERSION, - selection.intent().publishRequestId(), - 9, - selection.digest().substring("sha256:".length()), - account); - var acknowledgement = - new Acknowledgement( - request, - id("12121212-1212-4212-8212-121212121212"), - 9, - id("13131313-1313-4313-8313-131313131313"), - OwnerFreezePhase.FROZEN, - selected.commitId().toString(), - "a".repeat(64), - 4); - return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); - } - - private static PublicEvidence publicInventory( - WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { - var request = freezeEvidence.request(); - var acknowledgement = freezeEvidence.acknowledgement(); - var account = request.accountBinding(); - var selection = account.input().selection(); - var selected = selection.selectedCommit(); - var sourceModel = - new SourceModel( - WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, - WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, - "sha256:" + "4".repeat(64), - "sha256:" + "5".repeat(64), - List.of( - new FamilyCount("REGION", 1), - new FamilyCount("ZONE", 1), - new FamilyCount("ROOM", 1), - new FamilyCount("ROOM_EXIT", 1), - new FamilyCount("GENERATION_RULE", 0), - new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), - List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), - List.of("id", "name", "scopeType", "scopeId", "value"), - List.of( - "id", - "shardId", - "name", - "weather", - "generationSeed", - "generatorType", - "generatorParams", - "spacingMultiplier"), - List.of("id", "regionId", "name"), - List.of( - "id", - "zoneId", - "name", - "description", - "nameLocalizedVariantsJson", - "descriptionLocalizedVariantsJson"), - List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), - List.of( - "id", - "roomId", - "entityTemplateType", - "entityReference.kind", - "entityReference.tenantId", - "entityReference.versionId", - "entityReference.templateId", - "spawnCount", - "respawnDelaySeconds"), - List.of(), - 0, - 0, - selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) - .toList(), - emptyInboundClosure()); - var ownerScope = - new PublicOwnerScope( - request.targetNamespace(), - TENANT, - VERSION, - id("14141414-1414-4414-8414-141414141414"), - acknowledgement.intakeRequestId(), - id("13131313-1313-4313-8313-131313131313"), - "sha256:" + "1".repeat(64), - id("17171717-1717-4717-8717-171717171717"), - "sha256:" + "2".repeat(64), - "sha256:" + "3".repeat(64)); - return new PublicEvidence( - WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, - WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, - "COMPLETE", - ownerScope, - new SelectedApplication( - id("16161616-1616-4616-8616-161616161616"), - selected.requestId(), - selected.commitId().toString(), - selected.digest(), - "sha256:" + "6".repeat(64)), - new PublicAccountOrder( - account.operationId(), - account.fenceId(), - account.input().actorAccountId(), - selection.intent().publishRequestId(), - selection.digest(), - selected.commitId().toString(), - DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), - new Freeze( - acknowledgement.publicationFence(), - request.publicationRequestId(), - request.requestDigest(), - Long.toString(acknowledgement.versionStateEpoch()), - PublicationDigestRequestBinding.full( - request.canonicalTenantId().toString(), - Long.toString(selection.target().gameDesignVersionRowId()), - request.publicationRequestId()) - .derivedWorkflowIdentity()), - new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), - sourceModel, - List.of( - new ArtifactDecision( - "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), - new ArtifactDecision( - "PATH_GRAPH", - "NOT_REQUIRED", - "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); - } - - private static InboundSourceClosureDeclaration emptyInboundClosure() { - return new InboundSourceClosureDeclaration( - 1, - List.of( - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), - new InboundSourceFamilyCount( - "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), - new InboundSourceFamilyCount( - "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), - new InboundSourceFamilyCount( - "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); - } - - private static void frame(ByteArrayOutputStream out, String value) { - DraftAuthorizationFenceBinding.frame(out, value); - } - - private static void frame(ByteArrayOutputStream out, byte[] value) { - DraftAuthorizationFenceBinding.frame(out, value); - } - private static UUID id(String value) { return UUID.fromString(value); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java index 1c5e81d5ef..cb79b94bdd 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java @@ -525,6 +525,31 @@ void createdMethodsValidateFullServiceResponsesBeforeReturningThem() { verifyNoInteractions(malformedCallerService); } + @Test + void createdOwnerDeadlineMapsToUnavailableWithoutInternalMetric() { + var createdService = mock(EntityPlayerCreatedRosterService.class); + var meterRegistry = new SimpleMeterRegistry(); + var adapter = + new CanonicalGameplayRosterGrpcAdapter( + mock(CanonicalGameplayRosterService.class), + mock(CanonicalGameplayRosterSelectedAssignmentService.class), + createdService, + meterRegistry); + var request = playerCreatedRequest(); + when(createdService.list(request)).thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()); + var observer = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse>(); + + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, + () -> adapter.listPlayerCreatedRoster(request, observer)); + + assertOnlyStatus(observer, Status.Code.UNAVAILABLE); + verify(createdService).list(request); + assertThat(meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count()).isZero(); + } + @Test void expectedOwnerRejectionsReturnFailedPreconditionWithoutPartialResponse() { for (String reasonCode : @@ -532,7 +557,8 @@ void expectedOwnerRejectionsReturnFailedPreconditionWithoutPartialResponse() { "CANONICAL_ROSTER_ORIGINAL_DEREFERENCE_CLOSED", "CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT", "CANONICAL_ROSTER_LOCAL_ADMISSION_DISPOSED", - "CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT")) { + "CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT", + "CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED")) { var createdService = mock(EntityPlayerCreatedRosterService.class); when(createdService.list(any())).thenThrow(new IllegalStateException(reasonCode)); var adapter = diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java index 6d5018bae7..1ac569f344 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java @@ -2,68 +2,19 @@ import com.google.protobuf.ByteString; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.io.ByteArrayOutputStream; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; -import java.time.OffsetDateTime; -import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; -import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; -import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; -import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; -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.Owner; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; -import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; -import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; -import net.firedevops.firemud.common.gamedesign.AssetSnapshot; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection.AuthoredCore; -import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.CommandSnapshot; -import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; -import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; -import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; -import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; -import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; -import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; -import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; -import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; -import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; -import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; -import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; -import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient.AuthenticatedSource; import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; @@ -74,6 +25,7 @@ import net.firedevops.firemud.entitymanagement.service.impl.CanonicalGameplayRosterRecoveryGrpcAdapter; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture.WireFixture; +import net.firedevops.firemud.entitymanagement.testing.ControlledSelectedSourceIntakeFixtureBuilder; import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; @@ -183,7 +135,7 @@ public synchronized EntityCharacterCreateTerminal createActor( } if (sourceReceipt == null) { var intake = - ControlledIntakeBuilder.create( + ControlledSelectedSourceIntakeFixtureBuilder.create( "1", selected, source.response().getRequest().getTargetNamespace()); var inputs = intake.inputs(); String digest = @@ -454,389 +406,4 @@ private static CharacterCreateOperatorAction.Rule authoredRule( rule.revisionId().toString(), rule.revisionOrder()); } - - /** Small typed fixture builder for a controlled fresh Entity owner source-intake receipt. */ - private static final class ControlledIntakeBuilder { - static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); - - private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); - private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); - private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); - private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); - - private ControlledIntakeBuilder() {} - - public static Fixture create( - String sourceEpoch, DraftCommitBinding selected, String namespace) { - Objects.requireNonNull(selected, "selected"); - Objects.requireNonNull(namespace, "namespace"); - var target = selected.target(); - var scope = - new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( - Owner.ENTITY_MANAGEMENT, - namespace, - OPERATION, - FENCE, - INTAKE_REQUEST, - ACTOR, - selected); - TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); - SelectedOwnerIntakeAuthorizationBinding authorization = - new SelectedOwnerIntakeAuthorizationBinding( - sourceContent(scope, templateSnapshot), accountSources(target)); - WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected, namespace); - var inventory = - WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( - freeze, publicInventory(freeze)); - var worldRequest = - SelectedOwnerWorldInventoryReadEvidence.create(namespace, authorization, freeze); - var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); - return new Fixture( - authorization, - freeze, - worldEvidence, - new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); - } - - private static TemplateConfigSourceSnapshot templateSnapshot( - DraftCommitBinding selected, String sourceEpoch) { - var declaration = - EntityAuthoredSourceInventoryDeclaration.parse( - "{\"schema\":\"entity-authored-source-inventory/v1\"," - + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" - + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," - + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," - + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," - + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," - + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," - + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," - + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," - + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," - + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," - + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," - + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," - + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); - String declarationPayload = - TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration); - DraftCommitBinding authored = authoredBinding(declarationPayload, selected.target()); - TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = - TemplateConfigSourceValues.mutations(authored).stream() - .filter( - mutation -> - mutation.operation() - == TemplateConfigSourceValues.OperationKind - .DECLARE_OWNER_SOURCE_INVENTORY) - .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) - .findFirst() - .orElseThrow(); - return new TemplateConfigSourceSnapshot( - selected, - sourceEpoch, - authored.commitId(), - GENESIS_RECEIPT, - List.of(), - List.of(ownerDeclaration)); - } - - private static DraftCommitBinding authoredBinding(String payload, TargetProof target) { - return DraftCommitBinding.create( - target, - id("51515151-5151-4151-8151-515151515151"), - id("52525252-5252-4252-8252-525252525252"), - "base-commit-0", - List.of( - new RevisionPayload( - "0", - id("53535353-5353-4353-8353-535353535353"), - Owner.GAME_DESIGN_CONTROL_PLANE, - payload)), - List.of( - new DraftCommitBinding.AffectedUnit( - Owner.GAME_DESIGN_CONTROL_PLANE, - TemplateConfigSourceValues.SCOPE, - target.canonicalVersionId().toString(), - TemplateConfigSourceValues.SCOPE, - TemplateConfigSourceValues.SCOPE_ID, - "0"))); - } - - private static SelectedOwnerIntakeSourceContent sourceContent( - net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, - TemplateConfigSourceSnapshot templateSnapshot) { - var out = new ByteArrayOutputStream(); - frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); - frame(out, scope.canonicalBytes()); - frame(out, scope.digest()); - for (String family : - List.of( - "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { - byte[] snapshot = - "TEMPLATE_CONFIG".equals(family) - ? templateSnapshot.canonicalBytes() - : sourceSnapshot(family, scope.selected()); - frame(out, family); - frame(out, snapshot); - frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); - } - byte[] bytes = out.toByteArray(); - return SelectedOwnerIntakeSourceContent.fromStored( - bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); - } - - private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { - // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. - return switch (family) { - case "COMMAND" -> - new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) - .canonicalBytes(); - case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); - case "ASSET" -> - new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); - case "GAMEPLAY_RULE" -> - new GameplayRuleSelectedSource( - GameplayRuleManifest.canonical( - Map.of( - "schema", - "game-design-gameplay-rule-source-snapshot/v1", - "bindingJson", - selected.canonicalJson(), - "bindingDigest", - selected.digest(), - "sourceEpoch", - "0", - "inheritedCommitId", - "", - "genesisReceiptId", - GENESIS_RECEIPT.toString(), - "manifestJson", - GameplayRuleManifest.explicitEmpty().canonicalJson(), - "entries", - List.of()))) - .canonicalBytes(); - case "BRANDING" -> - new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) - .canonicalBytes(); - default -> - throw new IllegalArgumentException("Unsupported source family fixture: " + family); - }; - } - - private static List accountSources(TargetProof target) { - String tenant = target.canonicalTenantId().toString(); - return List.of( - source(SourceKind.TENANT, tenant, "tenant"), - source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), - source(SourceKind.MEMBERSHIP, ACTOR + "/" + tenant, "membership")); - } - - private static SourceEvidence source(SourceKind kind, String scope, String marker) { - return new SourceEvidence( - kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); - } - - private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( - DraftCommitBinding selected, String namespace) { - var target = selected.target(); - var selection = - AuthoredDraftPublishSelectionBinding.capture( - new PublishIntent( - target.canonicalTenantId(), - target.canonicalVersionId(), - "publication-request", - "9", - "synthetic selected-owner intake fixture", - selected.requestId(), - selected.commitId(), - selected.digest()), - selected.target(), - selected, - new VisibilityFence( - selected.target(), - selected.requestId(), - selected.commitId(), - selected.digest(), - "[]", - OffsetDateTime.parse("2026-10-01T00:00:00Z"))); - var account = - new AccountPublicationAuthorizationBinding( - id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - id("ffffffff-ffff-4fff-8fff-ffffffffffff"), - new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), - List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); - var request = - WorldSelectedDraftPublicationFreezeEvidence.Request.create( - namespace, - target.canonicalTenantId(), - target.canonicalVersionId(), - selection.intent().publishRequestId(), - 9, - selection.digest().substring("sha256:".length()), - account); - var acknowledgement = - new Acknowledgement( - request, - id("12121212-1212-4212-8212-121212121212"), - 9, - id("13131313-1313-4313-8313-131313131313"), - OwnerFreezePhase.FROZEN, - selected.commitId().toString(), - "a".repeat(64), - 4); - return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); - } - - private static PublicEvidence publicInventory( - WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { - var request = freezeEvidence.request(); - var target = request.accountBinding().input().selection().selectedCommit().target(); - var acknowledgement = freezeEvidence.acknowledgement(); - var account = request.accountBinding(); - var selection = account.input().selection(); - var selected = selection.selectedCommit(); - var sourceModel = - new SourceModel( - WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, - WorldSelectedPublicationArtifactInventoryEvidence - .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, - "sha256:" + "4".repeat(64), - "sha256:" + "5".repeat(64), - List.of( - new FamilyCount("REGION", 1), - new FamilyCount("ZONE", 1), - new FamilyCount("ROOM", 1), - new FamilyCount("ROOM_EXIT", 1), - new FamilyCount("GENERATION_RULE", 0), - new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), - List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), - List.of("id", "name", "scopeType", "scopeId", "value"), - List.of( - "id", - "shardId", - "name", - "weather", - "generationSeed", - "generatorType", - "generatorParams", - "spacingMultiplier"), - List.of("id", "regionId", "name"), - List.of( - "id", - "zoneId", - "name", - "description", - "nameLocalizedVariantsJson", - "descriptionLocalizedVariantsJson"), - List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), - List.of( - "id", - "roomId", - "entityTemplateType", - "entityReference.kind", - "entityReference.tenantId", - "entityReference.versionId", - "entityReference.templateId", - "spawnCount", - "respawnDelaySeconds"), - List.of(), - 0, - 0, - selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) - .toList(), - emptyInboundClosure()); - var ownerScope = - new PublicOwnerScope( - request.targetNamespace(), - target.canonicalTenantId(), - target.canonicalVersionId(), - id("14141414-1414-4414-8414-141414141414"), - acknowledgement.intakeRequestId(), - id("13131313-1313-4313-8313-131313131313"), - "sha256:" + "1".repeat(64), - id("17171717-1717-4717-8717-171717171717"), - "sha256:" + "2".repeat(64), - "sha256:" + "3".repeat(64)); - return new PublicEvidence( - WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, - WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, - "COMPLETE", - ownerScope, - new SelectedApplication( - id("16161616-1616-4616-8616-161616161616"), - selected.requestId(), - selected.commitId().toString(), - selected.digest(), - "sha256:" + "6".repeat(64)), - new PublicAccountOrder( - account.operationId(), - account.fenceId(), - account.input().actorAccountId(), - selection.intent().publishRequestId(), - selection.digest(), - selected.commitId().toString(), - DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), - new Freeze( - acknowledgement.publicationFence(), - request.publicationRequestId(), - request.requestDigest(), - Long.toString(acknowledgement.versionStateEpoch()), - PublicationDigestRequestBinding.full( - request.canonicalTenantId().toString(), - Long.toString(selection.target().gameDesignVersionRowId()), - request.publicationRequestId()) - .derivedWorkflowIdentity()), - new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), - sourceModel, - List.of( - new ArtifactDecision( - "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), - new ArtifactDecision( - "PATH_GRAPH", - "NOT_REQUIRED", - "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); - } - - private static InboundSourceClosureDeclaration emptyInboundClosure() { - return new InboundSourceClosureDeclaration( - 1, - List.of( - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), - new InboundSourceFamilyCount( - "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), - new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), - new InboundSourceFamilyCount( - "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), - new InboundSourceFamilyCount( - "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); - } - - private static void frame(ByteArrayOutputStream out, String value) { - DraftAuthorizationFenceBinding.frame(out, value); - } - - private static void frame(ByteArrayOutputStream out, byte[] value) { - DraftAuthorizationFenceBinding.frame(out, value); - } - - private static UUID id(String value) { - return UUID.fromString(value); - } - - public record Fixture( - SelectedOwnerIntakeAuthorizationBinding authorization, - WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, - SelectedOwnerWorldInventoryReadEvidence worldEvidence, - SelectedOwnerEmptySourceInputs inputs) {} - } } diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java new file mode 100644 index 0000000000..cabab2cbc1 --- /dev/null +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java @@ -0,0 +1,429 @@ +package net.firedevops.firemud.entitymanagement.testing; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; + +/** Builds synthetic selected-source intake evidence for Entity fixture callers. */ +public final class ControlledSelectedSourceIntakeFixtureBuilder { + private static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); + private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + private ControlledSelectedSourceIntakeFixtureBuilder() {} + + public static Fixture create(String sourceEpoch, DraftCommitBinding selected, String namespace) { + Objects.requireNonNull(selected, "selected"); + Objects.requireNonNull(namespace, "namespace"); + var target = selected.target(); + var scope = + new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, namespace, OPERATION, FENCE, INTAKE_REQUEST, ACTOR, selected); + TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); + SelectedOwnerIntakeAuthorizationBinding authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(scope, templateSnapshot), accountSources(target)); + WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected, namespace); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(namespace, authorization, freeze); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + return new Fixture( + authorization, + freeze, + worldEvidence, + new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, String sourceEpoch) { + var declaration = + EntityAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); + String declarationPayload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration); + DraftCommitBinding authored = authoredBinding(declarationPayload, selected.target()); + TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, + sourceEpoch, + authored.commitId(), + GENESIS_RECEIPT, + List.of(), + List.of(ownerDeclaration)); + } + + private static DraftCommitBinding authoredBinding(String payload, TargetProof target) { + return DraftCommitBinding.create( + target, + id("51515151-5151-4151-8151-515151515151"), + id("52525252-5252-4252-8252-525252525252"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("53535353-5353-4353-8353-535353535353"), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + target.canonicalVersionId().toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, + TemplateConfigSourceSnapshot templateSnapshot) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> + new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + GENESIS_RECEIPT.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family); + }; + } + + private static List accountSources(TargetProof target) { + String tenant = target.canonicalTenantId().toString(); + return List.of( + source(SourceKind.TENANT, tenant, "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + tenant, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected, String namespace) { + var target = selected.target(); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + target.canonicalTenantId(), + target.canonicalVersionId(), + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var target = request.accountBinding().input().selection().selectedCommit().target(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + target.canonicalTenantId(), + target.canonicalVersionId(), + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + public record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence worldEvidence, + SelectedOwnerEmptySourceInputs inputs) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index 1fbae283d2..09de3c7eb4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -2212,12 +2212,14 @@ void actual1017To1020UpgradePreservesPriorHistoryOriginalBytesAndXmin() throws E .intoMap() .toString()) .isEqualTo(retained); + var upgradedRow = + previous.fetchSingle( + "SELECT entry_policy,canonical_player_created_roster_receipt,canonical_selected_player_created_character_receipt FROM game_session_canonical_roster_selection"); + assertThat(upgradedRow.get("entry_policy", String.class)).isEqualTo("PRESEEDED_ONLY"); + assertThat(upgradedRow.get("canonical_player_created_roster_receipt", byte[].class)).isNull(); assertThat( - previous - .fetchSingle( - "SELECT entry_policy,canonical_player_created_roster_receipt,canonical_selected_player_created_character_receipt FROM game_session_canonical_roster_selection") - .get("entry_policy", String.class)) - .isEqualTo("PRESEEDED_ONLY"); + upgradedRow.get("canonical_selected_player_created_character_receipt", byte[].class)) + .isNull(); var upgradedRepository = new CanonicalGameplayRosterReferenceRepository(previous, policy(60000L, 60000L, 60000L)); assertThat(upgradedRepository.read(original).getCanonicalRosterReceipt()) From 4d0dd8e89a874c4e2f727e9f6b5b728e8ffc9245 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 00:46:04 +1300 Subject: [PATCH 12/22] Fix created roster review boundaries and quarantine proof --- .../game-session-service/runtime-and-data.md | 2 +- .../EntityCharacterCreateGrpcService.java | 37 +++- ...V1017__player_created_actor_quarantine.sql | 145 +++++++++++++ ...eseededActorAssignmentIntegrationTest.java | 5 +- .../RetainedActorIdentityIntegrationTest.java | 14 +- ...haracterCreatePostgresIntegrationTest.java | 191 +++++++++++++++++- ...ntakeMigrationPostgresIntegrationTest.java | 2 +- .../EntityCharacterCreateMtlsTest.java | 78 ++++++- .../game-session-service/build.gradle.kts | 3 + ...lledPlayerCreatedOriginalOwnerFixture.java | 20 +- 10 files changed, 477 insertions(+), 20 deletions(-) create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1017__player_created_actor_quarantine.sql 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 c0ce97c546..94e5df7c5a 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -85,7 +85,7 @@ Compact transfer receipts survive original removal and remain protected until En #### Player-created original roster storage -The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. The original-reference response preserves the complete selected payload within its 194 MiB purpose bound; retirement observation preserves it within the 195 MiB created-ACK bound with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within the existing recovery bound. These purpose-specific byte limits preserve owner bytes and preseeded limits; they do not widen global gRPC defaults. V1020 supplies the distinct receipt branch, not the absent V1018 canonical UUID or V1019 creation-protection storage. +The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. The original-reference response preserves the complete selected payload within its 194 MiB purpose bound; retirement observation preserves it within the 195 MiB created-ACK bound with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within the existing recovery bound. These purpose-specific byte limits preserve owner bytes and preseeded limits; they do not widen global gRPC defaults. Published V1020 supplies the distinct receipt branch. V1018 and V1019 were reserved in an unpublished receiving source and must not later be introduced below the published V1020 frontier. The local receiving source assigns the next unused versions, V1021 for canonical UUID runtime and V1022 for creation-protection storage, preserving their SQL bytes; qualification requires a fresh migration frontier and actual-parent upgrade proof. These local storage owners remain unregistered and separate from this created-receipt PR, and do not qualify the full receiving chain. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) and [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) for current proof limits. The unregistered bounded retention service uses the configured cadence and batch bound, pages past protected candidates, and reports oldest blocking age, cleanup lag, pending-transfer age and fixed cleanup outcomes without identity-bearing metric labels. Unfinished or unavailable authority remains protected. Production registration and real gameplay admission stay closed pending the [owning proof gate](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java index 5640c3d281..1eb69894c5 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateGrpcService.java @@ -1,47 +1,62 @@ package net.firedevops.firemud.entitymanagement.charactercreate; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.MeterRegistry; import java.util.Objects; import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.entitymanagement.v1.AbortProtectedCharacterCreateRequest; import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; import net.firedevops.firemud.entitymanagement.v1.ReadEntityCharacterCreateTerminalRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** Manually composed only; no annotation, bean, controller, feature flag or route registration. */ public final class EntityCharacterCreateGrpcService extends EntityCharacterCreateServiceGrpc.EntityCharacterCreateServiceImplBase { + private static final Logger LOGGER = + LoggerFactory.getLogger(EntityCharacterCreateGrpcService.class); + private final EntityCharacterCreateService owner; + private final MeterRegistry meterRegistry; - public EntityCharacterCreateGrpcService(EntityCharacterCreateService owner) { + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "MeterRegistry is an intentionally shared dependency-injected metrics sink") + public EntityCharacterCreateGrpcService( + EntityCharacterCreateService owner, MeterRegistry meterRegistry) { this.owner = Objects.requireNonNull(owner); + this.meterRegistry = Objects.requireNonNull(meterRegistry); } @Override public void commitProtectedCharacterCreate( CommitProtectedCharacterCreateRequest request, StreamObserver observer) { - deliver(() -> owner.commit(request), observer); + deliver("CommitProtectedCharacterCreate", () -> owner.commit(request), observer); } @Override public void abortProtectedCharacterCreate( AbortProtectedCharacterCreateRequest request, StreamObserver observer) { - deliver(() -> owner.abort(request), observer); + deliver("AbortProtectedCharacterCreate", () -> owner.abort(request), observer); } @Override public void readEntityCharacterCreateTerminal( ReadEntityCharacterCreateTerminalRequest request, StreamObserver observer) { - deliver(() -> owner.read(request), observer); + deliver("ReadEntityCharacterCreateTerminal", () -> owner.read(request), observer); } - private static void deliver( + private void deliver( + String operation, Supplier action, StreamObserver observer) { try { @@ -55,10 +70,18 @@ private static void deliver( Status.UNAVAILABLE .withDescription("Entity creation storage unavailable; no terminal inferred") .asRuntimeException()); - } catch (RuntimeException invalid) { + } catch (IllegalArgumentException invalidEvidence) { observer.onError( Status.DATA_LOSS - .withDescription("Entity creation owner evidence failed closed") + .withDescription("Entity creation owner evidence failed validation") + .withCause(invalidEvidence) + .asRuntimeException()); + } catch (RuntimeException unexpected) { + var internal = GrpcAppErrors.internal(meterRegistry, LOGGER, operation, unexpected); + observer.onError( + Status.INTERNAL + .withDescription(internal.getMessage()) + .withCause(unexpected) .asRuntimeException()); } } diff --git a/services/entity-management-service/src/main/resources/db/migration/V1017__player_created_actor_quarantine.sql b/services/entity-management-service/src/main/resources/db/migration/V1017__player_created_actor_quarantine.sql new file mode 100644 index 0000000000..a853dfe5f8 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1017__player_created_actor_quarantine.sql @@ -0,0 +1,145 @@ +-- Permit the existing canonical quarantine state for PLAYER_CREATED actors without changing +-- their immutable creation provenance or admitting them through current roster readers. +/* [jooq ignore start] */ +ALTER TABLE characters DROP CONSTRAINT ck_character_created_core; + +ALTER TABLE characters ADD CONSTRAINT ck_character_created_core CHECK ( + (actor_entry_policy IS NULL AND creation_target_namespace IS NULL + AND creation_operation_id IS NULL AND authored_initial_core_json IS NULL + AND creation_descriptor_json IS NULL AND creation_descriptor_digest IS NULL + AND account_id IS NOT NULL AND playable_state_key IS NOT NULL + AND level IS NOT NULL AND experience IS NOT NULL AND strength IS NOT NULL + AND agility IS NOT NULL AND intelligence IS NOT NULL AND stamina IS NOT NULL + AND health IS NOT NULL AND mana IS NOT NULL AND body_layout_key IS NOT NULL) + OR (actor_entry_policy = 'PLAYER_CREATED' AND creation_target_namespace IS NOT NULL + AND creation_operation_id IS NOT NULL + AND actor_identity_status IN ('OWNER_RESOLVED', 'QUARANTINED') + AND account_id IS NULL AND playable_state_key IS NULL + AND level IS NULL AND experience IS NULL AND strength IS NULL AND agility IS NULL + AND intelligence IS NULL AND stamina IS NULL AND health IS NULL AND mana IS NULL + AND body_layout_key IS NULL AND authored_initial_core_json IS NOT NULL + AND creation_descriptor_json IS NOT NULL + AND creation_descriptor_digest IS NOT NULL + AND creation_descriptor_digest ~ '^sha256:[0-9a-f]{64}$' + AND name = authored_initial_core_json::JSONB ->> 'displayName') +); +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +DO $entity_created_actor_quarantine_guard$ +DECLARE + owner_schema TEXT := current_schema(); +BEGIN + IF owner_schema IS NULL THEN + RAISE EXCEPTION 'Entity empty-source functions require an explicit installation schema'; + END IF; + + EXECUTE format($function$ + CREATE OR REPLACE FUNCTION %I.entity_guard_source_owner_row() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_value JSONB; + new_value JSONB; + old_tenant_key BIGINT; + new_tenant_key BIGINT; + old_version_key BIGINT; + new_version_key BIGINT; + old_is_owner_resolved_character BOOLEAN := FALSE; + new_is_owner_resolved_character BOOLEAN := FALSE; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_value := to_jsonb(OLD); + old_tenant_key := %I.entity_source_positive_numeric_key(old_value->>'tenant_id'); + old_version_key := %I.entity_source_positive_numeric_key(old_value->>'version_id'); + IF TG_TABLE_NAME = 'characters' THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', NULL::BIGINT); + SELECT EXISTS ( + SELECT 1 + FROM %I.entity_tenant_identities tenant_identity + JOIN %I.entity_playable_state_namespace_scopes namespace_scope + ON namespace_scope.tenant_uuid = tenant_identity.canonical_tenant_uuid + WHERE tenant_identity.entity_tenant_row_id = old_tenant_key + AND tenant_identity.canonical_tenant_uuid = + NULLIF(old_value->>'tenant_uuid', '')::UUID + AND namespace_scope.playable_state_namespace_id = + NULLIF(old_value->>'playable_state_namespace_id', '')::UUID + AND namespace_scope.playable_state_scope = + old_value->>'playable_state_scope' + AND ((old_value->>'actor_identity_status' = 'OWNER_RESOLVED' + AND old_value->>'actor_identity_quarantine_reason' IS NULL) + OR (old_value->>'actor_entry_policy' = 'PLAYER_CREATED' + AND old_value->>'actor_identity_status' = 'QUARANTINED' + AND old_value->>'actor_identity_quarantine_reason' IS NOT NULL + AND length(trim(old_value->>'actor_identity_quarantine_reason')) > 0)) + AND NULLIF(old_value->>'character_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + AND NULLIF(old_value->>'account_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + ) INTO old_is_owner_resolved_character; + IF NOT old_is_owner_resolved_character THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', old_tenant_key); + END IF; + ELSE + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', old_tenant_key); + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', old_version_key); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_value := to_jsonb(NEW); + new_tenant_key := %I.entity_source_positive_numeric_key(new_value->>'tenant_id'); + new_version_key := %I.entity_source_positive_numeric_key(new_value->>'version_id'); + IF TG_TABLE_NAME = 'characters' THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', NULL::BIGINT); + SELECT EXISTS ( + SELECT 1 + FROM %I.entity_tenant_identities tenant_identity + JOIN %I.entity_playable_state_namespace_scopes namespace_scope + ON namespace_scope.tenant_uuid = tenant_identity.canonical_tenant_uuid + WHERE tenant_identity.entity_tenant_row_id = new_tenant_key + AND tenant_identity.canonical_tenant_uuid = + NULLIF(new_value->>'tenant_uuid', '')::UUID + AND namespace_scope.playable_state_namespace_id = + NULLIF(new_value->>'playable_state_namespace_id', '')::UUID + AND namespace_scope.playable_state_scope = + new_value->>'playable_state_scope' + AND ((new_value->>'actor_identity_status' = 'OWNER_RESOLVED' + AND new_value->>'actor_identity_quarantine_reason' IS NULL) + OR (new_value->>'actor_entry_policy' = 'PLAYER_CREATED' + AND new_value->>'actor_identity_status' = 'QUARANTINED' + AND new_value->>'actor_identity_quarantine_reason' IS NOT NULL + AND length(trim(new_value->>'actor_identity_quarantine_reason')) > 0)) + AND NULLIF(new_value->>'character_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + AND NULLIF(new_value->>'account_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + ) INTO new_is_owner_resolved_character; + IF NOT new_is_owner_resolved_character THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', new_tenant_key); + END IF; + ELSE + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', new_tenant_key); + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', new_version_key); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, + owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, + owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema); +END; +$entity_created_actor_quarantine_guard$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 63ce867c56..bea3e077c6 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -411,7 +411,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( assertThat(successorHistory) .extracting(AppliedMigration::version) .containsExactly( - "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016"); + "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -424,7 +424,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1012__canonical_roster_retention.sql", "V1014__canonical_roster_retirement_observation.sql", "V1015__entity_character_create_terminal.sql", - "V1016__player_created_roster_snapshot_receipts.sql"); + "V1016__player_created_roster_snapshot_receipts.sql", + "V1017__player_created_actor_quarantine.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index b8252c3d65..5f6abe40f0 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -642,7 +642,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .extracting(migration -> migration.getVersion().getVersion()) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014", "1015", "1016"); + "1010", "1011", "1012", "1014", "1015", "1016", "1017"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -663,9 +663,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1012__canonical_roster_retention.sql", "V1014__canonical_roster_retirement_observation.sql", "V1015__entity_character_create_terminal.sql", - "V1016__player_created_roster_snapshot_receipts.sql"); + "V1016__player_created_roster_snapshot_receipts.sql", + "V1017__player_created_actor_quarantine.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1016")); + .isEqualTo(MigrationVersion.fromVersion("1017")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -738,7 +739,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .extracting(MigrationHistoryEntry::version) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014", "1015", "1016"); + "1010", "1011", "1012", "1014", "1015", "1016", "1017"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -758,7 +759,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1012__canonical_roster_retention.sql", "V1014__canonical_roster_retirement_observation.sql", "V1015__entity_character_create_terminal.sql", - "V1016__player_created_roster_snapshot_receipts.sql"); + "V1016__player_created_roster_snapshot_receipts.sql", + "V1017__player_created_actor_quarantine.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1021,7 +1023,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1016")); + .isEqualTo(MigrationVersion.fromVersion("1017")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 22daa073c3..dc5732f097 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector; import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterReadService.PublishedIdentity; import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient.AuthenticatedSource; +import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; import net.firedevops.firemud.entitymanagement.repository.EntityEmptySelectedSourceIntakePostgresFixture; import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; @@ -118,7 +119,7 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { DSLContext upgradedDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); assertThat(migrationHistory(upgradedDsl).subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); - assertThat(migrationVersions(upgradedDsl)).last().isEqualTo("1016"); + assertThat(migrationVersions(upgradedDsl)).last().isEqualTo("1017"); assertThat(retainedParentRows(upgradedDsl, character, snapshot)) .containsExactlyElementsOf(retainedRows); assertThat( @@ -134,6 +135,55 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { } } + @Test + void quarantinesCreatedActorWithoutChangingProvenanceOrCurrentRosterAdmission() throws Exception { + UUID accountId = UUID.randomUUID(); + var proof = proof(accountId, UUID.randomUUID()); + EntityCharacterCreateTerminal terminal = repository.settle(proof, null); + assertCreatedActorQuarantineBoundary(dsl, repository, proof, terminal, accountId); + } + + @Test + void upgradesRetainedV1016CreatedActorBeforeQuarantineWithoutChangingRows() throws Exception { + String retainedSchema = + "entity_create_quarantine_" + UUID.randomUUID().toString().replace("-", ""); + try { + DriverManagerDataSource retainedDataSource = dataSource(retainedSchema); + migrate(retainedDataSource, retainedSchema, "1016"); + DSLContext retainedDsl = DSL.using(retainedDataSource, SQLDialect.POSTGRES); + var retainedRepository = + new EntityCharacterCreateRepository(retainedDsl, Clock.fixed(NOW, ZoneOffset.UTC)); + var retainedSource = retainControlledSource(retainedDsl); + UUID accountId = UUID.randomUUID(); + var proof = proof(retainedSource, accountId, UUID.randomUUID(), false, null); + EntityCharacterCreateTerminal terminal = retainedRepository.settle(proof, null); + UUID characterId = UUID.fromString(terminal.getCharacterId()); + String actorBefore = retainedRow(retainedDsl, "characters", "character_uuid", characterId); + String operationBefore = + retainedOperationRow( + retainedDsl, + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId())); + + migrate(retainedDataSource, retainedSchema, null); + + assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1017"); + assertThat(retainedRow(retainedDsl, "characters", "character_uuid", characterId)) + .isEqualTo(actorBefore); + assertThat( + retainedOperationRow( + retainedDsl, + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))) + .isEqualTo(operationBefore); + assertCreatedActorQuarantineBoundary( + retainedDsl, retainedRepository, proof, terminal, accountId); + } finally { + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + retainedSchema + "\" CASCADE"); + } + } + @AfterEach void removeIsolatedSchema() { if (schema != null) @@ -1080,6 +1130,145 @@ private static DriverManagerDataSource dataSource(String schema) { return new DriverManagerDataSource(url, postgres.getUsername(), postgres.getPassword()); } + private static void assertCreatedActorQuarantineBoundary( + DSLContext ownerDsl, + EntityCharacterCreateRepository ownerRepository, + EntityCharacterCreateProofs proof, + EntityCharacterCreateTerminal terminal, + UUID accountId) + throws Exception { + UUID characterId = UUID.fromString(terminal.getCharacterId()); + Long privateCharacterId = + ownerDsl + .fetchSingle("SELECT id FROM characters WHERE character_uuid = ?", characterId) + .get(0, Long.class); + Long privateTenantId = + ownerDsl + .fetchSingle("SELECT tenant_id FROM characters WHERE character_uuid = ?", characterId) + .get(0, Long.class); + String immutableActorBefore = + ownerDsl + .fetchSingle( + "SELECT (to_jsonb(c) - 'actor_identity_status' " + + "- 'actor_identity_quarantine_reason')::text FROM characters c " + + "WHERE character_uuid = ?", + characterId) + .get(0, String.class); + String operationBefore = + retainedOperationRow( + ownerDsl, + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId())); + + assertThat( + ownerDsl.execute( + "UPDATE characters SET actor_identity_status='QUARANTINED', " + + "actor_identity_quarantine_reason='OWNER_PROVENANCE_REVOKED' " + + "WHERE character_uuid=? AND actor_identity_status='OWNER_RESOLVED'", + characterId)) + .isOne(); + + var quarantined = + ownerDsl.fetchSingle( + "SELECT actor_identity_status, actor_identity_quarantine_reason " + + "FROM characters WHERE character_uuid = ?", + characterId); + assertThat(quarantined.get("actor_identity_status", String.class)).isEqualTo("QUARANTINED"); + assertThat(quarantined.get("actor_identity_quarantine_reason", String.class)) + .isEqualTo("OWNER_PROVENANCE_REVOKED"); + + assertThat( + ownerDsl + .fetchSingle( + "SELECT (to_jsonb(c) - 'actor_identity_status' " + + "- 'actor_identity_quarantine_reason')::text FROM characters c " + + "WHERE character_uuid = ?", + characterId) + .get(0, String.class)) + .isEqualTo(immutableActorBefore); + assertThat( + retainedOperationRow( + ownerDsl, + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))) + .isEqualTo(operationBefore); + assertThatThrownBy( + () -> + ownerDsl.execute( + "UPDATE characters SET creation_descriptor_digest=? " + + "WHERE character_uuid=?", + "sha256:" + "f".repeat(64), + characterId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining("CHARACTER_CREATE authored identity/provenance is immutable"); + var published = published(proof); + var account = new AuthenticatedAccountSelector(accountId); + assertThat(ownerRepository.readPlayerCreatedRoster(account, published)).isEmpty(); + assertSelectedActorUnavailable(ownerRepository, account, published, characterId); + assertThat(ownerRepository.replay(proof.request()).orElseThrow().toByteArray()) + .containsExactly(terminal.toByteArray()); + assertThat( + ownerDsl.fetchCount( + DSL.table("characters"), + DSL.field("account_id") + .isNotNull() + .and(DSL.field("character_uuid").eq(characterId)))) + .isZero(); + assertThat(new CharacterRepository(ownerDsl).findById(privateCharacterId)).isEmpty(); + assertThatThrownBy( + () -> + ownerDsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, " + + "playable_state_namespace_id, playable_state_scope, account_id, " + + "tenant_id, name) VALUES (?, ?, ?, ?, " + + "'PLAYABLE_STATE_SCOPE_SHARED', 45, ?, 'unqualified quarantine')", + UUID.randomUUID(), + accountId, + UUID.fromString(proof.action().scope().tenantId()), + UUID.randomUUID(), + privateTenantId)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasStackTraceContaining( + "Entity numeric source key is reserved by an immutable empty-source receipt"); + } + + private static void assertSelectedActorUnavailable( + EntityCharacterCreateRepository ownerRepository, + AuthenticatedAccountSelector account, + PublishedIdentity published, + UUID characterId) { + assertThatThrownBy( + () -> + ownerRepository.readSelectedPlayerCreatedTerminal(account, published, characterId)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("FAILED_PRECONDITION") + .hasMessageContaining("Selected PLAYER_CREATED character is unavailable"); + } + + private static String retainedRow( + DSLContext ownerDsl, String table, String identityColumn, UUID identity) { + if (!"characters".equals(table) || !"character_uuid".equals(identityColumn)) + throw new IllegalArgumentException("Unsupported retained row selector"); + return ownerDsl + .fetchSingle( + "SELECT xmin::text || ':' || to_jsonb(c)::text FROM characters c " + + "WHERE character_uuid = ?", + identity) + .get(0, String.class); + } + + private static String retainedOperationRow( + DSLContext ownerDsl, String namespace, UUID operationId) { + return ownerDsl + .fetchSingle( + "SELECT xmin::text || ':' || to_jsonb(o)::text " + + "FROM entity_character_create_operations o " + + "WHERE target_namespace = ? AND operation_id = ?", + namespace, + operationId) + .get(0, String.class); + } + private static void migrate(DriverManagerDataSource dataSource, String schema, String target) { var configuration = Flyway.configure() diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index 2b20f86c87..7d0d6f9748 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -114,7 +114,7 @@ void seedLegacyRowsBeforeV1011() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1016"); + .isEqualTo("1017"); } @AfterEach diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java index 83cb5ccb47..383dfe1ac5 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java @@ -1,19 +1,26 @@ package net.firedevops.firemud.entitymanagement.charactercreate; +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.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.nio.file.Path; import java.util.Optional; import java.util.UUID; @@ -25,11 +32,14 @@ import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; import net.firedevops.firemud.entitymanagement.v1.ReadEntityCharacterCreateTerminalRequest; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; /** * Native incoming identity proof only. Owner storage and creation dependencies deliberately deny. @@ -77,7 +87,7 @@ void ownerCertificatesHaveDistinctReadAndMutationPermissions() throws Exception .build()) .addService( ServerInterceptors.intercept( - new EntityCharacterCreateGrpcService(service), + new EntityCharacterCreateGrpcService(service, new SimpleMeterRegistry()), new EntityCharacterCreatePeerInterceptor("firemud"))) .build() .start(); @@ -143,6 +153,54 @@ void ownerCertificatesHaveDistinctReadAndMutationPermissions() throws Exception } } + @Test + void unexpectedOwnerFailuresAreInternalAndCounted() { + var meterRegistry = new SimpleMeterRegistry(); + var nullFailure = new NullPointerException("private failure detail"); + var stateFailure = new IllegalStateException("private state detail"); + + var nullStatus = invokeReadFailure(nullFailure, meterRegistry); + var stateStatus = invokeReadFailure(stateFailure, meterRegistry); + + assertThat(nullStatus.getStatus().getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(nullStatus.getStatus().getDescription()).isEqualTo("Internal error"); + assertThat(nullStatus).hasCause(nullFailure); + assertThat(stateStatus.getStatus().getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(stateStatus.getStatus().getDescription()).isEqualTo("Internal error"); + assertThat(stateStatus).hasCause(stateFailure); + assertThat(meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count()).isEqualTo(2.0); + } + + @Test + void invalidOwnerEvidenceIsDataLossWithCauseAndNoInternalMetric() { + var meterRegistry = new SimpleMeterRegistry(); + var invalidEvidence = new IllegalArgumentException("private invalid evidence detail"); + + var failure = invokeReadFailure(invalidEvidence, meterRegistry); + + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.DATA_LOSS); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Entity creation owner evidence failed validation"); + assertThat(failure).hasCause(invalidEvidence); + assertThat(meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count()).isZero(); + } + + @Test + void explicitGrpcStatusAndStorageFailuresKeepTheirClassification() { + var meterRegistry = new SimpleMeterRegistry(); + var explicit = + Status.PERMISSION_DENIED.withDescription("controlled denial").asRuntimeException(); + var propagated = invokeReadFailure(explicit, meterRegistry); + var storage = new DataAccessResourceFailureException("controlled storage outage"); + var unavailable = invokeReadFailure(storage, meterRegistry); + + assertThat(propagated).isSameAs(explicit); + assertThat(unavailable.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(unavailable.getStatus().getDescription()) + .isEqualTo("Entity creation storage unavailable; no terminal inferred"); + assertThat(meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count()).isZero(); + } + private static ManagedChannel channel(int port, LoopbackMtlsTestPki.Pki pki, String alias) throws Exception { var identity = pki.identity(alias); @@ -166,4 +224,22 @@ private static CharacterCreateProtectionReference reference() { .setProtectionFence(1L) .build(); } + + @SuppressWarnings("unchecked") + private static StatusRuntimeException invokeReadFailure( + RuntimeException failure, SimpleMeterRegistry meterRegistry) { + var owner = mock(EntityCharacterCreateService.class); + doThrow(failure).when(owner).read(any()); + StreamObserver observer = mock(StreamObserver.class); + + new EntityCharacterCreateGrpcService(owner, meterRegistry) + .readEntityCharacterCreateTerminal( + ReadEntityCharacterCreateTerminalRequest.getDefaultInstance(), observer); + + var captured = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(captured.capture()); + verify(observer, never()).onNext(any()); + assertThat(captured.getValue()).isInstanceOf(StatusRuntimeException.class); + return (StatusRuntimeException) captured.getValue(); + } } diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index fd3c97aa58..c6c6550d74 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -114,6 +114,9 @@ tasks.named("bootRun") { val isWindows = System.getProperty("os.name").lowercase().contains("windows") tasks.withType().configureEach { + inputs.file( + rootProject.file("services/account-service/src/testFixtures/resources/charactercreate/public-action.json"), + ) jvmArgumentProviders.add( objects.newInstance().apply { testClasspath.from(classpath) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java index 94d6baa64f..d2bf6252fc 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java @@ -8,6 +8,7 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.time.Clock; @@ -118,7 +119,7 @@ public ControlledPlayerCreatedOriginalOwnerFixture( Objects.requireNonNull(supplied, "complete controlled publication fixture"); this.dataSource = Objects.requireNonNull(dataSource); Objects.requireNonNull(clock); - migrations = Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + migrations = resolveMigrationDirectory(); schema = Objects.requireNonNull(dataSource.getSchema(), "caller-owned isolated schema"); migrate("1005"); var manager = new DataSourceTransactionManager(dataSource); @@ -469,6 +470,23 @@ private void migrate(String version) { .migrate(); } + private static Path resolveMigrationDirectory() { + Path current = Path.of("").toAbsolutePath().normalize(); + while (current != null) { + if (Files.isRegularFile(current.resolve("settings.gradle.kts"))) { + Path migrations = + current.resolve("services/game-session-service/src/main/resources/db/migration"); + if (Files.isDirectory(migrations)) { + return migrations; + } + throw new IllegalStateException( + "Could not resolve Game Session migration directory from repository root " + current); + } + current = current.getParent(); + } + throw new IllegalStateException("Could not locate repository root from the current directory"); + } + private static StartSessionPostAuthorizationExecutionTuple freshControlledTuple( StartSessionPostAuthorizationExecutionTuple original, Clock clock) throws Exception { var bundle = From faf3ab8761c545cb4dd0b8579cad71dad8a41c2f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:02:25 +1300 Subject: [PATCH 13/22] Supply recovery metrics in created owner unit fixtures --- ...onicalGameplayRosterReferenceOwnerTest.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java index f3dd48a718..ac316e5567 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java @@ -14,6 +14,7 @@ import com.google.protobuf.ByteString; import io.grpc.Status; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; import java.util.Optional; @@ -89,7 +90,14 @@ class CanonicalGameplayRosterReferenceOwnerTest { request, 1, UUID.randomUUID(), null); private final CanonicalGameplayRosterReferenceOwner owner = new CanonicalGameplayRosterReferenceOwner( - repository, transactions(), published, routes, admissions, recovery, created); + repository, + transactions(), + published, + routes, + admissions, + recovery, + new SimpleMeterRegistry(), + created); @BeforeEach void controlledSource() { @@ -143,7 +151,13 @@ void freshCreatedReservationResolvesExactSourceOutsideSqlThenLocksCurrentPointer void missingCreatedCollaboratorFailsClosedWhileSixArgumentCompositionStillExists() { var preseededComposition = new CanonicalGameplayRosterReferenceOwner( - repository, transactions(), published, routes, admissions, recovery); + repository, + transactions(), + published, + routes, + admissions, + recovery, + new SimpleMeterRegistry()); assertThatThrownBy(() -> preseededComposition.begin(request)) .isInstanceOf(CanonicalPublishedPlayerRouteReadService.StorageUnavailableException.class); verify(repository, never()).begin(any()); From c282e2c031d97589ab97fc6f676b985c37d628c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:02:52 +1300 Subject: [PATCH 14/22] Name the explicit preseeded owner composition proof --- .../service/CanonicalGameplayRosterReferenceOwnerTest.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/CanonicalGameplayRosterReferenceOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java index ac316e5567..4b70462437 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java @@ -148,7 +148,7 @@ void freshCreatedReservationResolvesExactSourceOutsideSqlThenLocksCurrentPointer } @Test - void missingCreatedCollaboratorFailsClosedWhileSixArgumentCompositionStillExists() { + void missingCreatedCollaboratorFailsClosedInPreseededComposition() { var preseededComposition = new CanonicalGameplayRosterReferenceOwner( repository, From 7f44ad92a48e0f50cbe0c16df412777921c9a775 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 05:51:14 +1300 Subject: [PATCH 15/22] Record current-parent created roster qualification --- .../gameplay-rules-entities-and-effects.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 8433eb6685..99eaf12f15 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for gameplay rules, entities, and The unregistered composition implements Entity's `CHARACTER_CREATE` terminal writer and source-bound created-roster capture/readback, together with Common evidence and the immediate Game Session receipt consumer. Entity V1015 and V1016 retain the creation terminal and created snapshot branch; Game Session V1020 retains the distinct created receipt while preserving the strict preseeded branch. Canonical behavior belongs to the [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) and [sealed roster storage](../../architecture/microservices/entity-management-service/runtime-and-data.md#player-created-snapshot-storage). -The current bounded-retirement parent carry preserves the created owner and immediate consumer while extending Entity with forward V1020 typed target recognition. The complete created-source identity remains part of the shared account/target fence; independent changed-roster snapshots retain separate proofs, original inventories, holds, horizons and bounded preparation. Actual PostgreSQL proof creates an actor through the Entity writer between empty and populated captures, verifies physically blocked concurrent first seals, and independently acknowledges and disposes the two snapshots without reopening a delayed nonce. Additive metadata initialization preserves immutable prior source bytes, row versions and complete Flyway history; malformed source evidence remains protected. R241 passes the full Entity check and freshly executes 115 PostgreSQL cases with zero failures, errors or skips. Its unchanged 414 unit cases passed in R240, which also passes 140 affected Game Session unit cases, 50 PostgreSQL cases including the initial owner-to-owner composition and populated two-service migration cohort, and affected static analysis. These controlled proofs do not establish production custody, process-death recovery, successful public admission or the still-unrun causal current-supersession writer. Fresh-image qualification for this correction remains pending. +The current bounded-retirement parent carry preserves the created owner and immediate consumer while extending Entity with forward V1020 typed target recognition. The complete created-source identity remains part of the shared account/target fence; independent changed-roster snapshots retain separate proofs, original inventories, holds, horizons and bounded preparation. Actual PostgreSQL proof creates an actor through the Entity writer between empty and populated captures, verifies physically blocked concurrent first seals, and independently acknowledges and disposes the two snapshots without reopening a delayed nonce. Additive metadata initialization preserves immutable prior source bytes, row versions and complete Flyway history; malformed source evidence remains protected. R241 passes the full Entity check and freshly executes 115 PostgreSQL cases with zero failures, errors or skips. Its unchanged 414 unit cases passed in R240, which also passes 140 affected Game Session unit cases, 50 PostgreSQL cases including the initial owner-to-owner composition and populated two-service migration cohort, and affected static analysis. These controlled proofs do not establish production custody, process-death recovery, successful public admission or the still-unrun causal current-supersession writer. R242 rebuilds fresh Entity and Game Session images at `337f5b86665939c032b07122d391dd099ee2a4d1` and passes held Gateway/Telnet denial plus the separate isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline. Authenticated teardown succeeds; independent exact-project checks confirm no remaining containers, networks or volumes. That checkpoint includes the final #3295 `bd032b622d7696ebfeeab462d9c2907b9eed8765` documentation carry and the same code qualified in R240/R241. Earlier parent qualification receives #3295 at `cc33169ca1354872e101c4ef42777b0e79032473`, including its complete release/World validation correction. R116 passes the full Game Session check, formatting and affected static analysis with 2,568 unit cases, 365 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. This includes the actual initial owner-to-owner composition, which freshly passes in 30.763 seconds. The tested postimages are retained at `c9774094d76097ade5dcc5530d346e4960e613d8` after canonical fixture formatting. Unchanged Entity production source retains R113’s 402 unit and 94 PostgreSQL executions; R116 also passes both affected fixture static checks after correcting the earlier fixture-only SpotBugs failures. R117 freshly rebuilds that checkpoint and passes held Gateway/Telnet denial and isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK`, followed by authenticated teardown and independently confirmed exact-project container, network and volume absence. 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 a4d58ad3ba..1272e219c4 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. -The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records current-parent qualification at `c9774094d76097ade5dcc5530d346e4960e613d8`, including #3295’s complete release/World validation correction. The full Game Session check and initial authenticated source → Entity created capture/selected read → durable Game Session receipt/replay composition pass, together with affected fixture static checks; fresh rebuilt held-edge denial, isolated backend transport checks and authenticated teardown also pass. Entity and Common component results retain their explicitly recorded source attribution. Created recovery/retirement/ACK and current Human writer-refusal components remain separate proof: full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. +The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the bounded-retirement parent carry at `337f5b86665939c032b07122d391dd099ee2a4d1`, receiving #3295 `bd032b622d7696ebfeeab462d9c2907b9eed8765`. Its controlled initial owner-to-owner composition, additive typed retention, current affected Game Session checks, full Entity gate and fresh-image proof are qualified there; the earlier full Game Session gate at `c9774094d76097ade5dcc5530d346e4960e613d8` retains its separate attribution. Created recovery/retirement/ACK and current Human writer-refusal components remain separate proof: full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. ### Public character-creation and created-roster source preparation From d92b28bbc7faf4292b7bc21d5e7c56e0658da4b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 06:54:04 +1300 Subject: [PATCH 16/22] Qualify created roster retention progress and large owner calls --- .../runtime-and-data.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 4 + .../player-access-and-session.md | 2 + ...edPlayerCreatedRosterTerminalFixtures.java | 131 +++++++- ...anonicalGameplayRosterOwnerReadClient.java | 31 +- ...icalGameplayRosterRetentionRepository.java | 7 +- .../CanonicalGameplayRosterGrpcAdapter.java | 16 +- ...osterRetentionPostgresIntegrationTest.java | 63 ++++ ...GameplayRosterOwnerReadClientMtlsTest.java | 77 ++++- ...icalGameplayRosterOwnerReadClientTest.java | 79 ++++- ...anonicalGameplayRosterGrpcAdapterTest.java | 41 +++ ...osterReferencePostgresIntegrationTest.java | 311 ++++++++++++++++++ ...haracterCreatePublicSourceServiceTest.java | 10 +- ...anonicalPlayerCreatedRosterClientTest.java | 174 +--------- ...nicalGameplayRosterReferenceOwnerTest.java | 5 +- ...calGameplayRosterSelectionServiceTest.java | 201 ++--------- .../ControlledPlayerCreatedRosterValues.java | 211 ++++++++++++ 18 files changed, 995 insertions(+), 372 deletions(-) create mode 100644 services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedRosterValues.java diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index fc792275ad..3911522f5a 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -344,7 +344,7 @@ The configured cadence and batch bound limit each owner-local sweep. Its bounded #### Player-created snapshot storage -Forward `V1016__player_created_roster_snapshot_receipts.sql` extends the existing sealed-roster family after Entity creation V1015. A `PLAYER_CREATED` snapshot requires `SHARED` scope and immutable canonical `canonical_player_created_source_identity` bytes; preseeded snapshots keep that column null. Immutable entry-policy metadata selects the applicable admission, original receipt, lifecycle-proof and outbox branch. The created original receipt is distinct and mutually exclusive with the preseeded receipt. Prior preseeded digest/history, provenance, immutability, reference/hold, epoch, conditional-disposal and late-nonce guards remain effective. Created receipt/proof/ACK storage uses its explicit purpose budgets, including the complete selected terminal in retirement evidence, while existing preseeded caps remain unchanged. The [Entity API owner](./api-contracts.md#player-created-roster-and-selected-character) defines the wire identities and bounds. +Forward `V1016__player_created_roster_snapshot_receipts.sql` extends the existing sealed-roster family after Entity creation V1015. A `PLAYER_CREATED` snapshot requires `SHARED` scope and immutable canonical `canonical_player_created_source_identity` bytes; preseeded snapshots keep that column null. Immutable entry-policy metadata selects the applicable admission, original receipt, lifecycle-proof and outbox branch. The created original receipt is distinct and mutually exclusive with the preseeded receipt. Prior preseeded digest/history, provenance, immutability, reference/hold, epoch, conditional-disposal and late-nonce guards remain effective. Created receipt/proof/ACK storage uses its explicit purpose budgets, including the complete selected terminal in retirement evidence, while existing preseeded caps remain unchanged. The [Entity API owner](./api-contracts.md#player-created-roster-and-selected-character) defines the wire identities and bounds. Entity's original-reference, retirement acknowledgement and confirmation client calls use a finite ten-second RPC deadline for validated `PLAYER_CREATED` targets; preseeded calls and generic owner reads retain five seconds. These deadlines cover the RPC itself, with request prevalidation and response validation performed separately. Forward `V1020__canonical_roster_created_retirement_recognition.sql` extends retained target classification and snapshot inventory with additive typed recognition. A created retirement target binds the canonical account, complete target and complete canonical created-source identity; preseeded target bytes remain unchanged. Bounded initialization adds version-two metadata against exact immutable source bytes and positive retirement proof without replacing the original classification, snapshot, transfer or seal rows. The effective metadata view requires the applicable actual source family and exact retained evidence; a version marker alone grants no authority. A valid typed classification can qualify an earlier unrecognized created source, while malformed or uninitialized retained evidence keeps the roster boundary protected. Legacy seals whose stored target omits the created source stay protected rather than being rewritten. Created siblings use the same shared acquisition fence and independent per-snapshot preparation, holds, horizons and disposal checks described in [sealed roster retention](#sealed-canonical-roster-retention). 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 fe595ad9fa..e0fc17de6f 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -85,7 +85,7 @@ Compact transfer receipts survive original removal and remain protected until En #### Player-created original roster storage -The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. The original-reference response preserves the complete selected payload within its 194 MiB purpose bound; retirement observation preserves it within the 195 MiB created-ACK bound with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within the existing recovery bound. These purpose-specific byte limits preserve owner bytes and preseeded limits; they do not widen global gRPC defaults. Published V1020 supplies the distinct receipt branch. V1018 and V1019 were reserved in an unpublished receiving source and must not later be introduced below the published V1020 frontier. The local receiving source assigns the next unused versions, V1021 for canonical UUID runtime and V1022 for creation-protection storage, preserving their SQL bytes; qualification requires a fresh migration frontier and actual-parent upgrade proof. These local storage owners remain unregistered and separate from this created-receipt PR, and do not qualify the full receiving chain. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) and [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) for current proof limits. +The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. The original-reference response preserves the complete selected payload within its 194 MiB purpose bound; retirement observation preserves it within the 195 MiB created-ACK bound with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within the existing recovery bound. These purpose-specific byte limits preserve owner bytes and preseeded limits; they do not widen global gRPC defaults. Current implementation and migration qualification are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) and [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The unregistered bounded retention service uses the configured cadence and batch bound, pages past protected candidates, and reports oldest blocking age, cleanup lag, pending-transfer age and fixed cleanup outcomes without identity-bearing metric labels. Unfinished or unavailable authority remains protected. Production registration and real gameplay admission stay closed pending the [owning proof gate](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 99eaf12f15..a21cda37e0 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -12,6 +12,10 @@ The unregistered composition implements Entity's `CHARACTER_CREATE` terminal wri The current bounded-retirement parent carry preserves the created owner and immediate consumer while extending Entity with forward V1020 typed target recognition. The complete created-source identity remains part of the shared account/target fence; independent changed-roster snapshots retain separate proofs, original inventories, holds, horizons and bounded preparation. Actual PostgreSQL proof creates an actor through the Entity writer between empty and populated captures, verifies physically blocked concurrent first seals, and independently acknowledges and disposes the two snapshots without reopening a delayed nonce. Additive metadata initialization preserves immutable prior source bytes, row versions and complete Flyway history; malformed source evidence remains protected. R241 passes the full Entity check and freshly executes 115 PostgreSQL cases with zero failures, errors or skips. Its unchanged 414 unit cases passed in R240, which also passes 140 affected Game Session unit cases, 50 PostgreSQL cases including the initial owner-to-owner composition and populated two-service migration cohort, and affected static analysis. These controlled proofs do not establish production custody, process-death recovery, successful public admission or the still-unrun causal current-supersession writer. R242 rebuilds fresh Entity and Game Session images at `337f5b86665939c032b07122d391dd099ee2a4d1` and passes held Gateway/Telnet denial plus the separate isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline. Authenticated teardown succeeds; independent exact-project checks confirm no remaining containers, networks or volumes. That checkpoint includes the final #3295 `bd032b622d7696ebfeeab462d9c2907b9eed8765` documentation carry and the same code qualified in R240/R241. +The next review correction counts typed snapshot recognition as classification progress and preserves unavailable owner-evidence status after caller validation. R247 freshly passes all 39 Entity retention PostgreSQL cases, including five typed-only rows drained as 2, 2, 1, 0 without rewriting source rows or their row versions. R246 supplies 20 affected Entity and 51 Game Session unit passes; after correcting a shared-fixture session mismatch and preserving separate per-actor creation identities, R248 freshly passes the 34 Game Session client and selection cases. Its initial SQL-proof compilation failure supplies no runtime credit. R250 separately passes 15 Entity owner-client unit and mTLS cases. + +The large-payload qualification fills the four existing opaque limits (168 MiB total) and maximizes the supported feedback field in one valid canonical action family. R249 reproduces the five-second acknowledgement deadline failure through actual Game Session PostgreSQL storage, the durable owner and authenticated adapter, and the production Entity client. R251 then passes the initial and retired reads, acknowledgement, confirmation and exact retained-value assertions with a ten-second created-purpose RPC budget. Actual API times are 3.208, 3.062, 10.354 and 8.784 seconds respectively; API timing includes validation outside the RPC deadline. Original responses are 177,563,987 and 177,564,163 bytes, the acknowledgement request is 177,565,210 bytes and confirmation is 177,565,366 bytes. The independent 192–195 MiB envelopes are not claimed to be reachable maxima. R250's earlier combined run ended with exit 137; kernel evidence records a global Java OOM kill, without establishing a precise process attribution. The successful isolated R251 reduces temporary test copies and uses a private 3 GiB test heap, which is qualification headroom rather than a production recommendation. Controlled historical creation, superseding route/admission values and test PKI do not establish genuine source issuance, the current supersession writer, production latency or capacity, registration, admission or activation. + Earlier parent qualification receives #3295 at `cc33169ca1354872e101c4ef42777b0e79032473`, including its complete release/World validation correction. R116 passes the full Game Session check, formatting and affected static analysis with 2,568 unit cases, 365 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. This includes the actual initial owner-to-owner composition, which freshly passes in 30.763 seconds. The tested postimages are retained at `c9774094d76097ade5dcc5530d346e4960e613d8` after canonical fixture formatting. Unchanged Entity production source retains R113’s 402 unit and 94 PostgreSQL executions; R116 also passes both affected fixture static checks after correcting the earlier fixture-only SpotBugs failures. R117 freshly rebuilds that checkpoint and passes held Gateway/Telnet denial and isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK`, followed by authenticated teardown and independently confirmed exact-project container, network and volume absence. Prior component qualification R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases with affected static analysis, formatting and documentation checks. Unchanged Common and broader Game Session physical proof retain R86 attribution: 1,020 Common unit cases, 364 Game Session PostgreSQL cases and 36 cross-service cases. R86's earlier 396 Entity and 2,565 Game Session unit counts are superseded by the new executions, rather than credited as fresh runs. Native Entity proof includes the actual retained creation writer feeding authenticated source-bound snapshot capture; socket fixtures use controlled PKI and owner facts, including a complete 5 MiB terminal rather than physical proof at every maximum purpose bound. After the documentation-only parent carry, R93 rebuilds fresh images at `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project inspection confirms no remaining containers, networks or volumes. The documentation-only carry through parent `2aa25d9327bd9c15698c69168f2c96254f0fa732` preserves that code; the later release/World correction is qualified by R116 and R117 above. This validates controlled components, storage, packaging and the isolated backend baseline; it does not exercise a registered production created-actor flow. 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 1272e219c4..e2983f7aff 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,6 +12,8 @@ The unregistered Game Session composition consumes the independently resolved cu The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the bounded-retirement parent carry at `337f5b86665939c032b07122d391dd099ee2a4d1`, receiving #3295 `bd032b622d7696ebfeeab462d9c2907b9eed8765`. Its controlled initial owner-to-owner composition, additive typed retention, current affected Game Session checks, full Entity gate and fresh-image proof are qualified there; the earlier full Game Session gate at `c9774094d76097ade5dcc5530d346e4960e613d8` retains its separate attribution. Created recovery/retirement/ACK and current Human writer-refusal components remain separate proof: full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. +Game Session migration qualification follows the published created-reference V1020 and subsequent recovery-scheduling V1021. The unpublished runtime and creation-protection receivers previously reserved V1018/V1019; an earlier local V1021/V1022 receiving plan predates the scheduling correction and is not a current free-version assignment. Before receiving those owners, verify the actual migration frontier and next unused forward versions, preserve their SQL bytes, and prove the actual-parent upgrade and retained rows/history. Those separate owners remain unregistered; this status grants no runtime, protection or activation authority. + ### Public character-creation and created-roster source preparation The current parent reconciliation at `afc766f0ac093f1adac069e28f4a48d7fcc13e7d` carries the qualified sibling-retirement correction while preserving this stage’s 23-file source boundary. R228 freshly passes 13 affected Entity unit/mTLS cases, 36 Game Session unit/mTLS cases and 42 Game Session PostgreSQL cases, including the current-pointer reader and two-service retained-migration cohort, with zero failures, errors or skips and enabled static/format checks. R229 rebuilds fresh Entity and Game Session images at that clean checkpoint and passes held Gateway/Telnet denial plus isolated backend WORLDS/LOGIN/PLAY/LOOK; authenticated teardown and independent exact-project checks confirm no remaining containers, networks or volumes. This qualifies the carried source and packaging. Earlier full-suite results below retain their original attribution; these runs do not establish genuine source custody, created-player admission or activation. diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java index 7fdede06fc..2779b4df53 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/ControlledPlayerCreatedRosterTerminalFixtures.java @@ -63,7 +63,18 @@ public record Bundle( /** One real canonical action/terminal with a controlled 5 MiB opaque Account protection. */ public static Bundle withFiveMebibyteAccountProtection(String namespace) { - var action = action(namespace); + return build(namespace, false, false); + } + + /** + * Controlled known-field vector: saturates every opaque byte field and the authored projection. + */ + public static Bundle withMaximumOpaqueProtections(String namespace, boolean highEntropy) { + return build(namespace, true, highEntropy); + } + + private static Bundle build(String namespace, boolean maximum, boolean highEntropy) { + var action = maximum ? largestFeedbackAction(action(namespace)) : action(namespace); var target = target(action); var source = source(action); var account = action.target().accountId(); @@ -125,7 +136,8 @@ public static Bundle withFiveMebibyteAccountProtection(String namespace) { .build(); var selected = CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse( - selectedRequest, selectedCreatedResponse(action, target, source, selectedRequest)); + selectedRequest, + selectedCreatedResponse(action, target, source, selectedRequest, maximum, highEntropy)); var originalRequest = CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( UUID.fromString(operation), @@ -230,7 +242,9 @@ private static CanonicalSelectedPlayerCreatedCharacterResponse selectedCreatedRe CharacterCreateOperatorAction action, CanonicalGameplayRosterTarget target, CanonicalPlayerCreatedRosterSourceIdentity source, - CanonicalSelectedPlayerCreatedCharacterRequest request) { + CanonicalSelectedPlayerCreatedCharacterRequest request, + boolean maximum, + boolean highEntropy) { byte[] originalAction = CharacterCreateOperatorActionCodec.encode(action); String mutationDigest = CharacterCreateOperatorActionCodec.mutationDigest(originalAction); ReadOriginalCharacterCreateRequest originalRequest = @@ -256,16 +270,28 @@ private static CanonicalSelectedPlayerCreatedCharacterResponse selectedCreatedRe .setPurpose("CHARACTER_CREATE") .setOriginalAction(ByteString.copyFrom(originalAction)) // This opaque fixture is preserved as bytes and is not treated as remote authority. - .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-source-readback")) + .setOriginalSourceReadback( + maximum + ? opaque(32 * 1024 * 1024, 301, highEntropy) + : ByteString.copyFromUtf8("controlled-source-readback")) .setMutationDigest(mutationDigest) .build(); EntityCharacterCreateTerminal terminal = EntityCharacterCreateTerminal.newBuilder() .setOriginalRequest(terminalRequest) .setAccountOriginal(accountOriginal) - .setOriginalAccountProtection(ByteString.copyFrom(new byte[5 * 1024 * 1024])) - .setOriginalGameSessionProtection(ByteString.copyFromUtf8("game-session-protection")) - .setOriginalWorldProtection(ByteString.copyFromUtf8("world-protection")) + .setOriginalAccountProtection( + maximum + ? opaque(40 * 1024 * 1024, 302, highEntropy) + : ByteString.copyFrom(new byte[5 * 1024 * 1024])) + .setOriginalGameSessionProtection( + maximum + ? opaque(48 * 1024 * 1024, 303, highEntropy) + : ByteString.copyFromUtf8("game-session-protection")) + .setOriginalWorldProtection( + maximum + ? opaque(48 * 1024 * 1024, 304, highEntropy) + : ByteString.copyFromUtf8("world-protection")) .setEntityIntakeRequestId(uuid(125)) .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) .setCharacterId(request.getSelectedCharacterUuid()) @@ -287,6 +313,97 @@ private static CanonicalSelectedPlayerCreatedCharacterResponse selectedCreatedRe .build(); } + private static ByteString opaque(int size, long seed, boolean highEntropy) { + var random = new java.util.Random(seed); + byte[] chunk = new byte[64 * 1024]; + var output = ByteString.newOutput(chunk.length); + for (int remaining = size; remaining > 0; ) { + int count = Math.min(remaining, chunk.length); + if (highEntropy) random.nextBytes(chunk); + output.write(chunk, 0, count); + remaining -= count; + } + return output.toByteString(); + } + + private static CharacterCreateOperatorAction largestFeedbackAction( + CharacterCreateOperatorAction base) { + CharacterCreateOperatorActionCodec.encode(base); + CharacterCreateOperatorAction best = base; + int low = 1; + int high = CharacterCreateOperatorActionCodec.MAX_EXACT_UTF8_SOURCE_BYTES; + while (low <= high) { + int count = low + (high - low) / 2; + var candidate = withFeedbackText(base, "x".repeat(count)); + try { + CharacterCreateOperatorActionCodec.encode(candidate); + best = candidate; + low = count + 1; + } catch (IllegalArgumentException beyondKnownFieldLimit) { + high = count - 1; + } + } + return best; + } + + private static CharacterCreateOperatorAction withFeedbackText( + CharacterCreateOperatorAction base, String text) { + var mutation = base.mutation(); + var source = mutation.authoredSource(); + var prior = source.safeFeedback(); + String definition = prior.definitionJson().replace("Welcome, traveler.", text); + final String digest; + try { + digest = + "sha256:" + + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(definition.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + var feedback = + new CharacterCreateOperatorAction.Rule( + prior.key(), + definition, + digest, + prior.sourceCommitId(), + prior.sourceCommitDigest(), + prior.revisionId(), + prior.revisionOrder()); + var authored = + new CharacterCreateOperatorAction.AuthoredSource( + source.schema(), + source.bindingId(), + source.bindingDigest(), + source.canonicalTenantId(), + source.canonicalVersionId(), + source.worldSourceOperationId(), + source.worldSourceEvidenceDigest(), + source.worldSlug(), + source.publicationWorkflowId(), + source.selectedCommitId(), + source.selectedCommitDigest(), + source.policy(), + source.core(), + source.descriptor(), + source.disposition(), + feedback); + return new CharacterCreateOperatorAction( + base.scope(), + base.target(), + base.expectedVersion(), + new CharacterCreateOperatorAction.Mutation( + mutation.purpose(), + mutation.entryPolicy(), + mutation.catalog(), + mutation.pointer(), + authored, + mutation.canonicalCreationInput()), + base.auditReason()); + } + private static CharacterCreateProtectionReference protectionReference(int value) { return CharacterCreateProtectionReference.newBuilder() .setProtectionId(uuid(value)) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java index d3a00dc3c1..27778c5fde 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java @@ -28,6 +28,7 @@ public final class GameSessionCanonicalGameplayRosterOwnerReadClient CanonicalGameplayRosterOwnerReadServiceGrpc .CanonicalGameplayRosterOwnerReadServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; + private static final long PLAYER_CREATED_CALL_DEADLINE_SECONDS = 10L; private final String workloadNamespace; private final GrpcServerPeerIdentityClientInterceptor serverPeerIdentityInterceptor; @@ -113,7 +114,12 @@ protected String defaultTarget() { } var response = current - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withDeadlineAfter( + callDeadlineSeconds( + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .target(checkedRequest) + .getEntryPolicy()), + TimeUnit.SECONDS) .getCanonicalGameplayRosterReference(request); try { return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence @@ -132,7 +138,12 @@ protected String defaultTarget() { requireRetirementNamespace(request); var response = requireInitializedStub("Game Session retirement owner client is not initialized") - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withDeadlineAfter( + callDeadlineSeconds( + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .target(request.getOriginalSelection()) + .getEntryPolicy()), + TimeUnit.SECONDS) .acknowledgeCanonicalGameplayRosterRetirement(request); return CanonicalGameplayRosterRetirementEvidence.requireAcknowledgementResponse( request, response); @@ -146,11 +157,25 @@ protected String defaultTarget() { requireRetirementNamespace(request.getAcknowledgementRequest()); var response = requireInitializedStub("Game Session retirement owner client is not initialized") - .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .withDeadlineAfter( + callDeadlineSeconds( + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .target(request.getAcknowledgementRequest().getOriginalSelection()) + .getEntryPolicy()), + TimeUnit.SECONDS) .confirmCanonicalGameplayRosterRetirementAcknowledgement(request); return CanonicalGameplayRosterRetirementEvidence.requireConfirmationResponse(request, response); } + private static long callDeadlineSeconds( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy entryPolicy) { + return entryPolicy + == net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED + ? PLAYER_CREATED_CALL_DEADLINE_SECONDS + : CALL_DEADLINE_SECONDS; + } + private static void requireRetirementTransport() { if (org.springframework.transaction.support.TransactionSynchronizationManager .isActualTransactionActive() diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java index 51531175dd..df9953ec78 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java @@ -976,7 +976,7 @@ public int classifyRetainedDependencies(int limit) { if (limit <= 0) throw new IllegalArgumentException("Bounded retained classification page required"); dsl.fetchSingle("SELECT entity_roster_initialize_snapshot_targets(?)", limit); - initializeCreatedSnapshotTargets(null, limit); + int createdSnapshots = initializeCreatedSnapshotTargets(null, limit); initializeDisposedSealTargets(limit); var pending = dsl.fetch( @@ -993,7 +993,7 @@ public int classifyRetainedDependencies(int limit) { source.get("source_kind", String.class), source.get("operation_uuid", UUID.class), source.get("admission_uuid", UUID.class)); - return pending.size(); + return createdSnapshots + pending.size(); } private void initializeSnapshotTarget(UUID snapshot) { @@ -1006,7 +1006,7 @@ private void initializeSnapshotTarget(UUID snapshot) { initializeCreatedSnapshotTargets(snapshot, 1); } - private void initializeCreatedSnapshotTargets(UUID snapshot, int limit) { + private int initializeCreatedSnapshotTargets(UUID snapshot, int limit) { var pending = dsl.fetch( "SELECT m.*, (jsonb_populate_record(NULL::entity_canonical_gameplay_roster_snapshots, m.source_snapshot_projection)).canonical_player_created_source_identity AS retained_source " @@ -1041,6 +1041,7 @@ private void initializeCreatedSnapshotTargets(UUID snapshot, int limit) { known ? source.get("target_projection", org.jooq.JSONB.class) : null, source.get("source_snapshot_projection", org.jooq.JSONB.class)); } + return pending.size(); } /** Missing payload supplies no authority: only an already guarded positive disposed seal does. */ diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java index fbedc06d9b..38e4e01141 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java @@ -109,7 +109,13 @@ public void listPlayerCreatedRoster( requireTrustedPeer(); CanonicalPlayerCreatedRosterEvidence.requireRequest(request); if (playerCreatedRosterService == null) throw new PlayerCreatedRosterUnavailableException(); - var serviceResponse = playerCreatedRosterService.list(request); + CanonicalPlayerCreatedRosterResponse serviceResponse; + try { + serviceResponse = playerCreatedRosterService.list(request); + } catch (IllegalArgumentException invalidOwnerEvidence) { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException( + invalidOwnerEvidence); + } try { response = CanonicalPlayerCreatedRosterEvidence.requireResponse(request, serviceResponse); } catch (IllegalArgumentException invalidOutput) { @@ -135,7 +141,13 @@ public void readSelectedPlayerCreatedCharacter( requireTrustedPeer(); CanonicalPlayerCreatedRosterEvidence.requireSelectedRequest(request); if (playerCreatedRosterService == null) throw new PlayerCreatedRosterUnavailableException(); - var serviceResponse = playerCreatedRosterService.selected(request); + CanonicalSelectedPlayerCreatedCharacterResponse serviceResponse; + try { + serviceResponse = playerCreatedRosterService.selected(request); + } catch (IllegalArgumentException invalidOwnerEvidence) { + throw new CanonicalGameplayRosterOwnerEvidencePort.OwnerEvidenceUnavailableException( + invalidOwnerEvidence); + } try { response = CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, serviceResponse); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java index d59ec55ca7..4a957778d2 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java @@ -904,6 +904,69 @@ private String pageSourceRow(String table, String key, UUID value) { .get(0, String.class); } + @Test + void typedOnlySnapshotRecognitionReportsEveryBoundedPageBeforeDrainingToZero() { + int pageSize = 2; + int snapshotCount = 5; + transaction.executeWithoutResult( + ignored -> { + for (int index = 0; index < snapshotCount; index++) { + seedCreatedSnapshot(createdReceipt(createdRequest()), 0); + } + }); + // Sealing captures V1 inventory through the existing SQL trigger; only typed recognition is + // pending. + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM entity_canonical_roster_snapshot_targets " + + "WHERE source_kind = 'SNAPSHOT' AND recognition_version = 1 " + + "AND source_snapshot_projection->>'entry_policy' = 'PLAYER_CREATED'") + .get(0, Long.class)) + .isEqualTo((long) snapshotCount); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_admissions"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))).isZero(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM entity_canonical_roster_snapshot_targets WHERE recognition_version = 2") + .get(0, Long.class)) + .isZero(); + String retainedEvidenceSql = + "SELECT row_to_json(s)::text || ':' || s.xmin::text FROM entity_canonical_gameplay_roster_snapshots s " + + "UNION ALL SELECT row_to_json(m)::text || ':' || m.xmin::text FROM entity_canonical_roster_snapshot_targets m " + + "WHERE recognition_version = 1 ORDER BY 1"; + List retainedEvidence = + dsl.fetch(retainedEvidenceSql).map(row -> row.get(0, String.class)); + + for (int recognized = 0; recognized < snapshotCount; ) { + int expectedPage = Math.min(pageSize, snapshotCount - recognized); + assertThat( + transaction.execute( + ignored -> repository.classifyRetainedDependencies(pageSize))) + .isEqualTo(expectedPage); + recognized += expectedPage; + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM entity_canonical_roster_snapshot_targets " + + "WHERE source_kind = 'SNAPSHOT' AND recognition_version = 2 AND classification_state = 'KNOWN'") + .get(0, Long.class)) + .isEqualTo((long) recognized); + assertThat( + dsl.fetchSingle("SELECT entity_roster_target_classification_pending()") + .get(0, Boolean.class)) + .isEqualTo(recognized < snapshotCount); + assertThat(dsl.fetch(retainedEvidenceSql).map(row -> row.get(0, String.class))) + .containsExactlyElementsOf(retainedEvidence); + } + assertThat( + transaction.execute( + ignored -> repository.classifyRetainedDependencies(pageSize))) + .isZero(); + assertThat(dsl.fetch(retainedEvidenceSql).map(row -> row.get(0, String.class))) + .containsExactlyElementsOf(retainedEvidence); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_admissions"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))).isZero(); + } + @Test void boundedTargetClassificationPassesTrueUnknownAndKeepsEveryAdmissionBoundaryClosed() { assertThat(transaction.execute(ignored -> repository.classifyRetainedDependencies(1))) diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java index f304892834..e2eae8cc88 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java @@ -33,6 +33,7 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; @@ -229,11 +230,59 @@ void authenticatedRetirementTransferUsesExactBytesAndNoAmbientClaims() throws Ex void createdOriginalAndRetirementPreserveCompleteTerminalAboveDefaultReceiveLimit() throws Exception { // Controlled foreign proofs; actual file-backed Entity client and socket mTLS only. + boolean maximum = Boolean.getBoolean("firemud.test.created-retirement.maximum-payload"); + boolean highEntropy = + Boolean.parseBoolean( + System.getProperty("firemud.test.created-retirement.high-entropy", "true")); var fixture = - ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection(NAMESPACE); + maximum + ? ControlledPlayerCreatedRosterTerminalFixtures.withMaximumOpaqueProtections( + NAMESPACE, highEntropy) + : ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection( + NAMESPACE); + if (maximum) { + System.out.println( + "created-purpose-bytes terminal=" + + fixture.selected().getTerminal().getSerializedSize() + + " selected=" + + fixture.selected().getSerializedSize() + + " original=" + + fixture.original().getSerializedSize() + + " retired=" + + fixture.acknowledgementRequest().getObservedRetirement().getSerializedSize() + + " ack=" + + fixture.acknowledgementRequest().getSerializedSize() + + " confirmation=" + + fixture.confirmation().getSerializedSize() + + " action=" + + fixture.selected().getTerminal().getAccountOriginal().getOriginalAction().size() + + " terminalSlack=" + + (CanonicalPlayerCreatedRosterEvidence.MAX_TERMINAL_BYTES + - fixture.selected().getTerminal().getSerializedSize()) + + " ownerSlack=" + + (CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES + - fixture.original().getSerializedSize()) + + " ackSlack=" + + (CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES + - fixture.acknowledgementRequest().getSerializedSize()) + + " highEntropy=" + + highEntropy); + assertThat(fixture.selected().getTerminal().getOriginalGameSessionProtection().size()) + .isEqualTo(48 * 1024 * 1024); + assertThat(fixture.selected().getTerminal().getOriginalWorldProtection().size()) + .isEqualTo(48 * 1024 * 1024); + assertThat( + fixture + .selected() + .getTerminal() + .getAccountOriginal() + .getOriginalSourceReadback() + .size()) + .isEqualTo(32 * 1024 * 1024); + } int defaultReceiveLimit = 4 * 1024 * 1024; assertThat(fixture.selected().getTerminal().getOriginalAccountProtection().size()) - .isEqualTo(5 * 1024 * 1024); + .isEqualTo((maximum ? 40 : 5) * 1024 * 1024); assertThat(fixture.selected().getTerminal().getSerializedSize()) .isGreaterThan(defaultReceiveLimit); assertThat(fixture.original().getSerializedSize()).isGreaterThan(defaultReceiveLimit); @@ -254,7 +303,9 @@ void createdOriginalAndRetirementPreserveCompleteTerminalAboveDefaultReceiveLimi try (var client = client()) { client.init(); // The production client selects its 194 MiB receive bound from this created request. + long started = System.nanoTime(); var original = client.getCanonicalGameplayRosterReference(fixture.originalRequest()); + if (maximum) reportPurposeCall("read", started); assertThat(original).isEqualTo(fixture.original()); assertThat( CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( @@ -264,8 +315,10 @@ void createdOriginalAndRetirementPreserveCompleteTerminalAboveDefaultReceiveLimi .isEqualTo(fixture.selected().getTerminal().toByteString()); assertThat(observedRequest.get()).isEqualTo(fixture.originalRequest()); assertThat(authorization.get()).isNull(); + started = System.nanoTime(); var acknowledgement = client.acknowledgeCanonicalGameplayRosterRetirement(fixture.acknowledgementRequest()); + if (maximum) reportPurposeCall("ack", started); assertThat(acknowledgement).isEqualTo(fixture.acknowledgement()); assertThat(observedAcknowledgement.get()).isEqualTo(fixture.acknowledgementRequest()); assertThat( @@ -275,9 +328,11 @@ void createdOriginalAndRetirementPreserveCompleteTerminalAboveDefaultReceiveLimi .getCanonicalSelectedPlayerCreatedCharacterReceipt()) .isEqualTo(fixture.selected().toByteString()); assertThat(authorization.get()).isNull(); - assertThat( - client.confirmCanonicalGameplayRosterRetirementAcknowledgement( - fixture.confirmation())) + started = System.nanoTime(); + var confirmed = + client.confirmCanonicalGameplayRosterRetirementAcknowledgement(fixture.confirmation()); + if (maximum) reportPurposeCall("confirmation", started); + assertThat(confirmed) .isEqualTo( CanonicalGameplayRosterRetirementEvidence.confirmationResponse( fixture.confirmation())); @@ -299,6 +354,18 @@ void createdOriginalAndRetirementPreserveCompleteTerminalAboveDefaultReceiveLimi } } + private static void reportPurposeCall(String purpose, long started) { + System.out.println( + "created-purpose-call purpose=" + + purpose + + " apiElapsedNanos=" + + (System.nanoTime() - started) + + " usedHeapBytes=" + + java.lang.management.ManagementFactory.getMemoryMXBean() + .getHeapMemoryUsage() + .getUsed()); + } + private void start(String alias) throws Exception { start(alias, null, 0); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java index 942c462678..b7ec182fab 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java @@ -321,11 +321,49 @@ void onlyCreatedOriginalReferenceCallsWidenTheStubInboundLimit() throws Exceptio .withMaxInboundMessageSize( CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES); assertThat(client.getCanonicalGameplayRosterReference(preseeded)).isEqualTo(preseededResponse); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).withDeadlineAfter(10L, TimeUnit.SECONDS); verify(stub, times(1)) .withMaxInboundMessageSize( CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES); } + @Test + void createdPurposeOriginalAndRetirementCallsUseTenSecondDeadline() throws Exception { + var createdOriginal = createdOriginalRequest(); + var createdReference = + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + createdOriginal, 1L, UUID.randomUUID(), null); + var createdRetirement = retirementRequest(NAMESPACE, true); + var createdAcknowledgement = + CanonicalGameplayRosterRetirementEvidence.response( + createdRetirement, UUID.randomUUID(), 1000); + var createdConfirmation = + CanonicalGameplayRosterRetirementEvidence.confirmation( + createdRetirement, createdAcknowledgement); + var confirmed = + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(createdConfirmation); + var stub = mockStub(); + when(stub.getCanonicalGameplayRosterReference(createdOriginal)).thenReturn(createdReference); + when(stub.acknowledgeCanonicalGameplayRosterRetirement(createdRetirement)) + .thenReturn(createdAcknowledgement); + when(stub.confirmCanonicalGameplayRosterRetirementAcknowledgement(createdConfirmation)) + .thenReturn(confirmed); + var client = newClient(stub); + + assertThat(client.getCanonicalGameplayRosterReference(createdOriginal)) + .isEqualTo(createdReference); + assertThat(client.acknowledgeCanonicalGameplayRosterRetirement(createdRetirement)) + .isEqualTo(createdAcknowledgement); + assertThat(client.confirmCanonicalGameplayRosterRetirementAcknowledgement(createdConfirmation)) + .isEqualTo(confirmed); + + verify(stub, times(3)).withDeadlineAfter(10L, TimeUnit.SECONDS); + verify(stub).getCanonicalGameplayRosterReference(createdOriginal); + verify(stub).acknowledgeCanonicalGameplayRosterRetirement(createdRetirement); + verify(stub).confirmCanonicalGameplayRosterRetirementAcknowledgement(createdConfirmation); + } + @Test void retirementRejectsNamespaceMalformedInputAndAmbientTransactionsBeforeTransport() throws Exception { @@ -387,6 +425,11 @@ void retirementRejectsNamespaceMalformedInputAndAmbientTransactionsBeforeTranspo private static CanonicalGameplayRosterRetirementAcknowledgementRequest retirementRequest( String namespace) { + return retirementRequest(namespace, false); + } + + private static CanonicalGameplayRosterRetirementAcknowledgementRequest retirementRequest( + String namespace, boolean created) { var target = CanonicalGameplayRosterTarget.newBuilder() .setTenantUuid(TENANT_UUID.toString()) @@ -405,15 +448,40 @@ private static CanonicalGameplayRosterRetirementAcknowledgementRequest retiremen .setPublishedReleaseBundleRef("release:exact") .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .setEntryPolicy( - CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) + created + ? CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED + : CanonicalGameplayRosterEntryPolicy + .CANONICAL_ROSTER_ENTRY_POLICY_PRESEEDED_ONLY) .build(); var original = - CanonicalGameplayRosterReferenceEvidence.request( - REQUEST_UUID, ACCOUNT_UUID, UUID.randomUUID(), namespace, target); + created + ? CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( + REQUEST_UUID, + ACCOUNT_UUID, + UUID.randomUUID(), + namespace, + target, + CanonicalPlayerCreatedRosterEvidence.requireSourceIdentity( + CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() + .setSchemaVersion(1) + .setDescriptorUuid(UUID.randomUUID().toString()) + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .setDescriptorDigest("sha256:" + "1".repeat(64)) + .setAuthoredBindingUuid(UUID.randomUUID().toString()) + .setAuthoredBindingDigest("sha256:" + "2".repeat(64)) + .build())) + : CanonicalGameplayRosterReferenceEvidence.request( + REQUEST_UUID, ACCOUNT_UUID, UUID.randomUUID(), namespace, target); + var originalResponse = + created + ? CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + original, 1, UUID.randomUUID(), null) + : CanonicalGameplayRosterReferenceEvidence.response( + original, 1, UUID.randomUUID(), null); var retired = CanonicalGameplayRosterReferenceEvidence.sealRetirement( - CanonicalGameplayRosterReferenceEvidence.response(original, 1, UUID.randomUUID(), null) - .toBuilder() + originalResponse.toBuilder() .setState( CanonicalGameplayRosterReferenceState .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RETIRED) @@ -520,6 +588,7 @@ private static GameSessionCanonicalGameplayRosterOwnerReadClient newClientWithou CanonicalGameplayRosterOwnerReadServiceGrpc .CanonicalGameplayRosterOwnerReadServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withDeadlineAfter(10L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.withMaxInboundMessageSize( CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES)) .thenReturn(stub); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java index cb79b94bdd..e36c3c3ebd 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java @@ -525,6 +525,47 @@ void createdMethodsValidateFullServiceResponsesBeforeReturningThem() { verifyNoInteractions(malformedCallerService); } + @Test + void createdServiceEvidenceValidationFailuresMapToUnavailableForBothMethods() { + var createdService = mock(EntityPlayerCreatedRosterService.class); + var meterRegistry = new SimpleMeterRegistry(); + var adapter = + new CanonicalGameplayRosterGrpcAdapter( + mock(CanonicalGameplayRosterService.class), + mock(CanonicalGameplayRosterSelectedAssignmentService.class), + createdService, + meterRegistry); + var listRequest = playerCreatedRequest(); + when(createdService.list(listRequest)) + .thenThrow(new IllegalArgumentException("retained owner evidence is invalid")); + var listObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse>(); + + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.PLAYER_CREATED_METHOD_NAME, + () -> adapter.listPlayerCreatedRoster(listRequest, listObserver)); + + assertOnlyStatus(listObserver, Status.Code.UNAVAILABLE); + verify(createdService).list(listRequest); + + var selectedRequest = selectedCreatedRequest(); + when(createdService.selected(selectedRequest)) + .thenThrow(new IllegalArgumentException("retained selected evidence is invalid")); + var selectedObserver = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1 + .CanonicalSelectedPlayerCreatedCharacterResponse>(); + + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.SELECTED_PLAYER_CREATED_METHOD_NAME, + () -> adapter.readSelectedPlayerCreatedCharacter(selectedRequest, selectedObserver)); + + assertOnlyStatus(selectedObserver, Status.Code.UNAVAILABLE); + verify(createdService).selected(selectedRequest); + assertThat(meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count()).isZero(); + } + @Test void createdOwnerDeadlineMapsToUnavailableWithoutInternalMetric() { var createdService = mock(EntityPlayerCreatedRosterService.class); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index 2271e78ff8..b27286a94b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -903,6 +903,44 @@ private static void awaitBackendBlockedBy(DSLContext observer, int waitingPid, i .isTrue(); } + private static net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget + currentCreatedTarget(GetCanonicalGameplayRosterReferenceRequest request) { + var target = current(request); + return new net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget( + target.targetNamespace(), + target.tenantSlug(), + target.canonicalTenantId(), + target.worldSlug(), + target.worldDisplayName(), + target.realmId(), + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.canonicalVersionId(), + target.runtimeVersionId(), + target.catalogRevision(), + target.pointerVersion(), + target.admissionPointerSnapshotDigest(), + target.activeWorldEpoch(), + target.initialAdmissionRequestId(), + target.initialAdmissionRequestDigest(), + target.initialAdmissionOriginKind(), + target.expectedPriorPointerVersion(), + target.holdId(), + target.holdFence(), + target.holdBindingDigest(), + target.auditEventId(), + target.ownerProofDigest(), + target.ownerProofOutcome(), + target.positiveDurableAbort(), + target.ownerProofTerminalAt(), + "PLAYER_CREATED"); + } + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot currentSnapshot( GetCanonicalGameplayRosterReferenceRequest request) { var target = CanonicalGameplayRosterReferenceEvidence.target(request); @@ -2456,6 +2494,279 @@ private static CanonicalGameplayRosterRetirementAcknowledgementRequest acknowled return CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(request.build()); } + @org.junit.jupiter.api.io.TempDir Path ownerReadDirectory; + + @Test + void createdOriginalSurvivesSqlAndProductionMtlsOwnerReadAcknowledgementAndConfirmation() + throws Exception { + // Controlled historical creation and superseding source values; real GS SQL and handlers. + // This does not prove genuine source issuance, a current supersession writer or production PKI. + repository = repository(policy(1L, 1L, 1L)); + boolean maximum = Boolean.getBoolean("firemud.test.created-retirement.maximum-payload"); + boolean highEntropy = + Boolean.parseBoolean( + System.getProperty("firemud.test.created-retirement.high-entropy", "true")); + var fixture = + maximum + ? net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures + .withMaximumOpaqueProtections("gameplay", highEntropy) + : net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures + .withFiveMebibyteAccountProtection("gameplay"); + var original = fixture.originalRequest(); + var roster = CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(fixture.original()); + var selected = fixture.selected(); + assertThat(selected.getTerminal().getOriginalAccountProtection().size()) + .isEqualTo((maximum ? 40 : 5) * 1024 * 1024); + if (maximum) { + assertThat(selected.getTerminal().getAccountOriginal().getOriginalSourceReadback().size()) + .isEqualTo(32 * 1024 * 1024); + assertThat(selected.getTerminal().getOriginalGameSessionProtection().size()) + .isEqualTo(48 * 1024 * 1024); + assertThat(selected.getTerminal().getOriginalWorldProtection().size()) + .isEqualTo(48 * 1024 * 1024); + System.out.println( + "created-sql-purpose-bytes terminal=" + + selected.getTerminal().getSerializedSize() + + " selected=" + + selected.getSerializedSize() + + " original=" + + fixture.original().getSerializedSize() + + " highEntropy=" + + highEntropy); + } + var input = + net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .setSelector("1") + .setMenuSnapshotUuid(roster.getRoster().getSnapshotUuid()) + .setMenuSnapshotDigest(roster.getRoster().getSnapshotDigest()) + .build(); + + transaction.executeWithoutResult( + ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, input); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, roster); + repository.selectOriginal(original, UUID.fromString(selected.getSelectedCharacterUuid())); + repository.recordSelectedPlayerCreatedCharacter(original, selected); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); + }); + assertThat( + dsl.fetchSingle( + "SELECT canonical_player_created_roster_receipt FROM game_session_canonical_roster_selection WHERE operation_uuid = ?", + UUID.fromString(original.getOperationUuid())) + .get("canonical_player_created_roster_receipt", byte[].class)) + .containsExactly(roster.toByteArray()); + assertThat( + dsl.fetchSingle( + "SELECT canonical_selected_player_created_character_receipt FROM game_session_canonical_roster_selection WHERE operation_uuid = ?", + UUID.fromString(original.getOperationUuid())) + .get("canonical_selected_player_created_character_receipt", byte[].class)) + .containsExactly(selected.toByteArray()); + + Awaitility.await() + .atMost(java.time.Duration.ofSeconds(5)) + .untilAsserted( + () -> + assertThat( + dsl.fetchSingle( + "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() FROM game_session_canonical_roster_selection s JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) WHERE s.operation_uuid = ?", + UUID.fromString(original.getOperationUuid())) + .get(0, Boolean.class)) + .isTrue()); + + var routes = + org.mockito.Mockito.mock( + net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService.class); + var current = currentCreatedTarget(original); + org.mockito.Mockito.when( + routes.readCurrentTarget( + UUID.fromString( + CanonicalGameplayRosterReferenceEvidence.target(original).getTenantUuid()))) + .thenReturn(current); + var admissions = org.mockito.Mockito.mock(CanonicalInitialAdmissionRepository.class); + var snapshot = currentSnapshot(original); + org.mockito.Mockito.when( + admissions.readCurrentOpenSnapshotForRealm( + original.getTargetNamespace(), current.canonicalTenantId(), current.realmId())) + .thenReturn(snapshot); + org.mockito.Mockito.when(admissions.lockExactCurrentOpenSnapshot(snapshot)) + .thenReturn(snapshot); + var owner = + new net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner( + repository, + transaction, + org.mockito.Mockito.mock( + net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService + .class), + routes, + admissions, + org.mockito.Mockito.mock(CanonicalGameplayRosterRecoveryClient.class), + new SimpleMeterRegistry()); + + var pkiDirectory = java.nio.file.Files.createDirectories(ownerReadDirectory.resolve("pki")); + var pki = + net.firedevops.firemud.test.LoopbackMtlsTestPki.create( + pkiDirectory, + "Maximum created roster owner-read test CA", + new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( + "gs-server", "spiffe://firemud/ns/gameplay/sa/game-session-service", true), + new net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec( + "entity-client", + "spiffe://firemud/ns/gameplay/sa/entity-management-service", + false)); + var beans = new org.springframework.beans.factory.support.StaticListableBeanFactory(); + beans.addBean( + "source", + org.mockito.Mockito.mock( + net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService + .class)); + beans.addBean("reference", owner); + var adapter = + new net.firedevops.firemud.gamesession.service.impl + .CanonicalGameplayRosterOwnerReadGrpcAdapter( + beans.getBeanProvider( + net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService + .class), + "gameplay", + beans.getBeanProvider( + net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner + .class)); + var serverIdentity = pki.identity("gs-server"); + var server = + io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder.forAddress( + new java.net.InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES) + .sslContext( + io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts.configure( + io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.REQUIRE) + .build()) + .addService( + io.grpc.ServerInterceptors.intercept( + adapter, new net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor())) + .build() + .start(); + var endpoints = new net.firedevops.firemud.common.config.ServiceEndpointsProperties(); + endpoints.setGameSessionService("127.0.0.1:" + server.getPort()); + var client = + new net.firedevops.firemud.entitymanagement.client + .GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, + pki.clientProperties(pkiDirectory, pki.identity("entity-client")), + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + "gameplay"); + try { + client.init(); + var retained = repository.read(original); + long started = System.nanoTime(); + var transported = client.getCanonicalGameplayRosterReference(original); + if (maximum) { + System.out.println( + "created-sql-purpose-call purpose=initial-read elapsedNanos=" + + (System.nanoTime() - started) + + " requestBytes=" + + original.getSerializedSize() + + " responseBytes=" + + transported.getSerializedSize() + + " highEntropy=" + + highEntropy); + } + assertThat(transported).isEqualTo(retained); + assertThat(CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(transported)) + .isEqualTo(roster); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + transported)) + .isEqualTo(selected); + // Let the initial full-size decoded responses go before the retirement exchange. + transported = null; + retained = null; + + assertThat(owner.retireTarget(original)).isTrue(); + var retired = repository.read(original); + started = System.nanoTime(); + var retiredTransport = client.getCanonicalGameplayRosterReference(original); + if (maximum) { + System.out.println( + "created-sql-purpose-call purpose=retired-read elapsedNanos=" + + (System.nanoTime() - started) + + " requestBytes=" + + original.getSerializedSize() + + " responseBytes=" + + retiredTransport.getSerializedSize() + + " highEntropy=" + + highEntropy); + } + assertThat(retiredTransport).isEqualTo(retired); + retiredTransport = null; + assertThat( + dsl.fetchSingle( + "SELECT canonical_player_created_roster_receipt FROM game_session_canonical_roster_selection WHERE operation_uuid = ?", + UUID.fromString(original.getOperationUuid())) + .get("canonical_player_created_roster_receipt", byte[].class)) + .containsExactly(roster.toByteArray()); + assertThat( + dsl.fetchSingle( + "SELECT canonical_selected_player_created_character_receipt FROM game_session_canonical_roster_selection WHERE operation_uuid = ?", + UUID.fromString(original.getOperationUuid())) + .get("canonical_selected_player_created_character_receipt", byte[].class)) + .containsExactly(selected.toByteArray()); + + var acknowledgementRequest = + createdAcknowledgement(original, retired, UUID.randomUUID().toString()); + started = System.nanoTime(); + var acknowledgement = + client.acknowledgeCanonicalGameplayRosterRetirement(acknowledgementRequest); + if (maximum) { + System.out.println( + "created-sql-purpose-call purpose=acknowledgement elapsedNanos=" + + (System.nanoTime() - started) + + " requestBytes=" + + acknowledgementRequest.getSerializedSize() + + " responseBytes=" + + acknowledgement.getSerializedSize() + + " highEntropy=" + + highEntropy); + } + assertThat(acknowledgement) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence.response( + acknowledgementRequest, + UUID.fromString(acknowledgement.getAcknowledgementUuid()), + acknowledgement.getMinimumRetentionMillis())); + var confirmationRequest = + CanonicalGameplayRosterRetirementEvidence.confirmation( + acknowledgementRequest, acknowledgement); + started = System.nanoTime(); + var confirmation = + client.confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmationRequest); + if (maximum) { + System.out.println( + "created-sql-purpose-call purpose=confirmation elapsedNanos=" + + (System.nanoTime() - started) + + " requestBytes=" + + confirmationRequest.getSerializedSize() + + " responseBytes=" + + confirmation.getSerializedSize() + + " highEntropy=" + + highEntropy); + } + assertThat(confirmation) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmationRequest)); + assertThat(repository.read(original)).isEqualTo(retired); + } finally { + client.close(); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + @Test void createdEmptyMenuReplaysExactTypedReceiptWithoutInventingASelection() throws Exception { repository = repository(policy(60000L, 60000L, 60000L)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java index da0686a450..c20073ee5d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java @@ -178,7 +178,15 @@ void resolvedCreatedSourceRejectsMalformedDescriptorBindingAndChangedAuthoredRea try (var fixture = new Fixture()) { invalidate.accept(fixture); assertThatThrownBy(() -> fixture.service.resolvePlayerCreatedRosterSource(rosterRequest())) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo( + "Exact original public CHARACTER_CREATE source is unavailable or changed"); + }); } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java index f68e02b35b..16ba14f94c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java @@ -16,12 +16,10 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; -import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.Status; import io.grpc.StatusRuntimeException; import java.lang.reflect.Modifier; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -29,32 +27,18 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest; -import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; 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.operator.CharacterCreateOperatorActionCodec; -import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; -import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; -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.CanonicalGameplayRosterResponse; 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.CanonicalPlayerCreatedRosterRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; -import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; -import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; -import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; -import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource; import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient; import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient.VerifiedPlayerCreatedCharacter; @@ -63,6 +47,7 @@ import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository.SelectionOutcome; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner; import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.testing.ControlledPlayerCreatedRosterValues; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; @@ -597,155 +582,14 @@ private record Fixture( CanonicalSelectedPlayerCreatedCharacterResponse selected) {} private static Fixture fixture() throws Exception { - Path root = Path.of("").toAbsolutePath(); - while (root != null && !Files.exists(root.resolve("settings.gradle.kts"))) - root = root.getParent(); - if (root == null) - throw new IllegalStateException("Controlled CHARACTER_CREATE fixture unavailable"); - byte[] bytes = - Files.readString( - root.resolve( - "services/account-service/src/testFixtures/resources/charactercreate/public-action.json")) - .strip() - .getBytes(StandardCharsets.UTF_8); - var action = CharacterCreateOperatorActionCodec.decode(bytes); - var authored = action.mutation().authoredSource(); - var descriptor = PlayerCreationDescriptor.parse(authored.descriptor().canonicalJson()); - var source = - CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() - .setSchemaVersion(1) - .setDescriptorUuid(descriptor.descriptorId()) - .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) - .setDescriptorDigest(descriptor.digest()) - .setAuthoredBindingUuid(authored.bindingId()) - .setAuthoredBindingDigest(authored.bindingDigest()) - .build(); - var target = - CanonicalGameplayRosterTarget.newBuilder() - .setTenantUuid(action.scope().tenantId()) - .setRealmUuid(action.target().realmId()) - .setWorldSlug(action.target().worldSlug()) - .setRealmSlug(action.target().realmSlug()) - .setGameInstanceUuid(action.target().gameInstanceId()) - .setCanonicalVersionUuid(action.target().versionId()) - .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setEntryPolicy( - CanonicalGameplayRosterEntryPolicy.CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) - .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) - .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) - .setActiveWorldEpoch(Long.parseLong(action.expectedVersion().activeLifecycleEpoch())) - .setPublishedPolicyDigest(authored.policy().contentDigest().substring(7)) - .setPublishedReleaseBundleRef("controlled-created-release") - .setAdmissionPointerSnapshotDigest("b".repeat(64)) - .setPublishedOwnerProofDigest("c".repeat(64)) - .build(); - var context = - PlayerExecutionContext.newBuilder() - .setRequestId(UUID.randomUUID().toString()) - .setSessionId(UUID.randomUUID().toString()) - .setAccountId(action.target().accountId()) - .setTenantId(target.getTenantUuid()) - .setRealmId(target.getRealmUuid()) - .setGameInstanceId(target.getGameInstanceUuid()) - .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) - .setPlayableStateScope("SHARED") - .build(); - var original = - CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( - UUID.fromString(context.getRequestId()), - UUID.fromString(context.getAccountId()), - UUID.fromString(context.getSessionId()), - action.scope().targetNamespace(), - target, - source); - String character = UUID.randomUUID().toString(); - var actors = - List.of( - CanonicalGameplayRosterActor.newBuilder() - .setCharacterUuid(character) - .setDisplayName("Controlled persisted actor") - .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) - .build()); - String snapshot = UUID.randomUUID().toString(); - String digest = - CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( - context.getAccountId(), target, source, actors); - var roster = - CanonicalPlayerCreatedRosterResponse.newBuilder() - .setSourceIdentity(source) - .setRoster( - CanonicalGameplayRosterResponse.newBuilder() - .setCanonicalAccountUuid(context.getAccountId()) - .setTarget(target) - .setSnapshotUuid(snapshot) - .setSnapshotDigest(digest) - .addAllActors(actors)) - .build(); - String operation = UUID.randomUUID().toString(); - String mutation = CharacterCreateOperatorActionCodec.mutationDigest(action); - var accountRequest = - ReadOriginalCharacterCreateRequest.newBuilder() - .setTargetNamespace(action.scope().targetNamespace()) - .setOperationId(operation) - .setMutationDigest(mutation) - .build(); - var account = - ReadOriginalCharacterCreateResponse.newBuilder() - .setTargetNamespace(action.scope().targetNamespace()) - .setOperationId(operation) - .setMutationDigest(mutation) - .setCreateCharacterRequestId(UUID.randomUUID().toString()) - .setConnectScopeId("controlled-create-scope") - .setAuthenticatedAccountId(action.target().accountId()) - .setPurpose("CHARACTER_CREATE") - .setOriginalAction(ByteString.copyFrom(bytes)) - .setOriginalSourceReadback(ByteString.copyFromUtf8("controlled-source-readback")) - .build(); - var protection = - CharacterCreateProtectionReference.newBuilder() - .setProtectionId(UUID.randomUUID().toString()) - .setProtectionFence(1) - .build(); - var terminal = - EntityCharacterCreateTerminal.newBuilder() - .setOriginalRequest( - CommitProtectedCharacterCreateRequest.newBuilder() - .setOriginal(accountRequest) - .setAccountProtection(protection) - .setGameSessionProtection( - protection.toBuilder().setProtectionId(UUID.randomUUID().toString())) - .setWorldProtection( - protection.toBuilder().setProtectionId(UUID.randomUUID().toString()))) - .setAccountOriginal(account) - .setOriginalAccountProtection(ByteString.copyFromUtf8("controlled-account-protection")) - .setOriginalGameSessionProtection( - ByteString.copyFromUtf8("controlled-game-session-protection")) - .setOriginalWorldProtection(ByteString.copyFromUtf8("controlled-world-protection")) - .setEntityIntakeRequestId(UUID.randomUUID().toString()) - .setOutcome(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) - .setCharacterId(character) - .setTerminalId(UUID.randomUUID().toString()) - .setTerminalFence(1) - .setCompletedAt("2026-10-23T00:00:00Z") - .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)) - .build(); - var selected = - CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() - .setRequestUuid(context.getRequestId()) - .setCanonicalAccountUuid(context.getAccountId()) - .setSelectedCharacterUuid(character) - .setTarget(target) - .setSourceIdentity(source) - .setSnapshot( - CanonicalGameplayRosterSnapshotReference.newBuilder() - .setSnapshotUuid(snapshot) - .setSnapshotDigest(digest)) - .setCreationOperationUuid(operation) - .setMutationDigest(mutation) - .setTerminal(terminal) - .build(); + var values = ControlledPlayerCreatedRosterValues.forClient(); return new Fixture( - action.scope().targetNamespace(), target, source, context, original, roster, selected); + values.namespace(), + values.target(), + values.source(), + values.context(), + values.original(), + values.roster(), + values.selected().values().iterator().next()); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java index 4b70462437..fba42d6c7f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java @@ -1,4 +1,4 @@ -package net.firedevops.firemud.gamesession.service; +package unit.net.firedevops.firemud.gamesession.service; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -35,6 +35,9 @@ import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository.CurrentOpenSnapshot; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterReferenceState; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; 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 788dc99d65..c97573d36b 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 @@ -32,8 +32,6 @@ import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; -import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; -import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterRequest; @@ -42,10 +40,6 @@ 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.CanonicalPlayerCreatedRosterResponse; -import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; -import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; -import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateTerminal; import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService; import net.firedevops.firemud.gamesession.charactercreate.GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; @@ -68,6 +62,7 @@ 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.gamesession.testing.ControlledPlayerCreatedRosterValues; import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import org.junit.jupiter.api.Test; @@ -1114,59 +1109,17 @@ void createdContextAndAmbientSqlRefuseBeforeSourceAndTerminalWriteFailureStaysCl // genuine source issuance or SQL. The complete terminal values use the existing controlled // CHARACTER_CREATE vector; actual Common/client grammar and physical owner proofs are separate. private static CreatedHarness createdHarness(int actorCount) throws Exception { - java.nio.file.Path root = java.nio.file.Path.of("").toAbsolutePath(); - while (root != null && !java.nio.file.Files.exists(root.resolve("settings.gradle.kts"))) - root = root.getParent(); - if (root == null) - throw new IllegalStateException("Controlled CHARACTER_CREATE fixture unavailable"); - byte[] bytes = - java.nio.file.Files.readString( - root.resolve( - "services/account-service/src/testFixtures/resources/charactercreate/public-action.json")) - .strip() - .getBytes(java.nio.charset.StandardCharsets.UTF_8); - var action = - net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec.decode(bytes); - var authored = action.mutation().authoredSource(); - var descriptor = - net.firedevops.firemud.common.publication.PlayerCreationDescriptor.parse( - authored.descriptor().canonicalJson()); - var identity = - CanonicalPlayerCreatedRosterSourceIdentity.newBuilder() - .setSchemaVersion(1) - .setDescriptorUuid(descriptor.descriptorId()) - .setDescriptorRevisionUuid(descriptor.descriptorRevisionId()) - .setDescriptorDigest(descriptor.digest()) - .setAuthoredBindingUuid(authored.bindingId()) - .setAuthoredBindingDigest(authored.bindingDigest()) - .build(); - var target = - CanonicalGameplayRosterTarget.newBuilder() - .setTenantUuid(action.scope().tenantId()) - .setRealmUuid(action.target().realmId()) - .setWorldSlug(action.target().worldSlug()) - .setRealmSlug(action.target().realmSlug()) - .setGameInstanceUuid(action.target().gameInstanceId()) - .setCanonicalVersionUuid(action.target().versionId()) - .setPlayableStateNamespaceUuid(action.scope().playableStateNamespaceId()) - .setPlayableStateScope( - net.firedevops.firemud.entitymanagement.v1.PlayableStateScope - .PLAYABLE_STATE_SCOPE_SHARED) - .setEntryPolicy( - net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterEntryPolicy - .CANONICAL_ROSTER_ENTRY_POLICY_PLAYER_CREATED) - .setCatalogRevision(Long.parseLong(action.expectedVersion().catalogRevision())) - .setPointerVersion(Long.parseLong(action.expectedVersion().pointerVersion())) - .setActiveWorldEpoch(Long.parseLong(action.expectedVersion().activeLifecycleEpoch())) - .setPublishedPolicyDigest(authored.policy().contentDigest().substring(7)) - .setPublishedReleaseBundleRef("controlled-created-release") - .setAdmissionPointerSnapshotDigest("b".repeat(64)) - .setPublishedOwnerProofDigest("c".repeat(64)) - .build(); + var values = + ControlledPlayerCreatedRosterValues.forSelection( + actorCount, SNAPSHOT, FIRST_ACTOR, SECOND_ACTOR); + var target = values.target(); + var identity = values.source(); + var actors = values.actors(); + String digest = values.roster().getRoster().getSnapshotDigest(); var r = PublishedRealmPolicyEvidenceFixture.canonicalPublishedRoute().route(); var route = new CanonicalPlayableTarget( - action.scope().targetNamespace(), + values.namespace(), r.tenantSlug(), UUID.fromString(target.getTenantUuid()), target.getWorldSlug(), @@ -1199,146 +1152,38 @@ private static CreatedHarness createdHarness(int actorCount) throws Exception { r.ownerProofTerminalAt(), "PLAYER_CREATED"); var context = - context(route, UUID.randomUUID().toString()).toBuilder() - .setAccountId(action.target().accountId()) + context(route, values.context().getRequestId()).toBuilder() + .setAccountId(values.context().getAccountId()) + .setSessionId(values.context().getSessionId()) .build(); var source = mock(ResolvedPlayerCreatedRosterSource.class); when(source.route()).thenReturn(route); when(source.target()).thenReturn(target); when(source.sourceIdentity()).thenReturn(identity); - var actors = - java.util.stream.IntStream.range(0, actorCount) - .mapToObj( - i -> - CanonicalGameplayRosterActor.newBuilder() - .setCharacterUuid((i == 0 ? FIRST_ACTOR : SECOND_ACTOR).toString()) - .setDisplayName(i == 0 ? "Created One" : "Created Two") - .setActorKind( - CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) - .build()) - .toList(); - String digest = - CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( - context.getAccountId(), target, identity, actors); - var receipt = - CanonicalPlayerCreatedRosterResponse.newBuilder() - .setSourceIdentity(identity) - .setRoster( - CanonicalGameplayRosterResponse.newBuilder() - .setCanonicalAccountUuid(context.getAccountId()) - .setTarget(target) - .setSnapshotUuid(SNAPSHOT.toString()) - .setSnapshotDigest(digest) - .addAllActors(actors)) - .build(); var roster = mock(VerifiedPlayerCreatedRoster.class); - when(roster.response()).thenReturn(receipt); + when(roster.response()).thenReturn(values.roster()); when(roster.resolvedSource()).thenReturn(source); - when(roster.originalSelection()) - .thenReturn( - CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( - UUID.fromString(context.getRequestId()), - UUID.fromString(context.getAccountId()), - UUID.fromString(context.getSessionId()), - route.targetNamespace(), - target, - identity)); + when(roster.originalSelection()).thenReturn(values.original()); when(roster.canonicalAccountUuid()).thenReturn(UUID.fromString(context.getAccountId())); when(roster.target()).thenReturn(target); when(roster.sourceIdentity()).thenReturn(identity); - when(roster.snapshotUuid()).thenReturn(SNAPSHOT); + when(roster.snapshotUuid()) + .thenReturn(UUID.fromString(values.roster().getRoster().getSnapshotUuid())); when(roster.snapshotDigest()).thenReturn(digest); when(roster.actors()).thenReturn(actors); - String operation = UUID.randomUUID().toString(); - String mutation = - net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec.mutationDigest( - action); - var original = - net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateRequest.newBuilder() - .setTargetNamespace(route.targetNamespace()) - .setOperationId(operation) - .setMutationDigest(mutation) - .build(); - var account = - net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse.newBuilder() - .setTargetNamespace(route.targetNamespace()) - .setOperationId(operation) - .setMutationDigest(mutation) - .setCreateCharacterRequestId(UUID.randomUUID().toString()) - .setConnectScopeId("controlled-created-scope") - .setAuthenticatedAccountId(context.getAccountId()) - .setPurpose("CHARACTER_CREATE") - .setOriginalAction(com.google.protobuf.ByteString.copyFrom(bytes)) - .setOriginalSourceReadback( - com.google.protobuf.ByteString.copyFromUtf8("controlled-source-readback")) - .build(); - var protection = - net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference.newBuilder() - .setProtectionId(UUID.randomUUID().toString()) - .setProtectionFence(1) - .build(); - var terminal = - EntityCharacterCreateTerminal.newBuilder() - .setOriginalRequest( - net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest - .newBuilder() - .setOriginal(original) - .setAccountProtection(protection) - .setGameSessionProtection( - protection.toBuilder().setProtectionId(UUID.randomUUID().toString())) - .setWorldProtection( - protection.toBuilder().setProtectionId(UUID.randomUUID().toString()))) - .setAccountOriginal(account) - .setOriginalAccountProtection( - com.google.protobuf.ByteString.copyFromUtf8("controlled-account-protection")) - .setOriginalGameSessionProtection( - com.google.protobuf.ByteString.copyFromUtf8("controlled-game-session-protection")) - .setOriginalWorldProtection( - com.google.protobuf.ByteString.copyFromUtf8("controlled-world-protection")) - .setEntityIntakeRequestId(UUID.randomUUID().toString()) - .setOutcome( - net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome - .ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) - .setTerminalId(UUID.randomUUID().toString()) - .setTerminalFence(1) - .setCompletedAt("2026-10-23T00:00:00Z") - .setEntitySourceReceiptDigest("sha256:" + "d".repeat(64)); var references = new java.util.HashMap(); for (var actor : actors) { - String actorOperation = UUID.randomUUID().toString(); - var actorTerminal = - terminal - .clone() - .setCharacterId(actor.getCharacterUuid()) - .setTerminalId(UUID.randomUUID().toString()) - .setOriginalRequest( - terminal.getOriginalRequest().toBuilder() - .setOriginal(original.toBuilder().setOperationId(actorOperation))) - .setAccountOriginal(account.toBuilder().setOperationId(actorOperation)); - var response = - CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() - .setRequestUuid(context.getRequestId()) - .setCanonicalAccountUuid(context.getAccountId()) - .setSelectedCharacterUuid(actor.getCharacterUuid()) - .setTarget(target) - .setSourceIdentity(identity) - .setSnapshot( - net.firedevops.firemud.entitymanagement.v1 - .CanonicalGameplayRosterSnapshotReference.newBuilder() - .setSnapshotUuid(SNAPSHOT.toString()) - .setSnapshotDigest(digest)) - .setCreationOperationUuid(actorOperation) - .setMutationDigest(mutation) - .setTerminal(actorTerminal) - .build(); + UUID actorUuid = UUID.fromString(actor.getCharacterUuid()); + var response = values.selected().get(actorUuid); var verified = mock(VerifiedPlayerCreatedCharacter.class); when(verified.roster()).thenReturn(roster); when(verified.response()).thenReturn(response); - when(verified.selectedCharacterUuid()).thenReturn(UUID.fromString(actor.getCharacterUuid())); - when(verified.creationOperationUuid()).thenReturn(UUID.fromString(actorOperation)); - when(verified.mutationDigest()).thenReturn(mutation); + when(verified.selectedCharacterUuid()).thenReturn(actorUuid); + when(verified.creationOperationUuid()) + .thenReturn(UUID.fromString(response.getCreationOperationUuid())); + when(verified.mutationDigest()).thenReturn(response.getMutationDigest()); when(verified.terminal()).thenReturn(response.getTerminal()); - references.put(UUID.fromString(actor.getCharacterUuid()), verified); + references.put(actorUuid, verified); } var routes = mock(CanonicalPlayerRouteReadService.class); var publications = mock(CanonicalPublishedPlayerRouteReadService.class); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedRosterValues.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedRosterValues.java new file mode 100644 index 0000000000..e4198492f1 --- /dev/null +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedRosterValues.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.gamesession.testing; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.testing.ControlledPlayerCreatedRosterTerminalFixtures; +import net.firedevops.firemud.common.world.CanonicalPlayerCreatedRosterEvidence; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterSnapshotReference; +import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; +import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterSourceIdentity; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterRequest; +import net.firedevops.firemud.entitymanagement.v1.CanonicalSelectedPlayerCreatedCharacterResponse; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Shared controlled created-roster values for Game Session unit compositions only. */ +public final class ControlledPlayerCreatedRosterValues { + private static final String TEST_NAMESPACE = "firemud"; + + private ControlledPlayerCreatedRosterValues() {} + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = "Test protobuf values are immutable and collection inputs are copied.") + public record Values( + String namespace, + CanonicalGameplayRosterTarget target, + CanonicalPlayerCreatedRosterSourceIdentity source, + PlayerExecutionContext context, + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original, + CanonicalPlayerCreatedRosterResponse roster, + List actors, + Map selected) { + public Values { + actors = List.copyOf(actors); + selected = Map.copyOf(selected); + } + } + + /** Uses the shared Common codec vector without changing its complete original terminal. */ + public static Values forClient() { + var bundle = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection( + TEST_NAMESPACE); + var original = bundle.originalRequest(); + var target = target(original); + var source = source(original); + var context = context(original, target); + CanonicalPlayerCreatedRosterResponse roster; + try { + roster = + CanonicalPlayerCreatedRosterResponse.parseFrom( + bundle.original().getCanonicalPlayerCreatedRosterReceipt()); + } catch (com.google.protobuf.InvalidProtocolBufferException invalid) { + throw new IllegalStateException("Controlled created roster vector is invalid", invalid); + } + UUID selectedActor = UUID.fromString(bundle.selected().getSelectedCharacterUuid()); + return new Values( + original.getTargetNamespace(), + target, + source, + context, + original, + roster, + roster.getRoster().getActorsList(), + Map.of(selectedActor, bundle.selected())); + } + + /** + * Builds the variable-size selection menu around the same Common action, source and complete + * terminal vector, then validates each selected receipt with the production evidence codec. + */ + public static Values forSelection( + int actorCount, UUID snapshotUuid, UUID firstActor, UUID secondActor) { + if (actorCount < 0 || actorCount > 2) { + throw new IllegalArgumentException("Controlled selection vector supports zero to two actors"); + } + var bundle = + ControlledPlayerCreatedRosterTerminalFixtures.withFiveMebibyteAccountProtection( + TEST_NAMESPACE); + var original = bundle.originalRequest(); + var target = target(original); + var source = source(original); + var context = context(original, target); + var actors = new ArrayList(); + if (actorCount >= 1) actors.add(actor(firstActor, "Created One")); + if (actorCount == 2) actors.add(actor(secondActor, "Created Two")); + String digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + original.getCanonicalAccountUuid(), target, source, actors); + var rosterRequest = + CanonicalPlayerCreatedRosterRequest.newBuilder() + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setExpectedTarget(target) + .setExpectedSource(source) + .setPlayerExecutionContext(context) + .build(); + var roster = + CanonicalPlayerCreatedRosterEvidence.requireResponse( + rosterRequest, + CanonicalPlayerCreatedRosterResponse.newBuilder() + .setSourceIdentity(source) + .setRoster( + CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setTarget(target) + .setSnapshotUuid(snapshotUuid.toString()) + .setSnapshotDigest(digest) + .addAllActors(actors)) + .build()); + var snapshot = + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(snapshotUuid.toString()) + .setSnapshotDigest(digest) + .build(); + var selected = new LinkedHashMap(); + for (var actor : actors) { + UUID actorUuid = UUID.fromString(actor.getCharacterUuid()); + var request = + CanonicalSelectedPlayerCreatedCharacterRequest.newBuilder() + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(actorUuid.toString()) + .setExpectedTarget(target) + .setExpectedSource(source) + .setExpectedSnapshot(snapshot) + .setPlayerExecutionContext(context.toBuilder().setCharacterId(actorUuid.toString())) + .build(); + String creationOperation = UUID.randomUUID().toString(); + var template = bundle.selected().getTerminal(); + var terminal = + template.toBuilder() + .setCharacterId(actorUuid.toString()) + .setTerminalId(UUID.randomUUID().toString()) + .setEntityIntakeRequestId(UUID.randomUUID().toString()) + .setOriginalRequest( + template.getOriginalRequest().toBuilder() + .setOriginal( + template.getOriginalRequest().getOriginal().toBuilder() + .setOperationId(creationOperation))) + .setAccountOriginal( + template.getAccountOriginal().toBuilder().setOperationId(creationOperation)); + var response = + bundle.selected().toBuilder() + .setCreationOperationUuid(creationOperation) + .setRequestUuid(original.getOperationUuid()) + .setCanonicalAccountUuid(original.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(actorUuid.toString()) + .setTarget(target) + .setSnapshot(snapshot) + .setSourceIdentity(source) + .setTerminal(terminal) + .build(); + selected.put( + actorUuid, + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, response)); + } + return new Values( + original.getTargetNamespace(), target, source, context, original, roster, actors, selected); + } + + private static CanonicalGameplayRosterTarget target( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original) { + try { + return CanonicalGameplayRosterTarget.parseFrom(original.getCanonicalTarget()); + } catch (com.google.protobuf.InvalidProtocolBufferException invalid) { + throw new IllegalStateException("Controlled created target vector is invalid", invalid); + } + } + + private static CanonicalPlayerCreatedRosterSourceIdentity source( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original) { + try { + return CanonicalPlayerCreatedRosterSourceIdentity.parseFrom( + original.getCanonicalPlayerCreatedSourceIdentity()); + } catch (com.google.protobuf.InvalidProtocolBufferException invalid) { + throw new IllegalStateException("Controlled created source vector is invalid", invalid); + } + } + + private static PlayerExecutionContext context( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original, + CanonicalGameplayRosterTarget target) { + return PlayerExecutionContext.newBuilder() + .setRequestId(original.getOperationUuid()) + .setAccountId(original.getCanonicalAccountUuid()) + .setSessionId(original.getSessionUuid()) + .setTenantId(target.getTenantUuid()) + .setRealmId(target.getRealmUuid()) + .setGameInstanceId(target.getGameInstanceUuid()) + .setPlayableStateNamespaceId(target.getPlayableStateNamespaceUuid()) + .setPlayableStateScope("SHARED") + .build(); + } + + private static CanonicalGameplayRosterActor actor(UUID uuid, String name) { + return CanonicalGameplayRosterActor.newBuilder() + .setCharacterUuid(uuid.toString()) + .setDisplayName(name) + .setActorKind(CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER) + .build(); + } +} From 99068ed44d706c9fb14bc75248a6c035e98de945 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 07:00:35 +1300 Subject: [PATCH 17/22] Record qualified created roster correction and fresh image proof --- .../gameplay-rules-entities-and-effects.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index a21cda37e0..edf6e95330 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -16,6 +16,8 @@ The next review correction counts typed snapshot recognition as classification p The large-payload qualification fills the four existing opaque limits (168 MiB total) and maximizes the supported feedback field in one valid canonical action family. R249 reproduces the five-second acknowledgement deadline failure through actual Game Session PostgreSQL storage, the durable owner and authenticated adapter, and the production Entity client. R251 then passes the initial and retired reads, acknowledgement, confirmation and exact retained-value assertions with a ten-second created-purpose RPC budget. Actual API times are 3.208, 3.062, 10.354 and 8.784 seconds respectively; API timing includes validation outside the RPC deadline. Original responses are 177,563,987 and 177,564,163 bytes, the acknowledgement request is 177,565,210 bytes and confirmation is 177,565,366 bytes. The independent 192–195 MiB envelopes are not claimed to be reachable maxima. R250's earlier combined run ended with exit 137; kernel evidence records a global Java OOM kill, without establishing a precise process attribution. The successful isolated R251 reduces temporary test copies and uses a private 3 GiB test heap, which is qualification headroom rather than a production recommendation. Controlled historical creation, superseding route/admission values and test PKI do not establish genuine source issuance, the current supersession writer, production latency or capacity, registration, admission or activation. +R252 passes the remaining affected Common, Entity and Game Session formatting/static checks, the new SQL/mTLS case at its ordinary 5 MiB size, and documentation validation. Its new shared value fixture initially triggers immutable-protobuf accessor warnings; R255 passes the scoped fixture checks after retaining only the justified immutable-accessor suppression. Fresh Entity and Game Session images at code checkpoint `d92b28bbc7faf4292b7bc21d5e7c56e0658da4b6` pass R254 held Gateway/Telnet denial and the isolated backend WebSocket WORLDS, LOGIN, PLAY and LOOK baseline. Authenticated teardown succeeds, and independent exact-project checks confirm zero containers, networks and volumes. This qualifies packaging and the controlled baseline while the genuine admission and activation limits remain open. + Earlier parent qualification receives #3295 at `cc33169ca1354872e101c4ef42777b0e79032473`, including its complete release/World validation correction. R116 passes the full Game Session check, formatting and affected static analysis with 2,568 unit cases, 365 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. This includes the actual initial owner-to-owner composition, which freshly passes in 30.763 seconds. The tested postimages are retained at `c9774094d76097ade5dcc5530d346e4960e613d8` after canonical fixture formatting. Unchanged Entity production source retains R113’s 402 unit and 94 PostgreSQL executions; R116 also passes both affected fixture static checks after correcting the earlier fixture-only SpotBugs failures. R117 freshly rebuilds that checkpoint and passes held Gateway/Telnet denial and isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK`, followed by authenticated teardown and independently confirmed exact-project container, network and volume absence. Prior component qualification R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases with affected static analysis, formatting and documentation checks. Unchanged Common and broader Game Session physical proof retain R86 attribution: 1,020 Common unit cases, 364 Game Session PostgreSQL cases and 36 cross-service cases. R86's earlier 396 Entity and 2,565 Game Session unit counts are superseded by the new executions, rather than credited as fresh runs. Native Entity proof includes the actual retained creation writer feeding authenticated source-bound snapshot capture; socket fixtures use controlled PKI and owner facts, including a complete 5 MiB terminal rather than physical proof at every maximum purpose bound. After the documentation-only parent carry, R93 rebuilds fresh images at `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project inspection confirms no remaining containers, networks or volumes. The documentation-only carry through parent `2aa25d9327bd9c15698c69168f2c96254f0fa732` preserves that code; the later release/World correction is qualified by R116 and R117 above. This validates controlled components, storage, packaging and the isolated backend baseline; it does not exercise a registered production created-actor flow. From f8567ea7cbb585b0a536cf185d6924c1b30d6737 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:35:59 +1300 Subject: [PATCH 18/22] Guard production created-roster request bytes and qualify complete owner flows --- .../runtime-and-data.md | 2 +- .../game-session-service/api-contracts.md | 4 +- .../game-session-service/runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 12 +- ...monGrpcRequestBoundsAutoConfiguration.java | 150 ++++ .../grpc/BoundedGrpcRequestMarshaller.java | 176 +++++ .../common/grpc/BoundedGrpcServerFactory.java | 87 +++ .../common/grpc/GrpcRequestBytePolicy.java | 102 +++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + .../BoundedGrpcRequestMarshallerTest.java | 356 +++++++++ .../grpc/BoundedGrpcServerFactoryTest.java | 249 +++++++ ...rpcRequestBoundsAutoConfigurationTest.java | 293 ++++++++ .../firemud/test/LoopbackMtlsTestPki.java | 31 + .../EntityCharacterCreateRepository.java | 9 +- ...icalGameplayRosterRetentionRepository.java | 48 +- ...racter_create_binary_safe_immutability.sql | 18 + ...eseededActorAssignmentIntegrationTest.java | 5 +- .../RetainedActorIdentityIntegrationTest.java | 14 +- ...haracterCreatePostgresIntegrationTest.java | 67 +- ...osterRetentionPostgresIntegrationTest.java | 34 + ...ntakeMigrationPostgresIntegrationTest.java | 2 +- ...trolledPlayerCreatedOwnerStoreFixture.java | 45 +- .../game-session-service/build.gradle.kts | 1 + .../CanonicalPlayerCreatedRosterClient.java | 6 +- ...meSessionGrpcRequestByteConfiguration.java | 25 + ...ical_roster_binary_safe_recovery_guard.sql | 109 +++ ...GameSessionApplicationIntegrationTest.java | 1 + ...RosterOwnerCompositionIntegrationTest.java | 702 +++++++++++++++--- ...osterReferencePostgresIntegrationTest.java | 71 +- ...rationOrderingPostgresIntegrationTest.java | 6 + ...unchRepositoryPostgresIntegrationTest.java | 7 + ...RegionStatusRepositoryIntegrationTest.java | 3 + ...unchPreparationServiceIntegrationTest.java | 7 + ...anonicalPlayerCreatedRosterClientTest.java | 4 +- ...ssionGrpcRequestByteConfigurationTest.java | 334 +++++++++ .../gamesession/CrossServiceAppHarness.java | 11 +- ...lledPlayerCreatedOriginalOwnerFixture.java | 39 +- 37 files changed, 2842 insertions(+), 191 deletions(-) create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshaller.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactory.java create mode 100644 services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcRequestBytePolicy.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshallerTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java create mode 100644 services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java create mode 100644 services/entity-management-service/src/main/resources/db/migration/V1021__character_create_binary_safe_immutability.sql create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfiguration.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1022__canonical_roster_binary_safe_recovery_guard.sql create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 3911522f5a..869dc4025a 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -344,7 +344,7 @@ The configured cadence and batch bound limit each owner-local sweep. Its bounded #### Player-created snapshot storage -Forward `V1016__player_created_roster_snapshot_receipts.sql` extends the existing sealed-roster family after Entity creation V1015. A `PLAYER_CREATED` snapshot requires `SHARED` scope and immutable canonical `canonical_player_created_source_identity` bytes; preseeded snapshots keep that column null. Immutable entry-policy metadata selects the applicable admission, original receipt, lifecycle-proof and outbox branch. The created original receipt is distinct and mutually exclusive with the preseeded receipt. Prior preseeded digest/history, provenance, immutability, reference/hold, epoch, conditional-disposal and late-nonce guards remain effective. Created receipt/proof/ACK storage uses its explicit purpose budgets, including the complete selected terminal in retirement evidence, while existing preseeded caps remain unchanged. The [Entity API owner](./api-contracts.md#player-created-roster-and-selected-character) defines the wire identities and bounds. Entity's original-reference, retirement acknowledgement and confirmation client calls use a finite ten-second RPC deadline for validated `PLAYER_CREATED` targets; preseeded calls and generic owner reads retain five seconds. These deadlines cover the RPC itself, with request prevalidation and response validation performed separately. +Forward `V1021__character_create_binary_safe_immutability.sql` preserves the existing creation intent and terminal transition with an exact typed-row comparison, avoiding JSON materialization of large binary terminal/proof columns. Published creation V1015 remains unchanged. Forward `V1016__player_created_roster_snapshot_receipts.sql` extends the existing sealed-roster family after Entity creation V1015. A `PLAYER_CREATED` snapshot requires `SHARED` scope and immutable canonical `canonical_player_created_source_identity` bytes; preseeded snapshots keep that column null. Immutable entry-policy metadata selects the applicable admission, original receipt, lifecycle-proof and outbox branch. The created original receipt is distinct and mutually exclusive with the preseeded receipt. Prior preseeded digest/history, provenance, immutability, reference/hold, epoch, conditional-disposal and late-nonce guards remain effective. Created receipt/proof/ACK storage uses its explicit purpose budgets, including the complete selected terminal in retirement evidence, while existing preseeded caps remain unchanged. The [Entity API owner](./api-contracts.md#player-created-roster-and-selected-character) defines the wire identities and bounds. Entity's original-reference, retirement acknowledgement and confirmation client calls use a finite ten-second RPC deadline for validated `PLAYER_CREATED` targets; preseeded calls and generic owner reads retain five seconds. These deadlines cover the RPC itself, with request prevalidation and response validation performed separately. Forward `V1020__canonical_roster_created_retirement_recognition.sql` extends retained target classification and snapshot inventory with additive typed recognition. A created retirement target binds the canonical account, complete target and complete canonical created-source identity; preseeded target bytes remain unchanged. Bounded initialization adds version-two metadata against exact immutable source bytes and positive retirement proof without replacing the original classification, snapshot, transfer or seal rows. The effective metadata view requires the applicable actual source family and exact retained evidence; a version marker alone grants no authority. A valid typed classification can qualify an earlier unrecognized created source, while malformed or uninitialized retained evidence keeps the roster boundary protected. Legacy seals whose stored target omits the created source stay protected rather than being rewritten. Created siblings use the same shared acquisition fence and independent per-snapshot preparation, holds, horizons and disposal checks described in [sealed roster retention](#sealed-canonical-roster-retention). diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 2707b95cc2..b099437791 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -106,9 +106,9 @@ Entity durably records that authenticated response before confirming delivery. C #### Player-created original roster consequences -Game Session consumes Entity's distinct [player-created roster and selected-character contract](../entity-management-service/api-contracts.md#player-created-roster-and-selected-character) only after independently resolving the current published `PLAYER_CREATED` source and matching the complete route, policy, descriptor and source identity. It retains the exact typed created-roster and selected-character receipts on the original operation, preserves the original menu and ordinal/frozen actor choice, and revalidates the current route around owner reads. These receipts provide no membership, session-binding or gameplay-admission authority. The existing preseeded route remains a separate strict branch; a Common parser validates values without establishing authenticated custody. +Game Session consumes Entity's distinct [player-created roster and selected-character contract](../entity-management-service/api-contracts.md#player-created-roster-and-selected-character) only after independently resolving the current published `PLAYER_CREATED` source and matching the complete route, policy, descriptor and source identity. It retains the exact typed created-roster and selected-character receipts on the original operation, preserves the original menu and ordinal/frozen actor choice, and revalidates the current route around owner reads. Original-operation reservation, returned-roster qualification and selected-reference qualification require independent current published-source observations, including their Game Design, World and published-policy evidence. An earlier observation cannot be cached across those authority boundaries to remove their freshness checks. These receipts provide no membership, session-binding or gameplay-admission authority. The two created roster and selected-character client RPCs use a finite twenty-second outer deadline so the nested five-second current-source and ten-second original-owner calls retain their bounded budgets under the inherited gRPC context. Request and response validation outside those calls remains part of the caller operation; this deadline is not a production latency guarantee. The existing preseeded route remains a separate strict branch; a Common parser validates values without establishing authenticated custody. -The created reference response retains the complete selected payload within its 194 MiB purpose envelope, and retirement-observation requests retain it within the 195 MiB created-ACK envelope with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within its existing recovery purpose bound. These purpose-specific limits preserve complete owner bytes and the existing preseeded limits; they do not raise a global gRPC limit. The corresponding local storage consequences belong to [Runtime and Data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership). +The created reference response retains the complete selected payload within its 194 MiB purpose envelope, and retirement-observation requests retain it within the 195 MiB created-ACK envelope with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within its existing recovery purpose bound. These purpose-specific limits preserve complete owner bytes and the existing preseeded bounds. The shared server transport has one finite deframing ceiling large enough for the existing created-retirement confirmation envelope. Mandatory request marshalling at the canonical server-registration boundary checks the raw uncompressed request length before invoking any protobuf parser: only the exact generated acknowledgement and confirmation method descriptors receive their existing purpose bounds; every other method, including future or unlisted methods, retains the 4 MiB default or a smaller owning bound. Caller metadata cannot select a larger budget. Missing or duplicate admission configuration and unwrapped service registration fail closed. Semantic policy bounds, response bounds and workload authentication remain independent checks. The shared transport can buffer more than 4 MiB before method admission rejects a request; this mechanism does not establish a 4 MiB network-memory ceiling or production capacity. The corresponding local storage consequences belong to [Runtime and Data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership). #### Canonical gameplay roster owner read 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 e0fc17de6f..abf6feeb63 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -85,7 +85,7 @@ Compact transfer receipts survive original removal and remain protected until En #### Player-created original roster storage -The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. The original-reference response preserves the complete selected payload within its 194 MiB purpose bound; retirement observation preserves it within the 195 MiB created-ACK bound with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within the existing recovery bound. These purpose-specific byte limits preserve owner bytes and preseeded limits; they do not widen global gRPC defaults. Current implementation and migration qualification are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) and [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). +The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. Forward V1022 preserves the recovery-attempt timestamp transition with an exact typed-row comparison, so checking unchanged selected receipts does not convert large binary values to JSON; published V1020 and V1021 remain unchanged. Original-reference and retirement storage preserve the complete selected payload without truncation. Recovery retains the exact typed created-roster receipt independently of the selected terminal, while the existing preseeded storage branch remains unchanged. The [API contract](./api-contracts.md#player-created-original-roster-consequences) owns the shared transport ceiling and mandatory request admission before protobuf parsing; the shared deframing path can buffer large requests and requires separate resource qualification. Current implementation and migration qualification are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) and [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The unregistered bounded retention service uses the configured cadence and batch bound, pages past protected candidates, and reports oldest blocking age, cleanup lag, pending-transfer age and fixed cleanup outcomes without identity-bearing metric labels. Unfinished or unavailable authority remains protected. Production registration and real gameplay admission stay closed pending the [owning proof gate](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index edf6e95330..3fb21ccc91 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -14,10 +14,18 @@ The current bounded-retirement parent carry preserves the created owner and imme The next review correction counts typed snapshot recognition as classification progress and preserves unavailable owner-evidence status after caller validation. R247 freshly passes all 39 Entity retention PostgreSQL cases, including five typed-only rows drained as 2, 2, 1, 0 without rewriting source rows or their row versions. R246 supplies 20 affected Entity and 51 Game Session unit passes; after correcting a shared-fixture session mismatch and preserving separate per-actor creation identities, R248 freshly passes the 34 Game Session client and selection cases. Its initial SQL-proof compilation failure supplies no runtime credit. R250 separately passes 15 Entity owner-client unit and mTLS cases. -The large-payload qualification fills the four existing opaque limits (168 MiB total) and maximizes the supported feedback field in one valid canonical action family. R249 reproduces the five-second acknowledgement deadline failure through actual Game Session PostgreSQL storage, the durable owner and authenticated adapter, and the production Entity client. R251 then passes the initial and retired reads, acknowledgement, confirmation and exact retained-value assertions with a ten-second created-purpose RPC budget. Actual API times are 3.208, 3.062, 10.354 and 8.784 seconds respectively; API timing includes validation outside the RPC deadline. Original responses are 177,563,987 and 177,564,163 bytes, the acknowledgement request is 177,565,210 bytes and confirmation is 177,565,366 bytes. The independent 192–195 MiB envelopes are not claimed to be reachable maxima. R250's earlier combined run ended with exit 137; kernel evidence records a global Java OOM kill, without establishing a precise process attribution. The successful isolated R251 reduces temporary test copies and uses a private 3 GiB test heap, which is qualification headroom rather than a production recommendation. Controlled historical creation, superseding route/admission values and test PKI do not establish genuine source issuance, the current supersession writer, production latency or capacity, registration, admission or activation. +The large-payload qualification fills the four existing opaque limits (168 MiB total) and maximizes the supported feedback field in one valid canonical action family. R249 reproduces the five-second acknowledgement deadline failure through actual Game Session PostgreSQL storage, the durable owner and authenticated adapter, and the production Entity client. R251 then passes the initial and retired reads, acknowledgement, confirmation and exact retained-value assertions with a ten-second created-purpose RPC budget. Actual API times are 3.208, 3.062, 10.354 and 8.784 seconds respectively; API timing includes validation outside the RPC deadline. Original responses are 177,563,987 and 177,564,163 bytes, the acknowledgement request is 177,565,210 bytes and confirmation is 177,565,366 bytes. R251 explicitly enlarges its test server receive limit; it does not qualify production server request admission or the original Entity creation writer at those sizes. The independent 192–195 MiB envelopes are not claimed to be reachable maxima. R250's earlier combined run ended with exit 137; kernel evidence records a global Java OOM kill, without establishing a precise process attribution. The successful isolated R251 reduces temporary test copies and uses a private 3 GiB test heap, which is qualification headroom rather than a production recommendation. Controlled historical creation, superseding route/admission values and test PKI do not establish genuine source issuance, the current supersession writer, production latency or capacity, registration, admission or activation. R252 passes the remaining affected Common, Entity and Game Session formatting/static checks, the new SQL/mTLS case at its ordinary 5 MiB size, and documentation validation. Its new shared value fixture initially triggers immutable-protobuf accessor warnings; R255 passes the scoped fixture checks after retaining only the justified immutable-accessor suppression. Fresh Entity and Game Session images at code checkpoint `d92b28bbc7faf4292b7bc21d5e7c56e0658da4b6` pass R254 held Gateway/Telnet denial and the isolated backend WebSocket WORLDS, LOGIN, PLAY and LOOK baseline. Authenticated teardown succeeds, and independent exact-project checks confirm zero containers, networks and volumes. This qualifies packaging and the controlled baseline while the genuine admission and activation limits remain open. +The next correction preserves the independently fresh source reads, removes repeated validation within one retained-row decision, and gives only the two created roster calls a twenty-second outer deadline while retaining their ten-second nested original-owner deadline. R261 passes the actual full Game Session selection entrypoint in 14.524 seconds with eight independent complete source observations; Game Session and Entity use real authenticated owners while upstream design, World and policy facts remain controlled. R264 passes the actual Entity creation writer and both roster owners with a 155,291,849-byte terminal, a 906-byte roster and a 155,292,887-byte selected response. Its list and selected API times are 6.291 and 8.380 seconds. Forward Entity V1021 and Game Session V1022 remove whole-row binary-to-JSON conversion from immutable-row comparison without rewriting published migrations. Both jOOQ generations pass; R262 preserves the existing creation and Game Session migration cases, and R263 passes the new retained-created cohort after correcting its empty-source fixture. R264 precedes the shared production guard and does not qualify its request path. + +R267 passes thirteen focused shared-server cases, including actual mTLS/gzip exact-boundary and oversized requests, unknown-length admission before protobuf parsing, preserved interceptor context and response handling, and rejection of unguarded or substituted handlers. The initial R265 TLS fixture failure and R266 oversized wire-status failure are corrected; neither failed attempt supplies missing Game Session or composed-owner proof. R268 passes all three Game Session policy/discovery cases, including each actual purpose limit plus one byte rejected before parsing; its composed-test compilation failure was corrected before execution. R269 passes the ordinary-size owner and SQL flows. R270 then passes wrong-role and wrong-namespace ACK and confirmation attempts through the production mTLS guard, preserving all transfer bindings and the unconfirmed row before valid confirmation. R271 passes both large compositions using the canonical bounded production factory without a test receive-limit override: the actual creation writer feeds selection, retained retirement observation, durable Entity outbox, authenticated ACK and confirmation with a 155,291,849-byte terminal, a 155,295,932-byte ACK and a 155,296,090-byte confirmation. The complete selection takes 21.899 seconds across its independent calls. The separate stipulated 168 MiB opaque-field vector retains its prior 177,565,210-byte ACK and 177,565,366-byte confirmation, with API times of 9.984 and 9.057 seconds; API validation outside the RPC deadline remains included. These are known legal vectors, not claimed reachable maxima of the envelopes. A private 3 GiB test heap supplies qualification headroom. Controlled successor facts and test PKI remain explicit limits; fresh packaging and consolidated affected checks remain under qualification. These checks do not establish a network-memory ceiling, production capacity, genuine source custody or public activation. + +The shared request guard now buffers and replays bounded 64 KiB chunks without flattening the complete request into a second byte array. R275 repeats both large compositions successfully through that guard, retaining the actual-writer and separate opaque-vector sizes above; the complete multi-call selection takes 22.170 seconds. Existing keepalive warnings do not invalidate the completed calls or establish a production latency or capacity result. The actual Spring Boot discovery regression and the cross-service fixture use real framework service discovery and the canonical factory. Tests explicitly replacing the server lifecycle retain their mock, while an explicit factory start still refuses missing configured method descriptors. + +R277 passes the full enabled Common and Entity checks with 1,040 Common tests, 416 Entity unit cases and 117 Entity PostgreSQL cases, all without failures, errors or skips. Its 2,576 Game Session unit and 36 cross-service cases also pass. The Game Session integration aggregate remains a failed result: 370 reported cases include nine setup failures across two PostgreSQL fixtures and one Redis initializer, plus one skipped large-payload method. Connection refusal and port-readiness timeout do not establish a host-side cause. R278 then passes all fourteen cases in those three selected fixtures, together with the remaining Game Session enabled static, format and check tasks; it is focused recovery, not a new unfiltered integration run. PostgreSQL fixtures use the existing bounded mapped-JDBC readiness check before schema use, while the Redis fixture is unchanged. R275 separately executes the large-payload proof skipped in the ordinary aggregate. Earlier R272 and R274 heap/frontier and server-fixture failures retain their failed attribution; their corrections do not earn missing aggregate or packaging proof. Fresh-image qualification for this corrective source remains pending, as do genuine custody, causal current supersession, production registration, admission and activation. + Earlier parent qualification receives #3295 at `cc33169ca1354872e101c4ef42777b0e79032473`, including its complete release/World validation correction. R116 passes the full Game Session check, formatting and affected static analysis with 2,568 unit cases, 365 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. This includes the actual initial owner-to-owner composition, which freshly passes in 30.763 seconds. The tested postimages are retained at `c9774094d76097ade5dcc5530d346e4960e613d8` after canonical fixture formatting. Unchanged Entity production source retains R113’s 402 unit and 94 PostgreSQL executions; R116 also passes both affected fixture static checks after correcting the earlier fixture-only SpotBugs failures. R117 freshly rebuilds that checkpoint and passes held Gateway/Telnet denial and isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK`, followed by authenticated teardown and independently confirmed exact-project container, network and volume absence. Prior component qualification R96 executes at `b53bc6fd8b12263b27eea03793586febd525d5da` and passes 402 Entity unit cases, 94 Entity PostgreSQL cases and 2,567 Game Session unit cases with affected static analysis, formatting and documentation checks. Unchanged Common and broader Game Session physical proof retain R86 attribution: 1,020 Common unit cases, 364 Game Session PostgreSQL cases and 36 cross-service cases. R86's earlier 396 Entity and 2,565 Game Session unit counts are superseded by the new executions, rather than credited as fresh runs. Native Entity proof includes the actual retained creation writer feeding authenticated source-bound snapshot capture; socket fixtures use controlled PKI and owner facts, including a complete 5 MiB terminal rather than physical proof at every maximum purpose bound. After the documentation-only parent carry, R93 rebuilds fresh images at `765f4b23bb6e0c0b65c9db6b7673ed108c11522a` with the same code and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`. Authenticated teardown completes, and independent exact-project inspection confirms no remaining containers, networks or volumes. The documentation-only carry through parent `2aa25d9327bd9c15698c69168f2c96254f0fa732` preserves that code; the later release/World correction is qualified by R116 and R117 above. This validates controlled components, storage, packaging and the isolated backend baseline; it does not exercise a registered production created-actor flow. @@ -78,7 +86,7 @@ These links add decision provenance only; they do not upgrade entity, equipment, | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | +| GR-3.1 Character, NPC, and item state and lifecycle | `partial` - opaque actor UUID/quarantine metadata, exact canonical identity readers, assignment/receipt/roster storage, an unregistered created-actor terminal writer and source-bound roster/receipt consumers, and manually composed unregistered source services and guarded read-client/adapter definitions are present. Legacy consumers retain develop behavior for legacy rows; new owner-resolved actors are excluded from numeric character and holder predicates. No authenticated handler/caller, retained-identity promotion, controller/execution replacement, or production admission is activated. | `proven` - bounded passive preparation and controlled-storage proof for created-actor capture/readback, sealed-roster retention and exact canonical actor-repository read isolation. See [Player-created owner and roster preparation](#player-created-owner-and-roster-preparation). See [Canonical sealed roster retention prerequisite](#canonical-sealed-roster-retention-prerequisite), [Canonical actor repository read isolation](#canonical-actor-repository-read-isolation) and [Validation and Proof](#validation-and-proof); this proof does not establish genuine owner issuance, production registration or runtime activation, public admission, or a packaged player journey. | [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) | [ActorIdentityRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/ActorIdentityRepository.java); [CharacterRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java); [CanonicalGameplayRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterService.java); [PreseededActorAssignmentService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PreseededActorAssignmentService.java); [V1003 actor identity](../../../services/entity-management-service/src/main/resources/db/migration/V1003__quarantine_unresolved_actor_identity.sql); [V1006 assignment storage](../../../services/entity-management-service/src/main/resources/db/migration/V1006__preseeded_actor_assignment.sql); [CanonicalGameplayRosterGrpcAdapter.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapter.java); [CanonicalGameplayRosterPeerInterceptor.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptor.java); [GameSessionCanonicalGameplayRosterOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClient.java); [GameSessionPreseededActorAssignmentOwnerReadClient.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClient.java); [CanonicalGameplayRosterRetentionRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java); [CanonicalGameplayRosterRecoveryService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryService.java); [CanonicalGameplayRosterRetentionService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java); [V1012 sealed-roster retention](../../../services/entity-management-service/src/main/resources/db/migration/V1012__canonical_roster_retention.sql); [CanonicalGameplayRosterReferenceOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java); [CanonicalGameplayRosterReferenceRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java); [V1015 roster reference owner](../../../services/game-session-service/src/main/resources/db/migration/V1015__canonical_roster_reference_owner.sql); [EntityCharacterCreateRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java); [EntityPlayerCreatedRosterSnapshotRepository.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java); [EntityPlayerCreatedRosterService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java); [Entity V1015 character-create terminal](../../../services/entity-management-service/src/main/resources/db/migration/V1015__entity_character_create_terminal.sql); [Entity V1016 player-created roster snapshots](../../../services/entity-management-service/src/main/resources/db/migration/V1016__player_created_roster_snapshot_receipts.sql); [Entity V1020 typed created-retirement recognition](../../../services/entity-management-service/src/main/resources/db/migration/V1020__canonical_roster_created_retirement_recognition.sql); [Game Session V1020 player-created roster reference](../../../services/game-session-service/src/main/resources/db/migration/V1020__player_created_roster_reference.sql); [Entity V1014 retirement observation](../../../services/entity-management-service/src/main/resources/db/migration/V1014__canonical_roster_retirement_observation.sql); [Game Session V1017 retirement observation](../../../services/game-session-service/src/main/resources/db/migration/V1017__canonical_roster_retirement_observation.sql); [CanonicalGameplayRosterRetirementEvidence.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRetirementEvidence.java) | [ActorIdentityValueTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/entity/ActorIdentityValueTest.java); [RetainedActorIdentityIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java); [FlywayPostgresqlLockConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/FlywayPostgresqlLockConfigurationTest.java); [CanonicalGameplayRosterIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java); [PreseededActorAssignmentIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java); [CanonicalGameplayRosterConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java); [PreseededActorAssignmentConfigurationTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java); [CanonicalGameplayRosterPeerInterceptorTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java); [CanonicalGameplayRosterGrpcAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java); [GameSessionCanonicalGameplayRosterOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java); [GameSessionPreseededActorAssignmentOwnerReadClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java); [AccountRuntimeIdentityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java); [AccountPreseededActorStagingEligibilityClientTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java); [GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapterTest.java); [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java); [Entity retention PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java); [Entity recovery service unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java); [Entity retention sweep unit proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java); [Entity recovery adapter mTLS proof](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java); [Entity character-create PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java); [Entity player-created roster snapshot PostgreSQL proof](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java); [Game Session reference PostgreSQL proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java); [Player-created roster owner composition integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java); [Game Session reference mTLS proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java) | [GR-2.2](./world-runtime-and-movement.md); [AA-2.1](./player-access-and-session.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Authenticated owner provenance and genuine authority, full current supersession-to-retirement composition and genuine created-roster authority, real caller/controller/execution replacement, production admission, production PKI and activation, and a genuine playable journey remain open. Genuine policy/descriptor/template owner composition, auto-provisioning, fork-copy identity, and complete actor/NPC lifecycle also remain gaps. The sealed-roster retention prerequisite is locally source- and proof-qualified but remains unregistered. | | GR-3.2 Inventory, containers, ownership, and placement | `partial` - item instances/stacks, hidden and room-ground containers, guarded transfers, visible refs, audits, and replay guards for nonblank `effectId` are live; blank-`effectId` compatibility execution bypasses the Entity replay ledger. | `proven` - focused inventory, container, stack, transfer, location, and nonblank-`effectId` mutation-replay tests cover the bounded holder model; blank-ID ingress bypass and remediation proof remain open. | [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md); [Transactions](../../architecture/system-architecture-transactions.md) | [InventoryServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java); [ContainerServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java); [ItemTransferSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupport.java); [StackableItemSupport.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupport.java); [entity schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [InventoryServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImplTest.java); [ContainerServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImplTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java); [StackableItemSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/StackableItemSupportTest.java); [ContainerInstanceLocationIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/ContainerInstanceLocationIntegrationTest.java); [EntityMutationEffectReplayServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java) | [GR-2.2](./world-runtime-and-movement.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AR-1.1](./game-authoring-publishing-and-activation.md) | Blank-`effectId` replay-ledger bypass and its ingress remediation remain open, alongside nested-container UX, banking/vendor/corpse holders, richer filters, cross-domain replay contracts, and stronger audit alerting. | | GR-3.3 Equipment, body layouts, slots, and loadouts | `partial` - authored slot/body-layout compatibility and `WEAR`/`REMOVE` equipment binding are live; loadouts and lifecycle triggers are not. | `proven` - focused equipment service/controller and item-command tests cover slot compatibility and binding. | [Item/equipment balancing](../../architecture/microservices/game-design-service/item-equipment-balancing.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [EquipmentServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImpl.java); [EquipmentSlotDefinition.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/entity/EquipmentSlotDefinition.java); [EquipmentController.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java); [equipment schema](../../../services/entity-management-service/src/main/resources/db/migration/V1__baseline.sql) | [EquipmentServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EquipmentServiceImplTest.java); [EquipmentControllerTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/controller/EquipmentControllerTest.java); [EquipmentCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java); [ItemTransferSupportTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ItemTransferSupportTest.java) | [GR-3.2](./gameplay-rules-entities-and-effects.md); [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.1](./game-authoring-publishing-and-activation.md); [AR-3.2](./game-authoring-publishing-and-activation.md); [GR-4.1](./gameplay-rules-entities-and-effects.md) | Rich loadouts, broader authored body-layout lifecycle, equip/unequip/use/break triggers, and complete equipment effects remain absent. Publication fail-closed validation, complete occupancy semantics, and owner-validated cutover remapping remain target gaps coordinated with AR-3.2. | | GR-4.1 Action, targeting, check, effect, and status resolution | `partial` - typed actor-state evaluation, conditions, durable replay, and self-targeted `APPLY_ACTION_STATE` admission are live; general action resolution is not. | `proven` - focused evaluator, payload, actor-condition, authored-action, status, and durable-execution tests cover the bounded seam. | [Ability and action tools](../../architecture/microservices/game-design-service/ability-action-tools.md); [Player command model](../../architecture/system-architecture-player-command-model.md); [Entity runtime/data](../../architecture/microservices/entity-management-service/runtime-and-data.md) | [DefaultEffectEvaluationService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java); [ActorStateServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java); [ActorConditionMutationServiceImpl.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImpl.java); [AuthoredActionCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandler.java); [TextCommandEffectDeclaration.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclaration.java); [actor-state proto](../../../protos/entity-management/v1/entity_management_service.proto) | [DefaultEffectEvaluationServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationServiceTest.java); [EffectPayloadParserTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/effect/EffectPayloadParserTest.java); [ActorConditionMutationServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorConditionMutationServiceImplTest.java); [ActorStateServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImplTest.java); [AuthoredActionCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java); [DefaultDurableGameplayCommandExecutionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java) | [EA-1.1](./player-experience-commands-and-communication.md); [AR-1.5](./game-authoring-publishing-and-activation.md); [GR-1.4](./game-session-runtime-and-tick-coordination.md); [SF-2.3](./shared-runtime-contracts-and-persistence.md); [AS-1.5](./automation-and-scheduler-runtime.md) | Cross-actor target sets, checks, resource costs/cooldowns, multi-effect plans, semantic outcomes, and full release-catalog enforcement remain absent. | diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java new file mode 100644 index 0000000000..472edb7a25 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java @@ -0,0 +1,150 @@ +package net.firedevops.firemud.common.config; + +import io.grpc.BindableService; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.grpc.server.autoconfigure.ConditionalOnGrpcNativeServer; +import org.springframework.boot.grpc.server.autoconfigure.ConditionalOnGrpcServerEnabled; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.util.LambdaSafe; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.ServerBuilderCustomizer; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.GrpcServiceConfigurer; +import org.springframework.grpc.server.service.GrpcServiceDiscoverer; + +/** Owns the shared production registration boundary; alternate factories fail startup. */ +@AutoConfiguration( + beforeName = + "org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration") +@ConditionalOnClass({GrpcServerFactory.class, NettyServerBuilder.class}) +@ConditionalOnBean(BindableService.class) +@ConditionalOnGrpcServerEnabled +@EnableConfigurationProperties(GrpcServerProperties.class) +public class CommonGrpcRequestBoundsAutoConfiguration { + @Bean + @ConditionalOnMissingBean(GrpcRequestBytePolicy.class) + GrpcRequestBytePolicy ordinaryGrpcRequestBytePolicy() { + return GrpcRequestBytePolicy.ordinary(); + } + + @Bean + @ConditionalOnGrpcNativeServer + BoundedGrpcServerFactory boundedGrpcServerFactory( + GrpcServerProperties properties, + GrpcRequestBytePolicy policy, + GrpcServiceDiscoverer discoverer, + GrpcServiceConfigurer configurer, + ObjectProvider bundles, + ObjectProvider> builderCustomizers, + ObjectProvider factoryCustomizers, + Environment environment) { + KeyManagerFactory keys = null; + TrustManagerFactory trust = null; + if (properties.getSsl().determineEnabled()) { + String bundleName = properties.getSsl().getBundle(); + if (bundleName == null || bundleName.isBlank()) { + throw new IllegalStateException("A gRPC SSL bundle is required"); + } + SslBundle bundle = bundles.getObject().getBundle(bundleName); + keys = bundle.getManagers().getKeyManagerFactory(); + trust = + properties.getSsl().isSecure() + ? bundle.getManagers().getTrustManagerFactory() + : InsecureTrustManagerFactory.INSTANCE; + } + int transportMaximum = policy.transportMaximumBytes(); + if (environment.containsProperty("spring.grpc.server.max-inbound-message-size")) { + transportMaximum = Math.toIntExact(properties.getMaxInboundMessageSize().toBytes()); + } + List> customizers = + List.of( + builder -> configureProperties(builder, properties), + builder -> + applyBuilderCustomizers(builder, builderCustomizers.orderedStream().toList())); + BoundedGrpcServerFactory factory = + new BoundedGrpcServerFactory( + properties.determineAddress(), + customizers, + keys, + trust, + properties.getSsl().getClientAuth(), + policy, + transportMaximum); + factoryCustomizers.orderedStream().forEach(customizer -> customizer.customize(factory)); + discoverer + .findServices() + .forEach(service -> factory.addService(configurer.configure(service, factory))); + return factory; + } + + @Bean + @ConditionalOnMissingBean(GrpcServerLifecycle.class) + GrpcServerLifecycle boundedGrpcServerLifecycle( + BoundedGrpcServerFactory factory, + GrpcServerProperties properties, + ApplicationEventPublisher publisher) { + return new GrpcServerLifecycle(factory, properties.getShutdownGracePeriod(), publisher); + } + + @Bean + SmartInitializingSingleton requireOnlyBoundedGrpcServerFactory(ApplicationContext context) { + return () -> { + var factories = context.getBeansOfType(GrpcServerFactory.class); + if (factories.size() != 1 + || factories.values().iterator().next().getClass() != BoundedGrpcServerFactory.class) { + throw new IllegalStateException( + "Production gRPC requires exactly one bounded server factory"); + } + }; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static void applyBuilderCustomizers( + NettyServerBuilder builder, List> customizers) { + LambdaSafe.callbacks(ServerBuilderCustomizer.class, customizers, builder) + .invoke(customizer -> customizer.customize(builder)); + } + + private static void configureProperties( + NettyServerBuilder builder, GrpcServerProperties properties) { + var keepAlive = properties.getKeepAlive(); + duration(keepAlive.getTime(), builder::keepAliveTime); + duration(keepAlive.getTimeout(), builder::keepAliveTimeout); + duration(keepAlive.getMaxIdle(), builder::maxConnectionIdle); + duration(keepAlive.getMaxAge(), builder::maxConnectionAge); + duration(keepAlive.getMaxAgeGrace(), builder::maxConnectionAgeGrace); + duration(keepAlive.getPermitTime(), builder::permitKeepAliveTime); + builder.permitKeepAliveWithoutCalls(keepAlive.isPermitWithoutCalls()); + builder.maxInboundMetadataSize( + Math.toIntExact(properties.getMaxInboundMetadataSize().toBytes())); + } + + private static void duration(Duration duration, BiConsumer apply) { + if (duration != null) { + apply.accept(duration.toNanos(), TimeUnit.NANOSECONDS); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshaller.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshaller.java new file mode 100644 index 0000000000..cdc5810b49 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshaller.java @@ -0,0 +1,176 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.ForwardingServerCall; +import io.grpc.ForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.SequenceInputStream; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.Enumeration; + +/** Raw stream marshalling paired with admission before the original protobuf parser. */ +final class BoundedGrpcRequestMarshaller implements MethodDescriptor.Marshaller { + private static final int CHUNK_BYTES = 64 * 1024; + + private BoundedGrpcRequestMarshaller() {} + + static ServerServiceDefinition rawMessages(ServerServiceDefinition service) { + // Unlike useInputStreamMessages, this public adapter does not add a prefetching buffer. + return ServerInterceptors.useMarshalledMessages(service, new BoundedGrpcRequestMarshaller()); + } + + @Override + public InputStream stream(InputStream message) { + return message; + } + + @Override + public InputStream parse(InputStream message) { + return message; + } + + static ServerCallHandler guard( + ServerCallHandler next, int maximum) { + if (maximum <= 0 || maximum == Integer.MAX_VALUE) { + throw new IllegalArgumentException("A finite positive request byte bound is required"); + } + return (call, headers) -> { + var state = new CallState(); + ServerCall observedCall = + new ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void close(Status status, Metadata trailers) { + state.closed = true; + super.close(status, trailers); + } + }; + // The public stream adapter invokes the existing intercepted handler here. Its + // authentication, Contexts listener wrappers and response marshaller remain intact. + var delegate = next.startCall(observedCall, headers); + return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>(delegate) { + @Override + public void onMessage(InputStream message) { + if (stopped()) { + return; + } + Deque admitted = new ArrayDeque<>(); + int admittedBytes = 0; + try { + // Neither available(), compressed wire length nor caller metadata grants admission. + // Retain bounded chunks without flattening the whole request into a second array. + while (admittedBytes <= maximum) { + int requested = Math.min(CHUNK_BYTES, maximum - admittedBytes + 1); + byte[] chunk = message.readNBytes(requested); + if (chunk.length == 0) { + break; + } + admitted.addLast(chunk); + admittedBytes += chunk.length; + if (chunk.length < requested) { + break; + } + } + } catch (IOException failure) { + reject( + Status.INTERNAL + .withDescription("Unable to read bounded gRPC request") + .withCause(failure)); + return; + } catch (RuntimeException failure) { + Status status = Status.fromThrowable(failure); + reject( + status.getCode() == Status.Code.UNKNOWN + ? Status.INTERNAL + .withDescription("Unable to read bounded gRPC request") + .withCause(failure) + : status); + return; + } + if (admittedBytes > maximum) { + reject( + Status.RESOURCE_EXHAUSTED.withDescription( + "gRPC request exceeds method byte bound")); + return; + } + if (!stopped()) { + // Only this replay reaches the stream adapter's original protobuf parser. + super.onMessage(replay(admitted)); + } + } + + @Override + public void onHalfClose() { + if (!stopped()) { + super.onHalfClose(); + } + } + + @Override + public void onReady() { + if (!stopped()) { + super.onReady(); + } + } + + @Override + public void onCancel() { + if (!state.terminal) { + state.terminal = true; + state.closed = true; + super.onCancel(); + } + } + + @Override + public void onComplete() { + if (!state.terminal) { + state.terminal = true; + state.closed = true; + super.onComplete(); + } + } + + private boolean stopped() { + return state.closed || call.isCancelled(); + } + + private void reject(Status status) { + if (!stopped()) { + // Close explicitly: exceptions escaping marshaller.parse become UNKNOWN on the wire. + observedCall.close(status, new Metadata()); + } + } + }; + }; + } + + private static InputStream replay(Deque chunks) { + return new SequenceInputStream( + new Enumeration<>() { + @Override + public boolean hasMoreElements() { + return !chunks.isEmpty(); + } + + @Override + public InputStream nextElement() { + // Drop consumed chunks as the original parser advances, without a whole-message copy. + return new ByteArrayInputStream(chunks.removeFirst()); + } + }); + } + + private static final class CallState { + private volatile boolean closed; + private boolean terminal; + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactory.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactory.java new file mode 100644 index 0000000000..3ef97f15d7 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactory.java @@ -0,0 +1,87 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.HandlerRegistry; +import io.grpc.Server; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.TlsServerCredentials; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; +import org.springframework.grpc.server.ServerBuilderCustomizer; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; + +/** The production factory admits every method before protobuf parsing. */ +public final class BoundedGrpcServerFactory extends ShadedNettyGrpcServerFactory { + private static final HandlerRegistry CLOSED_FALLBACK = + new HandlerRegistry() { + @Override + public ServerMethodDefinition lookupMethod(String methodName, String authority) { + return null; + } + }; + private final Set> guardedMethods = + Collections.newSetFromMap(new IdentityHashMap<>()); + private final GrpcRequestBytePolicy policy; + private final int transportMaximum; + + public BoundedGrpcServerFactory( + String address, + List> customizers, + KeyManagerFactory keys, + TrustManagerFactory trust, + TlsServerCredentials.ClientAuth clientAuth, + GrpcRequestBytePolicy policy, + int transportMaximum) { + super(address, customizers, keys, trust, clientAuth); + if (transportMaximum <= 0 || transportMaximum > policy.transportMaximumBytes()) { + throw new IllegalArgumentException("Transport bound exceeds the closed gRPC request policy"); + } + this.policy = policy; + this.transportMaximum = transportMaximum; + } + + @Override + protected void configureServices( + NettyServerBuilder builder, List services) { + policy.requireRegistered(services); + List guarded = + services.stream().map(service -> policy.guard(service, transportMaximum)).toList(); + guardedMethods.clear(); + guarded.forEach(service -> guardedMethods.addAll(service.getMethods())); + super.configureServices(builder, guarded); + } + + @Override + protected void configure(NettyServerBuilder builder, List services) { + super.configure(builder, services); + // Customizers cannot leave an alternate mutable lookup or widen the finite ceiling. + builder.fallbackHandlerRegistry(CLOSED_FALLBACK); + builder.maxInboundMessageSize(transportMaximum); + } + + @Override + public Server createServer() { + Server server = super.createServer(); + try { + for (ServerServiceDefinition service : server.getServices()) { + for (ServerMethodDefinition method : service.getMethods()) { + // A descriptor or marshaller alone cannot prove its handler still enforces admission. + if (!guardedMethods.contains(method)) { + throw new IllegalStateException( + "Unguarded gRPC method registered: " + + method.getMethodDescriptor().getFullMethodName()); + } + } + } + return server; + } catch (RuntimeException failure) { + server.shutdownNow(); + throw failure; + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcRequestBytePolicy.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcRequestBytePolicy.java new file mode 100644 index 0000000000..12710266b3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcRequestBytePolicy.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.common.grpc; + +import io.grpc.MethodDescriptor; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import java.io.InputStream; +import java.util.HashSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; + +/** Closed, server-owned generated-descriptor exceptions to ordinary raw request admission. */ +public final class GrpcRequestBytePolicy { + public static final int ORDINARY_MAXIMUM_BYTES = 4 * 1024 * 1024; + private final Map, Integer> exceptions; + + record MethodBound(MethodDescriptor method, int maximumBytes) { + MethodBound { + Objects.requireNonNull(method); + if (maximumBytes <= 0 || maximumBytes == Integer.MAX_VALUE) { + throw new IllegalArgumentException("A finite positive method byte bound is required"); + } + } + } + + GrpcRequestBytePolicy(List bounds) { + exceptions = new IdentityHashMap<>(); + Set names = new HashSet<>(); + for (MethodBound bound : bounds) { + if (!names.add(bound.method().getFullMethodName())) { + throw new IllegalArgumentException("Duplicate gRPC request bound"); + } + exceptions.put(bound.method(), bound.maximumBytes()); + } + } + + public static GrpcRequestBytePolicy ordinary() { + return new GrpcRequestBytePolicy(List.of()); + } + + public static GrpcRequestBytePolicy createdRosterRetirement() { + return new GrpcRequestBytePolicy( + List.of( + new MethodBound( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod(), + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES), + new MethodBound( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getConfirmCanonicalGameplayRosterRetirementAcknowledgementMethod(), + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES))); + } + + public int transportMaximumBytes() { + return Math.max( + ORDINARY_MAXIMUM_BYTES, + exceptions.values().stream() + .mapToInt(Integer::intValue) + .max() + .orElse(ORDINARY_MAXIMUM_BYTES)); + } + + void requireRegistered(List services) { + Set> found = + java.util.Collections.newSetFromMap(new IdentityHashMap<>()); + for (ServerServiceDefinition service : services) { + service.getMethods().forEach(method -> found.add(method.getMethodDescriptor())); + } + if (!found.containsAll(exceptions.keySet())) { + throw new IllegalStateException( + "Configured gRPC request bound has no exact registered descriptor"); + } + } + + ServerServiceDefinition guard(ServerServiceDefinition service, int transportMaximum) { + ServerServiceDefinition raw = BoundedGrpcRequestMarshaller.rawMessages(service); + ServerServiceDefinition.Builder result = + ServerServiceDefinition.builder(raw.getServiceDescriptor()); + for (ServerMethodDefinition method : service.getMethods()) { + MethodDescriptor original = method.getMethodDescriptor(); + int maximum = + Math.min(transportMaximum, exceptions.getOrDefault(original, ORDINARY_MAXIMUM_BYTES)); + ServerMethodDefinition rawMethod = + streamMethod(raw.getMethod(original.getFullMethodName())); + result.addMethod( + rawMethod.withServerCallHandler( + BoundedGrpcRequestMarshaller.guard(rawMethod.getServerCallHandler(), maximum))); + } + return result.build(); + } + + @SuppressWarnings("unchecked") + private static ServerMethodDefinition streamMethod( + ServerMethodDefinition method) { + // rawMessages uses the public adapter with InputStream request and response marshallers. + return (ServerMethodDefinition) method; + } +} diff --git a/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 89624a3ff9..f8eea3ce77 100644 --- a/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/services/common-platform-core/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -1 +1,2 @@ net.firedevops.firemud.common.config.CommonCoreAutoConfiguration +net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshallerTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshallerTest.java new file mode 100644 index 0000000000..db73d0dbc2 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcRequestMarshallerTest.java @@ -0,0 +1,356 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class BoundedGrpcRequestMarshallerTest { + private static final Context.Key CONTEXT = Context.key("bounded-admission-test"); + + @Test + void exactUnknownLengthBoundaryParsesThenPreservesContextResponseAndLifecycle() { + var harness = new Harness(false); + harness.deliver( + new ByteArrayInputStream(new byte[8]) { + @Override + public int available() { + throw new AssertionError("available is not admission"); + } + }); + assertThat(harness.parses).hasValue(1); + harness.listener.onHalfClose(); + harness.listener.onComplete(); + assertThat(harness.events) + .containsExactly( + "start:identity", "message:identity", "half-close:identity", "complete:identity"); + assertThat(harness.call.closed).extracting(Status::getCode).containsExactly(Status.Code.OK); + assertThat(harness.call.response).isEqualTo(new byte[] {1, 2, 3}); + assertThat(harness.originalDescriptorObserved).isTrue(); + assertThat(harness.originalHeadersObserved).isTrue(); + } + + @Test + void chunkedReplayPreservesExactBytesAcrossFullChunksAndPartialTail() { + byte[] expected = new byte[2 * 64 * 1024 + 17]; + for (int index = 0; index < expected.length; index++) { + expected[index] = (byte) (index % 251); + } + var harness = new Harness(false, expected.length); + harness.deliver( + new ByteArrayInputStream(expected) { + @Override + public int available() { + throw new AssertionError("available is not admission"); + } + }); + assertThat(harness.parses).hasValue(1); + assertThat(harness.received).isEqualTo(expected); + harness.listener.onHalfClose(); + assertThat(harness.call.closed).extracting(Status::getCode).containsExactly(Status.Code.OK); + } + + @Test + void overflowAcrossChunkBoundaryStillStopsAtSentinelBeforeOriginalParser() { + int maximum = 64 * 1024 + 17; + var harness = new Harness(false, maximum); + AtomicInteger reads = new AtomicInteger(); + harness.deliver( + new InputStream() { + @Override + public int read() { + reads.incrementAndGet(); + return 255; + } + }); + harness.listener.onHalfClose(); + assertThat(reads).hasValue(maximum + 1); + assertThat(harness.parses).hasValue(0); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.RESOURCE_EXHAUSTED); + assertThat(harness.events).containsExactly("start:identity"); + } + + @Test + void oversizedMalformedUnknownLengthClosesExplicitlyWithoutParserOrOwnerDispatch() { + var harness = new Harness(false); + AtomicInteger reads = new AtomicInteger(); + harness.deliver( + new InputStream() { + @Override + public int read() { + reads.incrementAndGet(); + return 255; + } + + @Override + public int available() { + return 0; + } + }); + assertThat(reads).hasValue(9); + assertThat(harness.parses).hasValue(0); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.RESOURCE_EXHAUSTED); + harness.deliver(new ByteArrayInputStream(new byte[8])); + harness.listener.onHalfClose(); + harness.listener.onReady(); + harness.listener.onCancel(); + harness.listener.onCancel(); + harness.listener.onComplete(); + assertThat(harness.events).containsExactly("start:identity", "cancel:identity"); + assertThat(harness.call.closed).hasSize(1); + assertThat(harness.parses).hasValue(0); + } + + @Test + void readFailureClosesInternalAndTerminalCompleteStillCleansUpOnce() { + var harness = new Harness(false); + harness.deliver( + new InputStream() { + @Override + public int read() throws IOException { + throw new IOException("broken transport"); + } + }); + harness.listener.onHalfClose(); + harness.listener.onComplete(); + harness.listener.onComplete(); + harness.listener.onCancel(); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.INTERNAL); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity", "complete:identity"); + } + + @Test + void decompressionOrTransportStatusDuringReadIsClosedExplicitly() { + var harness = new Harness(false); + harness.deliver( + new InputStream() { + @Override + public int read() { + throw Status.RESOURCE_EXHAUSTED + .withDescription("transport decompression bound") + .asRuntimeException(); + } + }); + harness.listener.onHalfClose(); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.RESOURCE_EXHAUSTED); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity"); + } + + @Test + void cancellationSuppressesReadAndHalfCloseAndForwardsCleanupOnce() { + var harness = new Harness(false); + harness.call.cancelled = true; + harness.deliver( + new InputStream() { + @Override + public int read() { + throw new AssertionError("cancelled request must not be read"); + } + }); + harness.listener.onHalfClose(); + harness.listener.onReady(); + harness.listener.onCancel(); + harness.listener.onCancel(); + harness.listener.onComplete(); + assertThat(harness.call.closed).isEmpty(); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity", "cancel:identity"); + } + + @Test + void existingHandlerRejectionBeforeMessagesRetainsItsStatusAndPreventsParsing() { + var harness = new Harness(true); + harness.deliver( + new InputStream() { + @Override + public int read() { + throw new AssertionError("denied request must not be read"); + } + }); + harness.listener.onHalfClose(); + harness.listener.onComplete(); + assertThat(harness.call.closed) + .extracting(Status::getCode) + .containsExactly(Status.Code.PERMISSION_DENIED); + assertThat(harness.parses).hasValue(0); + assertThat(harness.events).containsExactly("start:identity", "complete:identity"); + } + + private static final class Harness { + private final AtomicInteger parses = new AtomicInteger(); + private final List events = new ArrayList<>(); + private final RecordingCall call = new RecordingCall(); + private final ServerCall.Listener listener; + private boolean originalDescriptorObserved; + private boolean originalHeadersObserved; + private byte[] received; + + private Harness(boolean rejectAtStart) { + this(rejectAtStart, 8); + } + + @SuppressWarnings("unchecked") + private Harness(boolean rejectAtStart, int maximum) { + MethodDescriptor original = + MethodDescriptor.newBuilder() + .setFullMethodName("test.Bounded/Read") + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(parser(parses)) + .setResponseMarshaller(parser(new AtomicInteger())) + .build(); + Metadata headers = new Metadata(); + ServerCallHandler handler = + (observedCall, observedHeaders) -> { + events.add("start:" + CONTEXT.get()); + originalDescriptorObserved = observedCall.getMethodDescriptor() == original; + originalHeadersObserved = observedHeaders == headers; + if (rejectAtStart) { + observedCall.close(Status.PERMISSION_DENIED, new Metadata()); + } + return new ServerCall.Listener<>() { + @Override + public void onMessage(byte[] message) { + received = message; + events.add("message:" + CONTEXT.get()); + } + + @Override + public void onHalfClose() { + events.add("half-close:" + CONTEXT.get()); + observedCall.sendHeaders(new Metadata()); + observedCall.sendMessage(new byte[] {1, 2, 3}); + observedCall.close(Status.OK, new Metadata()); + } + + @Override + public void onReady() { + events.add("ready:" + CONTEXT.get()); + } + + @Override + public void onCancel() { + events.add("cancel:" + CONTEXT.get()); + } + + @Override + public void onComplete() { + events.add("complete:" + CONTEXT.get()); + } + }; + }; + var service = + ServerServiceDefinition.builder("test.Bounded").addMethod(original, handler).build(); + service = + ServerInterceptors.intercept( + service, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall observedCall, + Metadata observedHeaders, + ServerCallHandler next) { + return Contexts.interceptCall( + Context.current().withValue(CONTEXT, "identity"), + observedCall, + observedHeaders, + next); + } + }); + var policy = + new GrpcRequestBytePolicy( + List.of(new GrpcRequestBytePolicy.MethodBound(original, maximum))); + var guarded = policy.guard(service, GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + var method = + (ServerMethodDefinition) + guarded.getMethod(original.getFullMethodName()); + call.method = method.getMethodDescriptor(); + listener = method.getServerCallHandler().startCall(call, headers); + } + + private void deliver(InputStream message) { + listener.onMessage(call.method.parseRequest(message)); + } + } + + private static final class RecordingCall extends ServerCall { + private MethodDescriptor method; + private final List closed = new ArrayList<>(); + private boolean cancelled; + private byte[] response; + + @Override + public void request(int count) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(InputStream message) { + try { + response = message.readAllBytes(); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } + + @Override + public void close(Status status, Metadata trailers) { + closed.add(status); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return method; + } + } + + static MethodDescriptor.Marshaller parser(AtomicInteger parses) { + return new MethodDescriptor.Marshaller<>() { + @Override + public InputStream stream(byte[] bytes) { + return new ByteArrayInputStream(bytes); + } + + @Override + public byte[] parse(InputStream stream) { + parses.incrementAndGet(); + try { + return stream.readAllBytes(); + } catch (IOException failure) { + throw new IllegalStateException(failure); + } + } + }; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java new file mode 100644 index 0000000000..cade53561b --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.CallOptions; +import io.grpc.HandlerRegistry; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.TlsServerCredentials; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.stub.ClientCalls; +import io.grpc.stub.ServerCalls; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class BoundedGrpcServerFactoryTest { + private static final int ORDINARY = GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES; + + @Test + void rejectsDuplicateUnknownAndNonidenticalDescriptorConfiguration() { + var method = method("test.Owner/Read", new AtomicInteger()); + assertThatThrownBy( + () -> + new GrpcRequestBytePolicy( + List.of( + new GrpcRequestBytePolicy.MethodBound(method, 1024), + new GrpcRequestBytePolicy.MethodBound(method, 1024)))) + .isInstanceOf(IllegalArgumentException.class); + var policy = + new GrpcRequestBytePolicy( + List.of(new GrpcRequestBytePolicy.MethodBound(method, ORDINARY + 1024))); + var factory = factory(policy); + factory.addService(service(method.toBuilder().build())); + assertThatThrownBy(factory::createServer).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> factory(policy).createServer()) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void refusesAnUnwrappedServiceAddedByCustomizer() { + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of( + builder -> + builder.addService(service(method("test.Bypass/Read", new AtomicInteger())))), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + new GrpcRequestBytePolicy(List.of()), + ORDINARY); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unguarded gRPC method"); + } + + @Test + void refusesAnExternallyGuardedDescriptorWhoseHandlerWasReplaced() { + var policy = GrpcRequestBytePolicy.ordinary(); + var external = policy.guard(service(method("test.Bypass/Read", new AtomicInteger())), ORDINARY); + var replaced = + io.grpc.ServerInterceptors.intercept( + external, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + return new io.grpc.ServerCall.Listener<>() {}; + } + }); + assertThat(replaced.getMethod("test.Bypass/Read").getMethodDescriptor()) + .isSameAs(external.getMethod("test.Bypass/Read").getMethodDescriptor()); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(builder -> builder.addService(replaced)), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + policy, + ORDINARY); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Unguarded gRPC method"); + } + + @Test + void mtlsCompressedOrdinaryAndFutureMethodsRejectBeforeParserAndFallbackCannotBypass( + @TempDir Path directory) throws Exception { + var pki = + LoopbackMtlsTestPki.create( + directory, + "bounded factory test CA", + new IdentitySpec("server", "spiffe://firemud/ns/test/sa/game-session-service", true), + new IdentitySpec( + "entity", "spiffe://firemud/ns/test/sa/entity-management-service", false)); + var serverIdentity = pki.identity("server"); + var ordinaryParses = new AtomicInteger(); + var exceptionalParses = new AtomicInteger(); + var futureParses = new AtomicInteger(); + var ordinary = method("test.Owner/Ordinary", ordinaryParses); + var exceptional = method("test.Owner/Exceptional", exceptionalParses); + var future = method("test.Owner/Future", futureParses); + var unknown = method("test.Unknown/Read", new AtomicInteger()); + var policy = + new GrpcRequestBytePolicy( + List.of(new GrpcRequestBytePolicy.MethodBound(exceptional, ORDINARY + 1024))); + var fallbackCalls = new AtomicInteger(); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of( + builder -> { + builder.fallbackHandlerRegistry( + new HandlerRegistry() { + @Override + public ServerMethodDefinition lookupMethod( + String method, String authority) { + fallbackCalls.incrementAndGet(); + return service(unknown).getMethod(method); + } + }); + }), + pki.keyManagerFactory(serverIdentity), + pki.trustManagerFactory(), + TlsServerCredentials.ClientAuth.REQUIRE, + policy, + policy.transportMaximumBytes()); + factory.addService( + ServerServiceDefinition.builder("test.Owner") + .addMethod(ordinary, handler()) + .addMethod(exceptional, handler()) + .addMethod(future, handler()) + .build()); + Server server = factory.createServer().start(); + var clientIdentity = pki.identity("entity"); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .sslContext( + GrpcSslContexts.forClient() + .trustManager(pki.caCertificate()) + .keyManager(clientIdentity.privateKey(), clientIdentity.certificate()) + .build()) + .build(); + ManagedChannel noCertificate = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()) + .sslContext(GrpcSslContexts.forClient().trustManager(pki.caCertificate()).build()) + .build(); + try { + var options = + CallOptions.DEFAULT.withDeadlineAfter(10, TimeUnit.SECONDS).withCompression("gzip"); + assertThat(ClientCalls.blockingUnaryCall(channel, ordinary, options, new byte[ORDINARY])) + .isEmpty(); + assertThat(ordinaryParses).hasValue(1); + byte[] bytes = new byte[ORDINARY + 1]; + assertThat(ClientCalls.blockingUnaryCall(channel, exceptional, options, bytes)).isEmpty(); + assertThat(exceptionalParses).hasValue(1); + // Response parsing uses a separate counter; these counters observe server request parsing. + assertRejected(channel, ordinary, options, bytes, Status.Code.RESOURCE_EXHAUSTED); + assertRejected(channel, future, options, bytes, Status.Code.RESOURCE_EXHAUSTED); + assertThat(ordinaryParses).hasValue(1); + assertThat(futureParses).hasValue(0); + assertRejected(channel, unknown, options, bytes, Status.Code.UNIMPLEMENTED); + assertThat(fallbackCalls).hasValue(0); + assertRejected( + channel, + exceptional, + options, + new byte[policy.transportMaximumBytes() + 1], + Status.Code.RESOURCE_EXHAUSTED); + assertThat(exceptionalParses).hasValue(1); + assertThatThrownBy( + () -> + ClientCalls.blockingUnaryCall( + noCertificate, + ordinary, + CallOptions.DEFAULT.withDeadlineAfter(3, TimeUnit.SECONDS), + new byte[0])) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).isOk()).isFalse()); + assertThat(ordinaryParses).hasValue(1); + } finally { + channel.shutdownNow(); + noCertificate.shutdownNow(); + server.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + assertThat(noCertificate.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void assertRejected( + ManagedChannel channel, + MethodDescriptor method, + CallOptions options, + byte[] bytes, + Status.Code code) { + assertThatThrownBy(() -> ClientCalls.blockingUnaryCall(channel, method, options, bytes)) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static BoundedGrpcServerFactory factory(GrpcRequestBytePolicy policy) { + return new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + policy, + policy.transportMaximumBytes()); + } + + private static MethodDescriptor method(String name, AtomicInteger parses) { + return MethodDescriptor.newBuilder() + .setFullMethodName(name) + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(BoundedGrpcRequestMarshallerTest.parser(parses)) + .setResponseMarshaller(BoundedGrpcRequestMarshallerTest.parser(new AtomicInteger())) + .build(); + } + + private static io.grpc.ServerCallHandler handler() { + return ServerCalls.asyncUnaryCall( + (request, observer) -> { + observer.onNext(new byte[0]); + observer.onCompleted(); + }); + } + + private static ServerServiceDefinition service(MethodDescriptor method) { + return ServerServiceDefinition.builder( + MethodDescriptor.extractFullServiceName(method.getFullMethodName())) + .addMethod(method, handler()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java new file mode 100644 index 0000000000..24b12af582 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java @@ -0,0 +1,293 @@ +package net.firedevops.firemud.common.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import com.google.protobuf.Empty; +import io.grpc.BindableService; +import io.grpc.CallOptions; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; +import io.grpc.ServerInterceptor; +import io.grpc.ServerServiceDefinition; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.protobuf.ProtoUtils; +import io.grpc.stub.ClientCalls; +import io.grpc.stub.ServerCalls; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; +import org.junit.jupiter.api.Test; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.annotation.Order; +import org.springframework.grpc.server.DefaultGrpcServerFactory; +import org.springframework.grpc.server.GlobalServerInterceptor; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.DefaultGrpcServiceConfigurer; +import org.springframework.grpc.server.service.DefaultGrpcServiceDiscoverer; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.grpc.server.service.GrpcServiceConfigurer; +import org.springframework.grpc.server.service.GrpcServiceDiscoverer; + +class CommonGrpcRequestBoundsAutoConfigurationTest { + private static final MethodDescriptor READ = + MethodDescriptor.newBuilder() + .setFullMethodName("test.Discovered/Read") + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + private final ApplicationContextRunner runner = + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonGrpcRequestBoundsAutoConfiguration.class, + GrpcServerFactoryAutoConfiguration.class, + GrpcServerAutoConfiguration.class)) + .withPropertyValues("spring.grpc.server.port=0", "spring.grpc.server.ssl.enabled=false") + .withUserConfiguration(DiscoveredServiceConfiguration.class); + + @Test + void productionAutoConfigurationDiscoversRegistersAndCallsRealServiceWithOrderedInterceptors() { + runner.run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerFactory.class) + .hasSingleBean(GrpcServerLifecycle.class); + assertThat(context.getBean(GrpcServiceDiscoverer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceDiscoverer.class); + assertThat(context.getBean(GrpcServiceConfigurer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceConfigurer.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle.getFactory()) + .isSameAs(context.getBean(BoundedGrpcServerFactory.class)); + assertThat(lifecycle.isRunning()).isTrue(); + var state = context.getBean(DiscoveryState.class); + assertThat(state.filtered).hasValue(1); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", lifecycle.getPort()) + .usePlaintext() + .build(); + try { + assertThat( + ClientCalls.blockingUnaryCall( + channel, + READ, + CallOptions.DEFAULT + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withCompression("gzip"), + Empty.getDefaultInstance())) + .isEqualTo(Empty.getDefaultInstance()); + assertThat(state.events).containsExactly("first", "second", "handler"); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + }); + } + + @Test + void realSpringBootAutoDiscoveryKeepsFrameworkSupportAndCanonicalGuardTogether() + throws Exception { + // Exercise classpath auto-configuration discovery rather than enumerating gRPC configurations. + // Core runtime composition is unrelated to this focused server registration proof. + try (var context = + new SpringApplicationBuilder(AutoDiscoveredBootApplication.class) + .web(WebApplicationType.NONE) + .registerShutdownHook(false) + .run( + "--spring.profiles.active=test", + "--spring.application.name=bounded-grpc-boot-test", + "--spring.grpc.server.port=0", + "--spring.grpc.server.ssl.enabled=false", + "--spring.main.banner-mode=off", + "--spring.autoconfigure.exclude=net.firedevops.firemud.common.config.CommonCoreAutoConfiguration," + + "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration")) { + assertThat(context.getBeansOfType(GrpcServerFactory.class)).hasSize(1); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(context.getBean(GrpcServiceDiscoverer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceDiscoverer.class); + assertThat(context.getBean(GrpcServiceConfigurer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceConfigurer.class); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle.isRunning()).isTrue(); + assertThat(lifecycle.getFactory()).isSameAs(context.getBean(BoundedGrpcServerFactory.class)); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", lifecycle.getPort()).usePlaintext().build(); + try { + assertThat( + ClientCalls.blockingUnaryCall( + channel, + READ, + CallOptions.DEFAULT + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withCompression("gzip"), + Empty.getDefaultInstance())) + .isEqualTo(Empty.getDefaultInstance()); + assertThat(context.getBean(DiscoveryState.class).events) + .containsExactly("first", "second", "handler"); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void explicitNoServerLifecycleBacksOffWithoutWeakeningFactoryDescriptorChecks() { + runner + .withUserConfiguration(NoGrpcServerTestConfiguration.class) + .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) + .run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerLifecycle.class) + .hasSingleBean(GrpcServerFactory.class) + .doesNotHaveBean("boundedGrpcServerLifecycle"); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); + verify(lifecycle, never()).start(); + var factory = context.getBean(GrpcServerFactory.class); + assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact registered descriptor"); + }); + } + + @Test + void alternateFactoryAndDuplicatePoliciesFailClosed() { + runner + .withBean("unguarded", GrpcServerFactory.class, () -> mock(GrpcServerFactory.class)) + .run(context -> assertThat(context).hasFailed()); + runner + .withBean("policyOne", GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::ordinary) + .withBean("policyTwo", GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::ordinary) + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void missingExceptionsUseOrdinaryCeilingAndUnknownOrUnboundedTransportCannotWidenIt() { + runner.run( + context -> + assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) + .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES)); + runner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=5MB") + .run(context -> assertThat(context).hasFailed()); + runner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=-1B") + .run(context -> assertThat(context).hasFailed()); + runner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=1MB") + .run(context -> assertThat(context).hasNotFailed()); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + @Import(DiscoveredServiceConfiguration.class) + static class AutoDiscoveredBootApplication {} + + static class DiscoveryState { + final List events = new CopyOnWriteArrayList<>(); + final AtomicInteger filtered = new AtomicInteger(); + } + + @Configuration(proxyBeanMethods = false) + static class DiscoveredServiceConfiguration { + @Bean + DiscoveryState discoveryState() { + return new DiscoveryState(); + } + + @Bean + DiscoveredService discoveredService(DiscoveryState state) { + return new DiscoveredService(state); + } + + @Bean + GrpcServerFactoryCustomizer serviceFilter(DiscoveryState state) { + return factory -> + ((DefaultGrpcServerFactory) factory) + .setServiceFilter( + (service, ignored) -> { + state.filtered.incrementAndGet(); + return true; + }); + } + + @Bean + @GlobalServerInterceptor + @Order(10) + ServerInterceptor firstInterceptor(DiscoveryState state) { + return interceptor(state, "first"); + } + + @Bean + @GlobalServerInterceptor + @Order(20) + ServerInterceptor secondInterceptor(DiscoveryState state) { + return interceptor(state, "second"); + } + } + + @GrpcService + static class DiscoveredService implements BindableService { + private final DiscoveryState state; + + DiscoveredService(DiscoveryState state) { + this.state = state; + } + + @Override + public ServerServiceDefinition bindService() { + return ServerServiceDefinition.builder("test.Discovered") + .addMethod( + READ, + ServerCalls.asyncUnaryCall( + (request, observer) -> { + state.events.add("handler"); + observer.onNext(Empty.getDefaultInstance()); + observer.onCompleted(); + })) + .build(); + } + } + + private static ServerInterceptor interceptor(DiscoveryState state, String name) { + return new ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + state.events.add(name); + return next.startCall(call, headers); + } + }; + } +} diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java index ed87ad4d05..5fcebb233d 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java @@ -4,6 +4,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.CertificateEncodingException; @@ -14,6 +15,8 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; /** Test-only PKI for loopback mTLS proofs. */ @@ -102,6 +105,34 @@ public Identity identity(String alias) { return identity; } + /** Creates fresh server key managers using the existing issued identity and CA chain. */ + public KeyManagerFactory keyManagerFactory(Identity identity) + throws GeneralSecurityException, IOException { + char[] password = STORE_PASSWORD.toCharArray(); + KeyStore store = KeyStore.getInstance("PKCS12"); + store.load(null, password); + store.setKeyEntry( + "identity", + identity.privateKey(), + password, + new X509Certificate[] {identity.certificate(), caCertificate}); + KeyManagerFactory factory = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + factory.init(store, password); + return factory; + } + + /** Creates fresh trust managers containing only this fixture's CA. */ + public TrustManagerFactory trustManagerFactory() throws GeneralSecurityException, IOException { + KeyStore store = KeyStore.getInstance("PKCS12"); + store.load(null, null); + store.setCertificateEntry("test-ca", caCertificate); + TrustManagerFactory factory = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + factory.init(store); + return factory; + } + public CommonGrpcClientProperties clientProperties(Path directory, Identity identity) throws IOException, CertificateEncodingException { Path clientDirectory = Files.createTempDirectory(directory, "loopback-mtls-client-"); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java index 07d7c5f2e1..d0f11b482a 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java @@ -4,6 +4,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; import java.time.Clock; +import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -350,7 +351,7 @@ EntityCharacterCreateTerminal settle(EntityCharacterCreateProofs proof, String a if (abortRequestId == null) { // Recheck expiry after every potentially blocking lock and immediately before // allocation. - requireCurrentAuthority(proof); + requireCurrentAuthority(action.expectedVersion().connectScopeExpiresAt()); if (!tx.fetch( "SELECT character_uuid FROM characters WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", tenant, @@ -361,7 +362,7 @@ EntityCharacterCreateTerminal settle(EntityCharacterCreateProofs proof, String a .withDescription("PLAYER_CREATED roster is not empty") .asRuntimeException(); } - requireCurrentAuthority(proof); + requireCurrentAuthority(action.expectedVersion().connectScopeExpiresAt()); character = UUID.randomUUID(); String core = action.mutation().authoredSource().core().canonicalJson(); int inserted = @@ -419,10 +420,10 @@ EntityCharacterCreateTerminal settle(EntityCharacterCreateProofs proof, String a }); } - private void requireCurrentAuthority(EntityCharacterCreateProofs proof) { + private void requireCurrentAuthority(Instant connectScopeExpiresAt) { // This is Entity's local admission deadline. Remote observation/acquisition timestamps remain // exact retained owner values and are never compared with Entity's clock. - if (!clock.instant().isBefore(proof.action().expectedVersion().connectScopeExpiresAt())) { + if (!clock.instant().isBefore(connectScopeExpiresAt)) { throw Status.FAILED_PRECONDITION .withDescription("Original creation authority expired; no abort inferred") .asRuntimeException(); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java index df9953ec78..4889ca0843 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.entitymanagement.v1.CanonicalPlayerCreatedRosterResponse; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementResponse; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationRequest; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementConfirmationResponse; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest; import net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceResponse; @@ -1974,8 +1975,27 @@ public java.util.List retirementTransfers(UUID after, int li ? null : CanonicalGameplayRosterRetirementAcknowledgementRequest.parseFrom( row.get("acknowledgement_request", byte[].class)); + var acknowledgement = + row.get("acknowledgement_response", byte[].class) == null + ? null + : CanonicalGameplayRosterRetirementAcknowledgementResponse.parseFrom( + row.get("acknowledgement_response", byte[].class)); + if ((acknowledgement != null && request == null) + || (request == null + && !"WAITING_RETIREMENT".equals(row.get("transfer_state", String.class))) + || (acknowledgement == null + && "ACKNOWLEDGED".equals(row.get("transfer_state", String.class)))) { + throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_INVALID"); + } if (request != null) { - CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(request); + // Each fresh retained row is fully validated once. The guarded response + // validator also computes and binds this same immutable request digest. + String requestDigest = + acknowledgement == null + ? CanonicalGameplayRosterRetirementEvidence.requestDigest(request) + : CanonicalGameplayRosterRetirementEvidence + .requireAcknowledgementResponse(request, acknowledgement) + .getRequestDigest(); if (!request.getOriginalSelection().equals(original) || !request .getObservationUuid() @@ -2004,27 +2024,12 @@ public java.util.List retirementTransfers(UUID after, int li || !Arrays.equals( request.getObservedRetirement().toByteArray(), row.get("observed_retirement", byte[].class)) - || !CanonicalGameplayRosterRetirementEvidence.requestDigest(request) - .equals(row.get("request_digest", String.class))) { + || !requestDigest.equals(row.get("request_digest", String.class))) { throw new IllegalStateException( "CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); } } - var acknowledgement = - row.get("acknowledgement_response", byte[].class) == null - ? null - : CanonicalGameplayRosterRetirementAcknowledgementResponse.parseFrom( - row.get("acknowledgement_response", byte[].class)); - if ((acknowledgement != null && request == null) - || (request == null - && !"WAITING_RETIREMENT".equals(row.get("transfer_state", String.class))) - || (acknowledgement == null - && "ACKNOWLEDGED".equals(row.get("transfer_state", String.class)))) { - throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_INVALID"); - } if (acknowledgement != null) { - CanonicalGameplayRosterRetirementEvidence.requireAcknowledgementResponse( - request, acknowledgement); Long effectiveMinimum = row.get("effective_minimum_retention_millis", Long.class); if (effectiveMinimum == null || acknowledgement.getMinimumRetentionMillis() != effectiveMinimum) { @@ -2189,9 +2194,14 @@ public boolean recordRetirementConfirmation( RetirementTransfer candidate, CanonicalGameplayRosterRetirementConfirmationResponse response) { requireOwnerTransaction(); + // The response guard validates the complete confirmation and nested proof once below; + // constructing the immutable envelope supplies no validation or retirement authority. var confirmation = - CanonicalGameplayRosterRetirementEvidence.confirmation( - candidate.acknowledgementRequest(), candidate.acknowledgement()); + CanonicalGameplayRosterRetirementConfirmationRequest.newBuilder() + .setSchemaVersion(1) + .setAcknowledgementRequest(candidate.acknowledgementRequest()) + .setAcknowledgement(candidate.acknowledgement()) + .build(); CanonicalGameplayRosterRetirementEvidence.requireConfirmationResponse(confirmation, response); Record retained = lockRetirementTransfer(candidate); if (!Arrays.equals( diff --git a/services/entity-management-service/src/main/resources/db/migration/V1021__character_create_binary_safe_immutability.sql b/services/entity-management-service/src/main/resources/db/migration/V1021__character_create_binary_safe_immutability.sql new file mode 100644 index 0000000000..e4bba7e9e2 --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1021__character_create_binary_safe_immutability.sql @@ -0,0 +1,18 @@ +-- Preserve exact immutable intent bytes without converting the full terminal to JSON. +/* [jooq ignore start] */ +CREATE OR REPLACE FUNCTION protect_entity_character_create_operation() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + immutable_new entity_character_create_operations%ROWTYPE; +BEGIN + immutable_new := NEW; + immutable_new.status := OLD.status; + immutable_new.terminal_bytes := OLD.terminal_bytes; + immutable_new.character_uuid := OLD.character_uuid; + IF OLD.status <> 'PENDING' OR NEW.status NOT IN ('COMMITTED', 'ABORTED') + OR immutable_new IS DISTINCT FROM OLD THEN + RAISE EXCEPTION 'CHARACTER_CREATE intent and terminal are immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 97a99b1b7e..5e2d3784d9 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -412,7 +412,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( .extracting(AppliedMigration::version) .containsExactly( "1006", "1007", "1008", "1009", "1010", "1011", "1012", "1014", "1015", "1016", "1017", - "1018", "1019", "1020"); + "1018", "1019", "1020", "1021"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -429,7 +429,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1017__player_created_actor_quarantine.sql", "V1018__canonical_roster_staged_retirement.sql", "V1019__canonical_roster_snapshot_retirement_seals.sql", - "V1020__canonical_roster_created_retirement_recognition.sql"); + "V1020__canonical_roster_created_retirement_recognition.sql", + "V1021__character_create_binary_safe_immutability.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index be8558940e..850495204d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -642,7 +642,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .extracting(migration -> migration.getVersion().getVersion()) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020"); + "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -667,9 +667,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1017__player_created_actor_quarantine.sql", "V1018__canonical_roster_staged_retirement.sql", "V1019__canonical_roster_snapshot_retirement_seals.sql", - "V1020__canonical_roster_created_retirement_recognition.sql"); + "V1020__canonical_roster_created_retirement_recognition.sql", + "V1021__character_create_binary_safe_immutability.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1020")); + .isEqualTo(MigrationVersion.fromVersion("1021")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -742,7 +743,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .extracting(MigrationHistoryEntry::version) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020"); + "1010", "1011", "1012", "1014", "1015", "1016", "1017", "1018", "1019", "1020", "1021"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -766,7 +767,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1017__player_created_actor_quarantine.sql", "V1018__canonical_roster_staged_retirement.sql", "V1019__canonical_roster_snapshot_retirement_seals.sql", - "V1020__canonical_roster_created_retirement_recognition.sql"); + "V1020__canonical_roster_created_retirement_recognition.sql", + "V1021__character_create_binary_safe_immutability.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1029,7 +1031,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1020")); + .isEqualTo(MigrationVersion.fromVersion("1021")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 25ff014fd2..0530ecd37b 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -119,7 +119,7 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { DSLContext upgradedDsl = DSL.using(parentDataSource, SQLDialect.POSTGRES); assertThat(migrationHistory(upgradedDsl).subList(0, parentHistory.size())) .containsExactlyElementsOf(parentHistory); - assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1020"); + assertThat(migrationVersions(upgradedDsl)).contains("1017").last().isEqualTo("1021"); assertThat(retainedParentRows(upgradedDsl, character, snapshot)) .containsExactlyElementsOf(retainedRows); assertThat( @@ -135,6 +135,69 @@ void upgradesActualEntity1014ParentWithoutChangingRetainedActorOrRosterRows() { } } + @Test + void binaryGuardUpgradePreservesCreatedRowsHistoryAndTerminalReplay() throws Exception { + String retainedSchema = "entity_binary_guard_" + UUID.randomUUID().toString().replace("-", ""); + try { + var retainedDataSource = dataSource(retainedSchema); + migrate(retainedDataSource, retainedSchema, "1014"); + var retainedDsl = DSL.using(retainedDataSource, SQLDialect.POSTGRES); + // The earlier retained-parent test covers the preseeded cohort separately. + // This schema keeps the declared-empty source census valid for the actual created writer. + migrate(retainedDataSource, retainedSchema, "1020"); + var retainedRepository = + new EntityCharacterCreateRepository(retainedDsl, Clock.fixed(NOW, ZoneOffset.UTC)); + var retainedSource = retainControlledSource(retainedDsl); + var retainedProof = proof(retainedSource, UUID.randomUUID(), UUID.randomUUID(), false, null); + var terminal = retainedRepository.settle(retainedProof, null); + UUID operation = UUID.fromString(retainedProof.original().getOperationId()); + String operationNamespace = retainedProof.action().scope().targetNamespace(); + String retainedRowsSql = + "SELECT 'actor:' || xmin::text || ':' || row_to_json(c)::text AS retained FROM characters c " + + "UNION ALL SELECT 'snapshot:' || xmin::text || ':' || row_to_json(s)::text FROM entity_canonical_gameplay_roster_snapshots s " + + "UNION ALL SELECT 'snapshot_actor:' || xmin::text || ':' || row_to_json(a)::text FROM entity_canonical_gameplay_roster_snapshot_actors a " + + "UNION ALL SELECT 'operation:' || xmin::text || ':' || row_to_json(o)::text FROM entity_character_create_operations o ORDER BY 1"; + List before = retainedDsl.fetch(retainedRowsSql).getValues(0, String.class); + String operationBefore = retainedOperationRow(retainedDsl, operationNamespace, operation); + List historyBefore = migrationHistory(retainedDsl); + + migrate(retainedDataSource, retainedSchema, null); + + assertThat(migrationHistory(retainedDsl).subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat(migrationVersions(retainedDsl)).last().isEqualTo("1021"); + assertThat(retainedDsl.fetch(retainedRowsSql).getValues(0, String.class)) + .containsExactlyElementsOf(before); + assertThat(retainedRepository.settle(retainedProof, null)).isEqualTo(terminal); + assertThat(retainedRepository.replay(retainedProof.request()).orElseThrow()) + .isEqualTo(terminal); + for (String change : + List.of( + "original_request = decode('01', 'hex')", + "terminal_bytes = decode('02', 'hex')", + "status = 'PENDING'")) { + assertThatThrownBy( + () -> + retainedDsl.execute( + "UPDATE entity_character_create_operations SET " + + change + + " WHERE target_namespace = ? AND operation_id = ?", + operationNamespace, + operation)) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + assertThat(retainedOperationRow(retainedDsl, operationNamespace, operation)) + .isEqualTo(operationBefore); + // The replacement also guards a new actual writer transition, not only old terminal replay. + var fresh = proof(retainedSource, UUID.randomUUID(), UUID.randomUUID(), false, null); + assertThat(retainedRepository.settle(fresh, null).getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED); + } finally { + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + retainedSchema + "\" CASCADE"); + } + } + @Test void quarantinesCreatedActorWithoutChangingProvenanceOrCurrentRosterAdmission() throws Exception { UUID accountId = UUID.randomUUID(); @@ -167,7 +230,7 @@ void upgradesRetainedV1016CreatedActorBeforeQuarantineWithoutChangingRows() thro migrate(retainedDataSource, retainedSchema, null); - assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1020"); + assertThat(migrationVersions(retainedDsl)).contains("1017").last().isEqualTo("1021"); assertThat(retainedRow(retainedDsl, "characters", "character_uuid", characterId)) .isEqualTo(actorBefore); assertThat( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java index 4a957778d2..d772c96b43 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java @@ -2217,6 +2217,40 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { CanonicalGameplayRosterRetirementEvidence.confirmation( acknowledged.acknowledgementRequest(), acknowledgement); var confirmed = CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation); + String retainedTransfer = + pageSourceRow( + "entity_canonical_roster_retirement_transfers", + "observation_uuid", + acknowledged.observationUuid()); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> + repository.recordRetirementConfirmation( + acknowledged, + confirmed.toBuilder().setRequestDigest("0".repeat(64)).build()))) + .isInstanceOf(IllegalArgumentException.class); + var changedRequest = + acknowledged.acknowledgementRequest().toBuilder().setSnapshotDigest("0".repeat(64)).build(); + var changedCandidate = + new CanonicalGameplayRosterRetentionRepository.RetirementTransfer( + acknowledged.observationUuid(), + acknowledged.state(), + acknowledged.original(), + changedRequest, + acknowledged.acknowledgement()); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + ignored -> + repository.recordRetirementConfirmation(changedCandidate, confirmed))) + .isInstanceOf(IllegalArgumentException.class); + assertThat( + pageSourceRow( + "entity_canonical_roster_retirement_transfers", + "observation_uuid", + acknowledged.observationUuid())) + .isEqualTo(retainedTransfer); transaction.executeWithoutResult( ignored -> assertThat(repository.recordRetirementConfirmation(acknowledged, confirmed)).isTrue()); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index 8529fc4a0b..ea1a70379e 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -106,7 +106,7 @@ void seedLegacyRowsBeforeV1011() { dsl.fetchSingle( "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") .get(0, String.class)) - .isEqualTo("1020"); + .isEqualTo("1021"); } @AfterEach diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java index 1ac569f344..94efeb2018 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java @@ -114,6 +114,13 @@ public AuthenticatedSource readAuthenticatedSource() { */ public synchronized EntityCharacterCreateTerminal createActor( UUID account, UUID operation, String displayName) throws Exception { + return createActor(account, operation, displayName, false); + } + + /** Fills the bounded known opaque proof fields while retaining the actual writer and bindings. */ + public synchronized EntityCharacterCreateTerminal createActor( + UUID account, UUID operation, String displayName, boolean maximumKnownOpaqueFields) + throws Exception { EntityCharacterCreateBindings.id(Objects.requireNonNull(account, "account").toString()); EntityCharacterCreateBindings.id(Objects.requireNonNull(operation, "operation").toString()); AuthenticatedSource source = readAuthenticatedSource(); @@ -145,7 +152,8 @@ public synchronized EntityCharacterCreateTerminal createActor( inputs.worldInventoryReadEvidence().request().freezeEvidence()); sourceReceipt = sourceIntakes.retainFresh(inputs, digest); } - EntityCharacterCreateProofs proof = createProof(sourceReceipt, account, operation, source); + EntityCharacterCreateProofs proof = + createProof(sourceReceipt, account, operation, source, maximumKnownOpaqueFields); return characterCreateRepository.settle(proof, null); } @@ -181,7 +189,8 @@ private static EntityCharacterCreateProofs createProof( EntityEmptySelectedSourceIntakeReceipt entitySource, UUID accountId, UUID operationId, - AuthenticatedSource rosterSource) + AuthenticatedSource rosterSource, + boolean maximumKnownOpaqueFields) throws Exception { CharacterCreateOperatorAction action = rosterSourceAction(entitySource, accountId, rosterSource); @@ -198,7 +207,9 @@ private static EntityCharacterCreateProofs createProof( .setOriginalAction(ByteString.copyFrom(actionBytes)) .setMutationDigest(CharacterCreateOperatorActionCodec.mutationDigest(action)) .setOriginalSourceReadback( - ByteString.copyFromUtf8("controlled-upstream-source-readback")) + maximumKnownOpaqueFields + ? opaque(32 * 1024 * 1024, 301) + : ByteString.copyFromUtf8("controlled-upstream-source-readback")) .build(); ReadOriginalCharacterCreateRequest reference = ReadOriginalCharacterCreateRequest.newBuilder() @@ -222,15 +233,23 @@ private static EntityCharacterCreateProofs createProof( .setAccountProtectionId(accountProtection.getProtectionId()) .setAccountProtectionFence(accountProtection.getProtectionFence()) .setAcquiredAt(readAt.toString()) - .setOriginalMembershipSnapshot(ByteString.copyFromUtf8("controlled-membership")) - .setOriginalEntitlementSnapshot(ByteString.copyFromUtf8("controlled-entitlement")) + .setOriginalMembershipSnapshot( + maximumKnownOpaqueFields + ? opaque(1024 * 1024, 302) + : ByteString.copyFromUtf8("controlled-membership")) + .setOriginalEntitlementSnapshot( + maximumKnownOpaqueFields + ? opaque(1024 * 1024, 303) + : ByteString.copyFromUtf8("controlled-entitlement")) .build(); var gameSession = new GameSessionCharacterCreateProtectionReader.Readback( account, gameSessionProtection, readAt.plusSeconds(1).toString(), - ByteString.copyFromUtf8("controlled-Game-Session-protection-readback")); + maximumKnownOpaqueFields + ? opaque(48 * 1024 * 1024, 304) + : ByteString.copyFromUtf8("controlled-Game-Session-protection-readback")); var world = WorldCharacterCreateLifecycleProtection.newBuilder() .setAccountProtection(account) @@ -245,6 +264,20 @@ private static EntityCharacterCreateProofs createProof( request, original, account, gameSession, world, entitySource); } + /** Uses the same seeded chunked high-entropy construction as the Common transport vector. */ + private static ByteString opaque(int size, long seed) { + var random = new java.util.Random(seed); + byte[] chunk = new byte[64 * 1024]; + var output = ByteString.newOutput(chunk.length); + for (int remaining = size; remaining > 0; ) { + int count = Math.min(remaining, chunk.length); + random.nextBytes(chunk); + output.write(chunk, 0, count); + remaining -= count; + } + return output.toByteString(); + } + /** * Rebinds only the controlled World lifecycle read correlation to the creation operation. The * authenticated source's target, complete launch binding, and lifecycle facts remain intact. diff --git a/services/game-session-service/build.gradle.kts b/services/game-session-service/build.gradle.kts index c6c6550d74..dcd05e7cae 100644 --- a/services/game-session-service/build.gradle.kts +++ b/services/game-session-service/build.gradle.kts @@ -80,6 +80,7 @@ dependencies { testFixturesImplementation(project(":common-data-runtime")) testFixturesImplementation(libs.jooq) testFixturesImplementation(libs.flyway.core) + testFixturesImplementation(libs.flyway.database.postgresql) testFixturesImplementation(platform(libs.spring.boot.dependencies)) testFixturesImplementation("com.fasterxml.jackson.core:jackson-databind") testFixturesImplementation(libs.spring.boot.starter.actuator) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java index bb0d2ae0ee..8d11811c82 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClient.java @@ -39,6 +39,8 @@ public final class CanonicalPlayerCreatedRosterClient extends AbstractReloadingBlockingGrpcClient< CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub> { + private static final long PLAYER_CREATED_OUTER_RPC_SECONDS = 20L; + private final String namespace; private final CanonicalGameplayRosterReferenceOwner owner; @@ -136,7 +138,7 @@ public VerifiedPlayerCreatedRoster listPlayerCreatedRoster( CanonicalPlayerCreatedRosterEvidence.requireResponse( request, current - .withDeadlineAfter(5L, TimeUnit.SECONDS) + .withDeadlineAfter(PLAYER_CREATED_OUTER_RPC_SECONDS, TimeUnit.SECONDS) .withMaxInboundMessageSize( CanonicalPlayerCreatedRosterEvidence.MAX_ROSTER_RECEIPT_BYTES) .listPlayerCreatedRoster(request)); @@ -204,7 +206,7 @@ public VerifiedPlayerCreatedCharacter readSelectedPlayerCreatedCharacter( } else { response = requireStub() - .withDeadlineAfter(5L, TimeUnit.SECONDS) + .withDeadlineAfter(PLAYER_CREATED_OUTER_RPC_SECONDS, TimeUnit.SECONDS) .withMaxInboundMessageSize( CanonicalPlayerCreatedRosterEvidence.MAX_SELECTED_RECEIPT_BYTES) .readSelectedPlayerCreatedCharacter(request); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfiguration.java new file mode 100644 index 0000000000..cd3cd0d7ea --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfiguration.java @@ -0,0 +1,25 @@ +package net.firedevops.firemud.gamesession.config; + +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.boot.grpc.server.autoconfigure.ConditionalOnGrpcServerEnabled; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration(proxyBeanMethods = false) +public class GameSessionGrpcRequestByteConfiguration { + @Bean + public GrpcRequestBytePolicy gameSessionGrpcRequestBytePolicy() { + return GrpcRequestBytePolicy.createdRosterRetirement(); + } + + @Bean + @ConditionalOnGrpcServerEnabled + SmartInitializingSingleton requireGameSessionBoundedGrpcServerFactory( + BoundedGrpcServerFactory factory) { + // A required typed bean dependency prevents plain Spring factory fallback if shared + // request-bound auto-configuration is accidentally omitted or excluded. + return () -> java.util.Objects.requireNonNull(factory); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1022__canonical_roster_binary_safe_recovery_guard.sql b/services/game-session-service/src/main/resources/db/migration/V1022__canonical_roster_binary_safe_recovery_guard.sql new file mode 100644 index 0000000000..ca40da7f77 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1022__canonical_roster_binary_safe_recovery_guard.sql @@ -0,0 +1,109 @@ +-- Preserve recovery scheduling checks without materializing retained binary receipts as JSON. +/* [jooq ignore start] */ +CREATE OR REPLACE FUNCTION guard_game_session_canonical_roster_selection() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE + immutable_new game_session_canonical_roster_selection%ROWTYPE; +BEGIN + IF TG_OP = 'UPDATE' THEN + immutable_new := NEW; + immutable_new.recovery_last_attempt_at := OLD.recovery_last_attempt_at; + END IF; + IF TG_OP = 'DELETE' AND EXISTS (SELECT 1 FROM game_session_canonical_roster_target_fences f + WHERE f.target_fence_uuid = OLD.target_fence_uuid AND f.fence_state = 'RETIRED' + AND f.retired_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp()) THEN + RETURN OLD; + END IF; + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'roster original selection dependencies remain protected' USING ERRCODE = '23514'; + END IF; + PERFORM 1 FROM game_session_canonical_roster_target_fences + WHERE target_fence_uuid = NEW.target_fence_uuid AND owner_fence = NEW.owner_fence + AND fence_state = 'ACTIVE' FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'roster target fence is sealed against new and recovered references' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.canonical_roster_receipt IS NOT NULL OR NEW.canonical_player_created_roster_receipt IS NOT NULL OR NEW.receipt_recorded_at IS NOT NULL + OR NEW.selection_input IS NOT NULL OR NEW.selected_character_uuid IS NOT NULL + OR NEW.canonical_selected_assignment_receipt IS NOT NULL OR NEW.canonical_selected_player_created_character_receipt IS NOT NULL OR NEW.roster_read_started + OR NEW.terminal_outcome IS NOT NULL OR NEW.recovery_uuid IS NOT NULL + OR NEW.recovery_started_at IS NOT NULL OR NEW.recovery_last_attempt_at IS NOT NULL OR NEW.recovery_receipt IS NOT NULL THEN + RAISE EXCEPTION 'roster selection must reserve before owner read' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.recovery_uuid IS NULL AND NEW.recovery_uuid IS NOT NULL THEN + IF OLD.terminal_outcome IS NOT NULL OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_roster_target_fences f + WHERE f.target_fence_uuid = OLD.target_fence_uuid + AND OLD.recorded_at + f.replay_horizon_millis * interval '1 millisecond' <= clock_timestamp()) + OR ROW(NEW.selection_input, NEW.selected_character_uuid, NEW.canonical_selected_assignment_receipt, NEW.canonical_selected_player_created_character_receipt, + NEW.roster_read_started, NEW.canonical_roster_receipt, NEW.canonical_player_created_roster_receipt, NEW.receipt_recorded_at, NEW.terminal_outcome, NEW.terminal_at, NEW.recovery_receipt) + IS DISTINCT FROM ROW(OLD.selection_input, OLD.selected_character_uuid, OLD.canonical_selected_assignment_receipt, OLD.canonical_selected_player_created_character_receipt, + OLD.roster_read_started, OLD.canonical_roster_receipt, OLD.canonical_player_created_roster_receipt, OLD.receipt_recorded_at, OLD.terminal_outcome, OLD.terminal_at, OLD.recovery_receipt) THEN + RAISE EXCEPTION 'roster recovery must fence the unchanged original after its stored replay horizon' USING ERRCODE = '23514'; + END IF; + END IF; + IF (OLD.recovery_uuid IS NOT NULL AND ( + ROW(NEW.recovery_uuid, NEW.recovery_started_at, NEW.selection_input, NEW.selected_character_uuid, + NEW.canonical_selected_assignment_receipt, NEW.canonical_selected_player_created_character_receipt, NEW.roster_read_started) + IS DISTINCT FROM ROW(OLD.recovery_uuid, OLD.recovery_started_at, OLD.selection_input, OLD.selected_character_uuid, + OLD.canonical_selected_assignment_receipt, OLD.canonical_selected_player_created_character_receipt, OLD.roster_read_started) + OR (NEW IS DISTINCT FROM OLD AND NOT ( + (NEW.recovery_receipt IS NOT NULL AND NEW.terminal_outcome = 'DENIED') + OR (OLD.terminal_outcome IS NULL AND NEW.terminal_outcome IS NULL + AND NEW.recovery_last_attempt_at IS DISTINCT FROM OLD.recovery_last_attempt_at + AND NEW.recovery_last_attempt_at IS NOT NULL + AND (OLD.recovery_last_attempt_at IS NULL + OR NEW.recovery_last_attempt_at > OLD.recovery_last_attempt_at) + AND immutable_new IS NOT DISTINCT FROM OLD))) + OR (NEW.recovery_last_attempt_at IS DISTINCT FROM OLD.recovery_last_attempt_at + AND NOT (OLD.terminal_outcome IS NULL AND NEW.terminal_outcome IS NULL + AND NEW.recovery_last_attempt_at IS NOT NULL + AND (OLD.recovery_last_attempt_at IS NULL + OR NEW.recovery_last_attempt_at > OLD.recovery_last_attempt_at) + AND immutable_new IS NOT DISTINCT FROM OLD)))) + OR (OLD.recovery_receipt IS NOT NULL AND NEW.recovery_receipt IS DISTINCT FROM OLD.recovery_receipt) + OR (OLD.recovery_uuid IS NULL AND NEW.recovery_uuid IS NULL + AND ROW(NEW.recovery_started_at, NEW.recovery_receipt) IS DISTINCT FROM ROW(OLD.recovery_started_at, OLD.recovery_receipt)) THEN + RAISE EXCEPTION 'roster recovery fence and positive closure cannot be replaced' USING ERRCODE = '23514'; + END IF; + IF ROW(NEW.operation_uuid, NEW.original_request, NEW.owner_fence, NEW.recorded_at, NEW.target_fence_uuid, NEW.entry_policy) + IS DISTINCT FROM ROW(OLD.operation_uuid, OLD.original_request, OLD.owner_fence, OLD.recorded_at, OLD.target_fence_uuid, OLD.entry_policy) + OR (OLD.roster_read_started AND NOT NEW.roster_read_started) + OR (OLD.terminal_outcome IS NOT NULL + AND ROW(NEW.terminal_outcome, NEW.terminal_at) IS DISTINCT FROM ROW(OLD.terminal_outcome, OLD.terminal_at)) + OR (OLD.terminal_outcome IS NOT NULL AND NEW IS DISTINCT FROM OLD) + OR (OLD.selection_input IS NOT NULL AND NEW.selection_input IS DISTINCT FROM OLD.selection_input) + OR (OLD.selection_input IS NULL AND (OLD.canonical_roster_receipt IS NOT NULL OR OLD.canonical_player_created_roster_receipt IS NOT NULL) AND NEW.selection_input IS NOT NULL) + OR (OLD.selected_character_uuid IS NOT NULL AND NEW.selected_character_uuid IS DISTINCT FROM OLD.selected_character_uuid) + OR (OLD.canonical_selected_assignment_receipt IS NOT NULL + AND NEW.canonical_selected_assignment_receipt IS DISTINCT FROM OLD.canonical_selected_assignment_receipt) + OR (OLD.canonical_selected_player_created_character_receipt IS NOT NULL + AND NEW.canonical_selected_player_created_character_receipt IS DISTINCT FROM OLD.canonical_selected_player_created_character_receipt) + OR (OLD.canonical_player_created_roster_receipt IS NOT NULL + AND ROW(NEW.canonical_player_created_roster_receipt, NEW.receipt_recorded_at) + IS DISTINCT FROM ROW(OLD.canonical_player_created_roster_receipt, OLD.receipt_recorded_at)) + OR (OLD.canonical_roster_receipt IS NOT NULL + AND ROW(NEW.canonical_roster_receipt, NEW.receipt_recorded_at) + IS DISTINCT FROM ROW(OLD.canonical_roster_receipt, OLD.receipt_recorded_at)) THEN + RAISE EXCEPTION 'original roster selection cannot be replaced or reopened' USING ERRCODE = '23514'; + END IF; + IF OLD.terminal_outcome IS NULL AND NEW.terminal_outcome IS NOT NULL + AND NOT (NEW.recovery_uuid IS NOT NULL AND NEW.recovery_receipt IS NOT NULL AND NEW.terminal_outcome = 'DENIED') + AND NOT (NEW.terminal_outcome = 'DENIED' AND NOT NEW.roster_read_started + AND NEW.canonical_roster_receipt IS NULL AND NEW.canonical_player_created_roster_receipt IS NULL + AND NEW.selected_character_uuid IS NULL AND NEW.recovery_uuid IS NULL) + AND (NEW.selection_input IS NULL + OR (NEW.roster_read_started AND NEW.canonical_roster_receipt IS NULL AND NEW.canonical_player_created_roster_receipt IS NULL) + OR (NEW.selected_character_uuid IS NOT NULL AND NEW.canonical_selected_assignment_receipt IS NULL AND NEW.canonical_selected_player_created_character_receipt IS NULL) + OR (NEW.terminal_outcome = 'SELECTED' AND NEW.canonical_selected_assignment_receipt IS NULL AND NEW.canonical_selected_player_created_character_receipt IS NULL) + OR (NEW.terminal_outcome = 'MENU' AND (NEW.selected_character_uuid IS NOT NULL + OR (NEW.canonical_roster_receipt IS NULL AND NEW.canonical_player_created_roster_receipt IS NULL)))) THEN + RAISE EXCEPTION 'roster terminal outcome requires its exact policy receipts or positive recovery' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +/* [jooq ignore stop] */ 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 626b7403db..4d5e11a1e6 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 @@ -86,6 +86,7 @@ class GameSessionApplicationIntegrationTest { @DynamicPropertySource static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); PostgresBackedServiceTestSupport.registerPostgresService( registry, postgres, "game_session_service"); PostgresBackedServiceTestSupport.registerRedisService(registry, redis); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java index dd6d82d0ee..ab999a9a45 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -2,46 +2,54 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.BindableService; -import io.grpc.CallOptions; -import io.grpc.ClientCall; -import io.grpc.ManagedChannel; -import io.grpc.MethodDescriptor; +import io.grpc.Context; +import io.grpc.Metadata; import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; import io.grpc.ServerInterceptors; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; -import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; -import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; -import java.net.InetSocketAddress; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Clock; import java.time.Duration; +import java.time.Instant; import java.util.ArrayDeque; +import java.util.List; import java.util.Map; -import java.util.Set; import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLException; 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.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; import net.firedevops.firemud.entitymanagement.charactercreate.ControlledPlayerCreatedOwnerStoreFixture; import net.firedevops.firemud.entitymanagement.charactercreate.EntityPlayerCreatedRosterSourceClient; import net.firedevops.firemud.entitymanagement.client.GameSessionCanonicalGameplayRosterOwnerReadClient; +import net.firedevops.firemud.entitymanagement.repository.CanonicalGameplayRosterRetentionRepository; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRetentionPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterRetentionService; import net.firedevops.firemud.entitymanagement.testing.ControlledPlayerCreatedRosterSourceFixture; import net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.EntityCharacterCreateOutcome; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterClient; import net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient; import net.firedevops.firemud.gamesession.client.CanonicalPlayerCreatedRosterClient; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayRosterReferenceRepository.SelectionOutcome; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner; import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferencePolicy; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterSelectionService; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayRosterOwnerReadGrpcAdapter; import net.firedevops.firemud.gamesession.testing.ControlledPlayerCreatedOriginalOwnerFixture; import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; @@ -49,16 +57,19 @@ import net.firedevops.firemud.shared.v1.PlayerExecutionContext; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import net.firedevops.firemud.test.TestContainerImages; +import org.awaitility.Awaitility; import org.flywaydb.core.Flyway; import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.support.StaticListableBeanFactory; 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; @@ -66,21 +77,22 @@ /** * Real owner stores and authenticated transports with explicitly controlled upstream authority. * This does not establish genuine Account ingress, production PKI, registration or player - * admission, nor the production five-second RPC latency budget. + * admission, nor production latency qualification. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") class PlayerCreatedRosterOwnerCompositionIntegrationTest { private static final String NAMESPACE = "test"; private static final Duration RETENTION = Duration.ofSeconds(20); - private static final long COUPLED_OWNER_TEST_RPC_SECONDS = 30L; - private static final Set COUPLED_OWNER_TEST_RPCS = - Set.of( - CanonicalGameplayRosterServiceGrpc.SERVICE_NAME + "/ListPlayerCreatedRoster", - CanonicalGameplayRosterServiceGrpc.SERVICE_NAME + "/ReadSelectedPlayerCreatedCharacter", - CharacterCreatePublicSourceServiceGrpc.SERVICE_NAME + "/ReadPlayerCreatedRosterSource", - CanonicalGameplayRosterOwnerReadServiceGrpc.SERVICE_NAME - + "/GetCanonicalGameplayRosterReference"); + private static final String LIST_RPC = + CanonicalGameplayRosterServiceGrpc.SERVICE_NAME + "/ListPlayerCreatedRoster"; + private static final String SELECTED_RPC = + CanonicalGameplayRosterServiceGrpc.SERVICE_NAME + "/ReadSelectedPlayerCreatedCharacter"; + private static final String SOURCE_RPC = + CharacterCreatePublicSourceServiceGrpc.SERVICE_NAME + "/ReadPlayerCreatedRosterSource"; + private static final String ORIGINAL_RPC = + CanonicalGameplayRosterOwnerReadServiceGrpc.SERVICE_NAME + + "/GetCanonicalGameplayRosterReference"; @Container static PostgreSQLContainer postgres = @@ -116,12 +128,41 @@ void actualCreatedTerminalCrossesAuthenticatedOwnersAndReplaysTheImmutableOrigin .resolvePlayerCreatedRosterSource(owners.gs.wireFixture().request()); var context = owners.context(account); owners.roster.reserveSelectionInput(source, context, null, null, null); + int sourceReadsBeforeList = owners.gs.controlledWorldLifecycleReadCount(); + int sourceRpcBeforeList = owners.rpcCount(SOURCE_RPC); + int originalRpcBeforeList = owners.rpcCount(ORIGINAL_RPC); + long listStarted = System.nanoTime(); var menu = owners.roster.listPlayerCreatedRoster(source, context); + long listMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - listStarted); + assertThat(listMillis).isLessThan(TimeUnit.SECONDS.toMillis(20)); + // The reserved original is requalified locally, on Entity's original-owner read, + // and on Entity's independent current-source read. + assertThat(owners.gs.controlledWorldLifecycleReadCount() - sourceReadsBeforeList) + .isEqualTo(3); + assertThat(owners.rpcCount(SOURCE_RPC) - sourceRpcBeforeList).isEqualTo(1); + assertThat(owners.rpcCount(ORIGINAL_RPC) - originalRpcBeforeList).isEqualTo(1); + owners.requireDeadline(LIST_RPC, 20); + owners.requireDeadline(SOURCE_RPC, 5); + owners.requireDeadline(ORIGINAL_RPC, 10); assertThat(menu.actors()).hasSize(1); assertThat(menu.actors().getFirst().getDisplayName()).isEqualTo(displayName); assertThat(menu.actors().getFirst().getCharacterUuid()).isEqualTo(terminal.getCharacterId()); var selectedContext = context.toBuilder().setCharacterId(terminal.getCharacterId()).build(); + int sourceReadsBeforeSelected = owners.gs.controlledWorldLifecycleReadCount(); + int sourceRpcBeforeSelected = owners.rpcCount(SOURCE_RPC); + int originalRpcBeforeSelected = owners.rpcCount(ORIGINAL_RPC); + long selectedStarted = System.nanoTime(); var selected = owners.roster.readSelectedPlayerCreatedCharacter(menu, selectedContext); + long selectedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - selectedStarted); + assertThat(selectedMillis).isLessThan(TimeUnit.SECONDS.toMillis(20)); + // Selection repeats the Entity current-source read; the completed original replays. + assertThat(owners.gs.controlledWorldLifecycleReadCount() - sourceReadsBeforeSelected) + .isEqualTo(1); + assertThat(owners.rpcCount(SOURCE_RPC) - sourceRpcBeforeSelected).isEqualTo(1); + assertThat(owners.rpcCount(ORIGINAL_RPC) - originalRpcBeforeSelected).isEqualTo(1); + owners.requireDeadline(SELECTED_RPC, 20); + owners.requireDeadline(SOURCE_RPC, 5); + owners.requireDeadline(ORIGINAL_RPC, 10); assertThat(selected.creationOperationUuid()).isEqualTo(creation); assertThat(selected.terminal()).isEqualTo(terminal); owners.roster.completeSelection(source, context, SelectionOutcome.SELECTED); @@ -167,11 +208,364 @@ void actualCreatedTerminalCrossesAuthenticatedOwnersAndReplaysTheImmutableOrigin } } + @Test + void completeOneActorSelectionMeasuresActualCreatedOwnerEntrypoint() throws Exception { + try (var owners = new Owners(directory)) { + UUID account = UUID.randomUUID(); + UUID creation = UUID.randomUUID(); + String displayName = + new net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection + .AuthoredCore( + owners + .gs + .wireFixture() + .authored() + .projections() + .getFirst() + .core() + .canonicalJson()) + .displayName(); + boolean maximum = Boolean.getBoolean("firemud.player-created.maximum-known-fields"); + var terminal = owners.entity.createActor(account, creation, displayName, maximum); + var preseeded = mock(CanonicalGameplayRosterClient.class); + var selection = + new CanonicalGameplayRosterSelectionService( + owners.gs.routeReader(), + owners.gs.publishedRouteReader(), + preseeded, + owners.gs.sourceReader(), + owners.roster); + var context = owners.context(account); + int sourceReadsBefore = owners.gs.controlledWorldLifecycleReadCount(); + int sourceRpcsBefore = owners.rpcCount(SOURCE_RPC); + int originalRpcsBefore = owners.rpcCount(ORIGINAL_RPC); + int listRpcsBefore = owners.rpcCount(LIST_RPC); + int selectedRpcsBefore = owners.rpcCount(SELECTED_RPC); + long started = System.nanoTime(); + var result = selection.select(context, null, null); + long elapsedNanos = System.nanoTime() - started; + assertThat(result) + .isInstanceOf( + CanonicalGameplayRosterSelectionService.SelectedPlayerCreatedOwnerReference.class); + var selected = + (CanonicalGameplayRosterSelectionService.SelectedPlayerCreatedOwnerReference) result; + assertThat(selected.ordinal()).isEqualTo(1); + assertThat(selected.displayName()).isEqualTo(displayName); + assertThat(selected.ownerReference().selectedCharacterUuid()) + .isEqualTo(UUID.fromString(terminal.getCharacterId())); + assertThat(selected.ownerReference().creationOperationUuid()).isEqualTo(creation); + assertThat(selected.ownerReference().terminal()).isEqualTo(terminal); + var originalRequest = selected.ownerReference().roster().originalSelection(); + var retained = owners.gs.referenceOwner().read(originalRequest); + assertThat(retained.getTerminalOutcome()).isEqualTo("SELECTED"); + assertThat(CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(retained)) + .isEqualTo(selected.ownerReference().roster().response()); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + retained)) + .isEqualTo(selected.ownerReference().response()); + byte[] originalBytes = retained.toByteArray(); + // Initial source, reserve, list recheck, original-owner read, Entity list source, + // post-list freshness, Entity selected source, and post-selected freshness are independent. + int fullSourceReads = owners.gs.controlledWorldLifecycleReadCount() - sourceReadsBefore; + assertThat(fullSourceReads).isEqualTo(8); + assertThat(owners.rpcCount(SOURCE_RPC) - sourceRpcsBefore).isEqualTo(2); + assertThat(owners.rpcCount(ORIGINAL_RPC) - originalRpcsBefore).isEqualTo(2); + assertThat(owners.rpcCount(LIST_RPC) - listRpcsBefore).isEqualTo(1); + assertThat(owners.rpcCount(SELECTED_RPC) - selectedRpcsBefore).isEqualTo(1); + assertThat(elapsedNanos).isPositive(); + System.out.printf( + "Created full selection: elapsedSeconds=%.3f completeSourceReads=%d sourceRpc=%d originalRpc=%d listRpc=%d selectedRpc=%d%n", + elapsedNanos / 1_000_000_000.0, + fullSourceReads, + owners.rpcCount(SOURCE_RPC) - sourceRpcsBefore, + owners.rpcCount(ORIGINAL_RPC) - originalRpcsBefore, + owners.rpcCount(LIST_RPC) - listRpcsBefore, + owners.rpcCount(SELECTED_RPC) - selectedRpcsBefore); + verifyNoInteractions(preseeded); + + var replay = selection.select(context, null, null); + assertThat(replay) + .isInstanceOf( + CanonicalGameplayRosterSelectionService.SelectedPlayerCreatedOwnerReference.class); + var replayed = + (CanonicalGameplayRosterSelectionService.SelectedPlayerCreatedOwnerReference) replay; + assertThat(replayed.ownerReference().terminal()).isEqualTo(terminal); + assertThat(owners.gs.referenceOwner().read(originalRequest).toByteArray()) + .containsExactly(originalBytes); + verifyNoInteractions(preseeded); + + // Current production source still names the issued target, so retirement first refuses. + assertThat(owners.gs.referenceOwner().retireTarget(originalRequest)).isFalse(); + Awaitility.await() + .atMost(Duration.ofSeconds(30)) + .untilAsserted( + () -> + assertThat( + owners + .gsDsl + .fetchSingle( + "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() FROM game_session_canonical_roster_selection s JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) WHERE s.operation_uuid = ?", + UUID.fromString(originalRequest.getOperationUuid())) + .get(0, Boolean.class)) + .isTrue()); + // Only the later successor reader is controlled. The original/fence/transfer SQL is real. + assertThat(owners.retireWithControlledSuccessor(originalRequest)).isTrue(); + var retired = owners.gs.referenceOwner().read(originalRequest); + CanonicalGameplayRosterReferenceEvidence.requireRetirement(retired); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + retired)) + .isEqualTo(selected.ownerReference().response()); + + var entityTransactions = + new TransactionTemplate(new DataSourceTransactionManager(owners.entityData)); + var retention = + new CanonicalGameplayRosterRetentionService( + owners.entity.retentionRepository(), + owners.originalClient, + entityTransactions, + new CanonicalGameplayRosterRetentionPolicy( + RETENTION, RETENTION, RETENTION, Duration.ofSeconds(1), 20), + new io.micrometer.core.instrument.simple.SimpleMeterRegistry()); + retention.sweep(); // Authenticated retired-original read and local observation. + assertThat( + owners + .entityDsl + .fetchSingle( + "SELECT owner_retirement_proof FROM entity_canonical_roster_retention_lifecycle WHERE snapshot_uuid = ?", + selected.ownerReference().roster().snapshotUuid()) + .get(0, byte[].class)) + .containsExactly(retired.toByteArray()); + // The bounded service cursor may require another page pass before preparing this snapshot. + List transfers = List.of(); + for (int pass = 0; pass < 5; pass++) { + retention.sweep(); + transfers = + entityTransactions.execute( + ignored -> owners.entity.retentionRepository().retirementTransfers(null, 20)); + if (transfers.size() == 1 && "ACKNOWLEDGED".equals(transfers.getFirst().state())) break; + } + assertThat(transfers).hasSize(1); + var transfer = transfers.getFirst(); + assertThat(transfer.valid()).isTrue(); + assertThat(transfer.state()).isEqualTo("ACKNOWLEDGED"); + var acknowledgementRequest = transfer.acknowledgementRequest(); + assertThat(acknowledgementRequest.getOriginalSelection()).isEqualTo(originalRequest); + assertThat(acknowledgementRequest.getObservedRetirement()).isEqualTo(retired); + assertThat(acknowledgementRequest.getSnapshotUuid()) + .isEqualTo(selected.ownerReference().roster().snapshotUuid().toString()); + assertThat(acknowledgementRequest.getSnapshotDigest()) + .isEqualTo(selected.ownerReference().roster().snapshotDigest()); + var admission = + owners.entityDsl.fetchSingle( + "SELECT admission_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", + UUID.fromString(originalRequest.getOperationUuid())); + assertThat(acknowledgementRequest.getAdmissionUuid()) + .isEqualTo(admission.get(0, UUID.class).toString()); + assertThat(acknowledgementRequest.getObservationUuid()) + .isEqualTo(transfer.observationUuid().toString()); + assertThat(transfer.acknowledgement().getRequestDigest()) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence.requestDigest(acknowledgementRequest)); + var gsTransfer = + owners.gsDsl.fetchSingle( + "SELECT observation_uuid, admission_uuid, snapshot_uuid, snapshot_digest, request_digest, acknowledgement_uuid, entity_principal FROM game_session_canonical_roster_retirement_transfers WHERE operation_uuid = ?", + UUID.fromString(originalRequest.getOperationUuid())); + assertThat(gsTransfer.get("observation_uuid", UUID.class)) + .isEqualTo(transfer.observationUuid()); + assertThat(gsTransfer.get("admission_uuid", UUID.class).toString()) + .isEqualTo(acknowledgementRequest.getAdmissionUuid()); + assertThat(gsTransfer.get("snapshot_uuid", UUID.class).toString()) + .isEqualTo(acknowledgementRequest.getSnapshotUuid()); + assertThat(gsTransfer.get("snapshot_digest", String.class)) + .isEqualTo(acknowledgementRequest.getSnapshotDigest()); + assertThat(gsTransfer.get("request_digest", String.class)) + .isEqualTo(transfer.acknowledgement().getRequestDigest()); + assertThat(gsTransfer.get("acknowledgement_uuid", UUID.class).toString()) + .isEqualTo(transfer.acknowledgement().getAcknowledgementUuid()); + assertThat(gsTransfer.get("entity_principal", String.class)) + .isEqualTo("spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service"); + var confirmationRequest = + CanonicalGameplayRosterRetirementEvidence.confirmation( + acknowledgementRequest, transfer.acknowledgement()); + // These trusted-CA peers reach the real GS listener but lack the exact Entity identity. + // Neither method may mutate the durable transfer before the valid confirmation. + if (!maximum) { + for (var deniedClient : + List.of(owners.wrongRoleOriginalClient, owners.wrongNamespaceOriginalClient)) { + assertThatThrownBy( + () -> + deniedClient.acknowledgeCanonicalGameplayRosterRetirement( + acknowledgementRequest)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThatThrownBy( + () -> + deniedClient.confirmCanonicalGameplayRosterRetirementAcknowledgement( + confirmationRequest)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + var unchangedTransfer = + owners.gsDsl.fetchSingle( + "SELECT observation_uuid, admission_uuid, snapshot_uuid, snapshot_digest, request_digest, acknowledgement_uuid, entity_principal, confirmed_at FROM game_session_canonical_roster_retirement_transfers WHERE operation_uuid = ?", + UUID.fromString(originalRequest.getOperationUuid())); + for (String field : + List.of( + "observation_uuid", + "admission_uuid", + "snapshot_uuid", + "snapshot_digest", + "request_digest", + "acknowledgement_uuid", + "entity_principal")) { + assertThat(unchangedTransfer.get(field)).isEqualTo(gsTransfer.get(field)); + } + assertThat(unchangedTransfer.get("confirmed_at")).isNull(); + } + } + var confirmation = + owners.originalClient.confirmCanonicalGameplayRosterRetirementAcknowledgement( + confirmationRequest); + assertThat(confirmation) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmationRequest)); + Boolean recordedConfirmation = + entityTransactions.execute( + ignored -> + owners + .entity + .retentionRepository() + .recordRetirementConfirmation(transfer, confirmation)); + assertThat(recordedConfirmation).isTrue(); + assertThat( + owners + .entityDsl + .fetchSingle( + "SELECT transfer_state, confirmation_response FROM entity_canonical_roster_retirement_transfers WHERE operation_uuid = ?", + UUID.fromString(originalRequest.getOperationUuid())) + .get("transfer_state", String.class)) + .isEqualTo("CONFIRMED"); + assertThat( + owners + .gsDsl + .fetchSingle( + "SELECT confirmed_at FROM game_session_canonical_roster_retirement_transfers WHERE operation_uuid = ?", + UUID.fromString(originalRequest.getOperationUuid())) + .get(0)) + .isNotNull(); + assertThat(owners.gs.referenceOwner().read(originalRequest)).isEqualTo(retired); + System.out.printf( + "Created actual-writer transfer: maximumKnownFields=%s terminalBytes=%d ackBytes=%d confirmationBytes=%d%n", + maximum, + terminal.getSerializedSize(), + acknowledgementRequest.getSerializedSize(), + confirmationRequest.getSerializedSize()); + } + } + + @Test + @EnabledIfSystemProperty(named = "firemud.player-created.maximum-known-fields", matches = "true") + void maximumKnownOpaqueFieldsCrossTheActualWriterAndBothOwners() throws Exception { + try (var owners = new Owners(directory)) { + UUID account = UUID.randomUUID(); + UUID creation = UUID.randomUUID(); + String displayName = + new net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection + .AuthoredCore( + owners + .gs + .wireFixture() + .authored() + .projections() + .getFirst() + .core() + .canonicalJson()) + .displayName(); + // The Account and World protections retain their exact structured owner response types. + // Only their legal opaque source/snapshot fields and GS readback reach their bounds. + var terminal = owners.entity.createActor(account, creation, displayName, true); + assertThat(terminal.getOutcome()) + .isEqualTo(EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED); + assertThat(terminal.getAccountOriginal().getOriginalSourceReadback().size()) + .isEqualTo(32 * 1024 * 1024); + var accountProof = + net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse.parseFrom( + terminal.getOriginalAccountProtection()); + assertThat(accountProof.getOriginal()).isEqualTo(terminal.getAccountOriginal()); + assertThat(terminal.getOriginalAccountProtection().size()).isGreaterThan(34 * 1024 * 1024); + assertThat(accountProof.getOriginalMembershipSnapshot().size()).isEqualTo(1024 * 1024); + assertThat(accountProof.getOriginalEntitlementSnapshot().size()).isEqualTo(1024 * 1024); + assertThat(terminal.getOriginalGameSessionProtection().size()).isEqualTo(48 * 1024 * 1024); + var worldProof = + net.firedevops.firemud.worldmanagement.v1.WorldCharacterCreateLifecycleProtection + .parseFrom(terminal.getOriginalWorldProtection()); + assertThat(worldProof.getAccountProtection()).isEqualTo(accountProof); + assertThat(terminal.getOriginalWorldProtection().size()).isGreaterThan(34 * 1024 * 1024); + assertThat(terminal.getSerializedSize()).isGreaterThan(140 * 1024 * 1024); + var source = + owners + .gs + .sourceReader() + .resolvePlayerCreatedRosterSource(owners.gs.wireFixture().request()); + var context = owners.context(account); + owners.roster.reserveSelectionInput(source, context, null, null, null); + long listStarted = System.nanoTime(); + var menu = owners.roster.listPlayerCreatedRoster(source, context); + long listNanos = System.nanoTime() - listStarted; + assertThat(menu.actors()).hasSize(1); + assertThat(menu.actors().getFirst().getCharacterUuid()).isEqualTo(terminal.getCharacterId()); + var selectedContext = context.toBuilder().setCharacterId(terminal.getCharacterId()).build(); + long selectedStarted = System.nanoTime(); + var selected = owners.roster.readSelectedPlayerCreatedCharacter(menu, selectedContext); + long selectedNanos = System.nanoTime() - selectedStarted; + System.out.printf( + "Created actual-writer bounded vector: terminalBytes=%d rosterBytes=%d selectedBytes=%d listApiSeconds=%.3f selectedApiSeconds=%.3f%n", + terminal.getSerializedSize(), + menu.response().getSerializedSize(), + selected.response().getSerializedSize(), + listNanos / 1_000_000_000.0, + selectedNanos / 1_000_000_000.0); + owners.requireDeadline(LIST_RPC, 20); + owners.requireDeadline(SELECTED_RPC, 20); + owners.requireDeadline(SOURCE_RPC, 5); + owners.requireDeadline(ORIGINAL_RPC, 10); + assertThat(selected.creationOperationUuid()).isEqualTo(creation); + assertThat(selected.terminal()).isEqualTo(terminal); + owners.roster.completeSelection(source, context, SelectionOutcome.SELECTED); + var retained = owners.gs.referenceOwner().read(menu.originalSelection()); + assertThat(CanonicalGameplayRosterReferenceEvidence.playerCreatedReceipt(retained)) + .isEqualTo(menu.response()); + assertThat( + CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + retained)) + .isEqualTo(selected.response()); + assertThat(owners.gs.referenceOwner().retireTarget(menu.originalSelection())).isFalse(); + var replay = owners.roster.listPlayerCreatedRoster(source, context); + assertThat(replay.response()).isEqualTo(menu.response()); + assertThat( + owners.roster.readSelectedPlayerCreatedCharacter(replay, selectedContext).response()) + .isEqualTo(selected.response()); + assertThat(owners.gs.referenceOwner().read(menu.originalSelection())).isEqualTo(retained); + } + } + private static final class Owners implements AutoCloseable { private final ArrayDeque resources = new ArrayDeque<>(); + private final List rpcObservations = new CopyOnWriteArrayList<>(); private final DriverManagerDataSource gsData; private final DriverManagerDataSource entityData; private final org.jooq.DSLContext entityDsl; + private final org.jooq.DSLContext gsDsl; + private final GameSessionCanonicalGameplayRosterOwnerReadClient originalClient; + private final GameSessionCanonicalGameplayRosterOwnerReadClient wrongRoleOriginalClient; + private final GameSessionCanonicalGameplayRosterOwnerReadClient wrongNamespaceOriginalClient; private final ControlledPlayerCreatedOriginalOwnerFixture gs; private final ControlledPlayerCreatedOwnerStoreFixture entity; private final CanonicalPlayerCreatedRosterClient roster; @@ -191,6 +585,12 @@ private Owners(Path directory) throws Exception { "gs-server", uri("game-session-service"), true), new LoopbackMtlsTestPki.IdentitySpec( "entity-client", uri("entity-management-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-role-client", uri("world-management-service"), false), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace-client", + "spiffe://firemud/ns/other/sa/entity-management-service", + false), new LoopbackMtlsTestPki.IdentitySpec( "entity-server", uri("entity-management-service"), true)); var endpoints = new ServiceEndpointsProperties(); @@ -212,6 +612,7 @@ private Owners(Path directory) throws Exception { Clock.systemUTC(), new CanonicalGameplayRosterReferencePolicy( RETENTION, RETENTION, RETENTION, Duration.ofSeconds(1), 20)); + gsDsl = DSL.using(new TransactionAwareDataSourceProxy(gsData), SQLDialect.POSTGRES); var beans = new StaticListableBeanFactory(); beans.addBean("source", gs.publishedRouteReader()); beans.addBean("reference", gs.referenceOwner()); @@ -232,13 +633,29 @@ private Owners(Path directory) throws Exception { var sourceClient = own( new EntityPlayerCreatedRosterSourceClient( - endpoints, entityTls, coupledOwnerTestChannels(), NAMESPACE)); + endpoints, entityTls, new GrpcChannelFactory(), NAMESPACE)); sourceClient.init(); - var originalClient = + originalClient = own( new GameSessionCanonicalGameplayRosterOwnerReadClient( - endpoints, entityTls, coupledOwnerTestChannels(), NAMESPACE)); + endpoints, entityTls, new GrpcChannelFactory(), NAMESPACE)); originalClient.init(); + wrongRoleOriginalClient = + own( + new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("wrong-role-client")), + new GrpcChannelFactory(), + NAMESPACE)); + wrongRoleOriginalClient.init(); + wrongNamespaceOriginalClient = + own( + new GameSessionCanonicalGameplayRosterOwnerReadClient( + endpoints, + pki.clientProperties(directory, pki.identity("wrong-namespace-client")), + new GrpcChannelFactory(), + NAMESPACE)); + wrongNamespaceOriginalClient.init(); var migration = Flyway.configure() .dataSource(entityData) @@ -274,7 +691,7 @@ private Owners(Path directory) throws Exception { roster = own( new CanonicalPlayerCreatedRosterClient( - endpoints, gsTls, coupledOwnerTestChannels(), NAMESPACE, gs.referenceOwner())); + endpoints, gsTls, new GrpcChannelFactory(), NAMESPACE, gs.referenceOwner())); roster.init(); } catch (Exception failure) { try { @@ -286,6 +703,48 @@ private Owners(Path directory) throws Exception { } } + private boolean retireWithControlledSuccessor( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original) { + var snapshot = controlledSuccessorSnapshot(original); + var current = controlledSuccessorRoute(original, snapshot); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readCurrentTarget(current.canonicalTenantId())).thenReturn(current); + var admissions = mock(CanonicalInitialAdmissionRepository.class); + when(admissions.readCurrentOpenSnapshotForRealm( + original.getTargetNamespace(), current.canonicalTenantId(), current.realmId())) + .thenReturn(snapshot); + when(admissions.lockExactCurrentOpenSnapshot(snapshot)).thenReturn(snapshot); + var successorOwner = + new CanonicalGameplayRosterReferenceOwner( + gs.referenceRepository(), + new TransactionTemplate(new DataSourceTransactionManager(gsData)), + gs.publishedRouteReader(), + routes, + admissions, + mock(CanonicalGameplayRosterRecoveryClient.class), + new io.micrometer.core.instrument.simple.SimpleMeterRegistry()); + return successorOwner.retireTarget(original); + } + + private int rpcCount(String method) { + return (int) rpcObservations.stream().filter(call -> call.method().equals(method)).count(); + } + + private void requireDeadline(String method, long seconds) { + assertThat(rpcObservations.stream().filter(call -> call.method().equals(method)).toList()) + .isNotEmpty() + .allSatisfy( + call -> { + assertThat(call.remainingMillis()).isPositive(); + assertThat(call.remainingMillis()) + .isLessThanOrEqualTo(TimeUnit.SECONDS.toMillis(seconds)); + if (seconds == 20) { + // The outer call reaches Entity with room for both nested owner RPCs. + assertThat(call.remainingMillis()).isGreaterThan(10_000L); + } + }); + } + private PlayerExecutionContext context(UUID account) { var route = gs.routeReader().readCurrentTarget(gs.route().canonicalTenantId()); return PlayerExecutionContext.newBuilder() @@ -308,26 +767,49 @@ private T own(T resource) { private Server server(LoopbackMtlsTestPki.Pki pki, String alias, BindableService... services) throws Exception { var identity = pki.identity(alias); - var builder = - NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .maxInboundMessageSize( - net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence - .MAX_PLAYER_CREATED_CONFIRMATION_BYTES) - .sslContext( - GrpcSslContexts.configure( - SslContextBuilder.forServer( - identity.privateKey(), identity.certificate())) - .trustManager(pki.caCertificate()) - .clientAuth(ClientAuth.REQUIRE) - .build()); + var bytePolicy = + switch (alias) { + case "gs-server" -> + new net.firedevops.firemud.gamesession.config + .GameSessionGrpcRequestByteConfiguration() + .gameSessionGrpcRequestBytePolicy(); + case "entity-server" -> + net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy.ordinary(); + default -> throw new IllegalArgumentException("Unknown controlled owner server role"); + }; + var factory = + new net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(identity), + pki.trustManagerFactory(), + io.grpc.TlsServerCredentials.ClientAuth.REQUIRE, + bytePolicy, + bytePolicy.transportMaximumBytes()); for (var service : services) - builder.addService( + factory.addService( ServerInterceptors.intercept( service, new net.firedevops.firemud.entitymanagement.security .CanonicalGameplayRosterPeerInterceptor(NAMESPACE), - new GrpcPeerIdentityInterceptor())); - var server = builder.build().start(); + new GrpcPeerIdentityInterceptor(), + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + var deadline = Context.current().getDeadline(); + rpcObservations.add( + new RpcObservation( + call.getMethodDescriptor().getFullMethodName(), + deadline == null + ? -1L + : deadline.timeRemaining(TimeUnit.MILLISECONDS))); + return next.startCall(call, headers); + } + })); + var server = factory.createServer().start(); own(() -> server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS)); return server; } @@ -350,72 +832,84 @@ public void close() throws Exception { } } - /** - * Keep real network, TLS and peer validation while allowing cold physical owner composition a - * bounded test-only budget. There are no retries; all other RPC call options remain unchanged. - */ - private static GrpcChannelFactory coupledOwnerTestChannels() { - return new GrpcChannelFactory() { - @Override - public ManagedChannel buildChannel( - String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) - throws SSLException { - var transport = super.buildChannel(target, defaultPort, properties, keepAlive); - return new ManagedChannel() { - @Override - public ClientCall newCall( - MethodDescriptor method, CallOptions options) { - var testOptions = - COUPLED_OWNER_TEST_RPCS.contains(method.getFullMethodName()) - ? options.withDeadlineAfter(COUPLED_OWNER_TEST_RPC_SECONDS, TimeUnit.SECONDS) - : options; - return transport.newCall(method, testOptions); - } - - @Override - public String authority() { - return transport.authority(); - } - - @Override - @SuppressFBWarnings( - value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", - justification = - "ManagedChannel.shutdown initiates shutdown; returning this preserves the wrapper's fluent identity.") - public ManagedChannel shutdown() { - transport.shutdown(); - return this; - } - - @Override - @SuppressFBWarnings( - value = "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", - justification = - "ManagedChannel.shutdownNow initiates shutdown; returning this preserves the wrapper's fluent identity.") - public ManagedChannel shutdownNow() { - transport.shutdownNow(); - return this; - } - - @Override - public boolean isShutdown() { - return transport.isShutdown(); - } - - @Override - public boolean isTerminated() { - return transport.isTerminated(); - } + private static CanonicalInitialAdmissionRepository.CurrentOpenSnapshot + controlledSuccessorSnapshot( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest + original) { + var target = CanonicalGameplayRosterReferenceEvidence.target(original); + var proof = + new net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof( + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome + .COMMITTED, + "controlled-successor-owner", + "1".repeat(64), + original.getTargetNamespace(), + UUID.fromString(target.getTenantUuid()), + target.getWorldSlug(), + UUID.fromString(target.getRealmUuid()), + UUID.fromString(target.getPlayableStateNamespaceUuid()), + "SHARED", + UUID.fromString(target.getGameInstanceUuid()), + UUID.fromString(target.getCanonicalVersionUuid()), + target.getActiveWorldEpoch() + 1L, + target.getCatalogRevision() + 1L, + net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind + .EXPECT_CLOSED, + target.getPointerVersion(), + UUID.fromString(original.getOperationUuid()), + UUID.fromString(original.getSessionUuid()), + "sha256:" + "2".repeat(64), + target.getPointerVersion() + 1L, + 1L, + "sha256:" + "3".repeat(64), + false, + Instant.now()); + return new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, "f".repeat(64)); + } - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { - return transport.awaitTermination(timeout, unit); - } - }; - } - }; + private static net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget + controlledSuccessorRoute( + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest original, + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot snapshot) { + var target = CanonicalGameplayRosterReferenceEvidence.target(original); + var proof = snapshot.ownerProof(); + return new net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget( + proof.targetNamespace(), + "controlled-tenant", + proof.canonicalTenantId(), + proof.worldSlug(), + "Controlled World", + proof.realmId(), + target.getRealmSlug(), + "Controlled Realm", + 1L, + 1L, + proof.playableStateNamespaceId(), + proof.playableStateScope(), + proof.canonicalGameInstanceId(), + proof.canonicalVersionId(), + 1L, + proof.expectedCatalogRevision(), + proof.committedPointerVersion(), + snapshot.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(), + "PLAYER_CREATED"); } + private record RpcObservation(String method, long remainingMillis) {} + private static DriverManagerDataSource dataSource(String schema) { var data = new DriverManagerDataSource( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index b27286a94b..941a73b17f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -94,12 +94,18 @@ void upgradeActualCanonicalHistory() { assertThat(history().subList(0, beforeCreated.size())).containsExactlyElementsOf(beforeCreated); assertThat(history()).hasSize(beforeCreated.size() + 1); assertThat(history().getLast()).contains("1020", "V1020__player_created_roster_reference.sql"); + var beforeScheduling = history(); + migrate("1021"); + assertThat(history().subList(0, beforeScheduling.size())) + .containsExactlyElementsOf(beforeScheduling); + assertThat(history().getLast()) + .contains("1021", "V1021__canonical_roster_recovery_attempt_scheduling.sql"); var beforeLatest = history(); migrate("latest"); assertThat(history().subList(0, beforeLatest.size())).containsExactlyElementsOf(beforeLatest); assertThat(history()).hasSize(beforeLatest.size() + 1); assertThat(history().get(history().size() - 1)) - .contains("1021", "V1021__canonical_roster_recovery_attempt_scheduling.sql"); + .contains("1022", "V1022__canonical_roster_binary_safe_recovery_guard.sql"); transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); repository = new CanonicalGameplayRosterReferenceRepository( @@ -256,11 +262,20 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() .isEqualTo(createdTerminalFixture.selected().toByteString()); var historyBeforeScheduling = history(upgradeDsl); + migrate(upgradeDataSource, upgradeSchema, "1021"); + String retainedRowsSql = + "SELECT row_to_json(s)::text || ':' || s.xmin::text FROM game_session_canonical_roster_selection s ORDER BY operation_uuid"; + var rowsBeforeBinaryGuard = upgradeDsl.fetch(retainedRowsSql).getValues(0, String.class); + var historyBeforeBinaryGuard = history(upgradeDsl); migrate(upgradeDataSource, upgradeSchema, "latest"); + assertThat(history(upgradeDsl).subList(0, historyBeforeBinaryGuard.size())) + .containsExactlyElementsOf(historyBeforeBinaryGuard); + assertThat(upgradeDsl.fetch(retainedRowsSql).getValues(0, String.class)) + .containsExactlyElementsOf(rowsBeforeBinaryGuard); assertThat(history(upgradeDsl).subList(0, historyBeforeScheduling.size())) .containsExactlyElementsOf(historyBeforeScheduling); assertThat(history(upgradeDsl).get(history(upgradeDsl).size() - 1)) - .contains("1021", "V1021__canonical_roster_recovery_attempt_scheduling.sql"); + .contains("1022", "V1022__canonical_roster_binary_safe_recovery_guard.sql"); assertThat(upgradeRow(upgradeDsl, ordinaryTerminal)).isEqualTo(retainedOrdinaryTerminal); assertThat(upgradeRow(upgradeDsl, recoveredTerminal)).isEqualTo(retainedRecoveredTerminal); assertThat(upgradeRow(upgradeDsl, pendingRecovery)).isEqualTo(retainedPendingRecovery); @@ -345,6 +360,25 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() upgradeRowValue(upgradeDsl, createdPending, "recovery_last_attempt_at", String.class); assertThat(createdAttempt).isNotNull(); var createdPendingAfterAttempt = upgradePredecessorRow(upgradeDsl, createdPending); + for (String change : + List.of( + "recovery_last_attempt_at = NULL", + "recovery_last_attempt_at = recovery_last_attempt_at - interval '1 millisecond'", + "recovery_last_attempt_at = recovery_last_attempt_at + interval '1 millisecond', original_request = decode('01', 'hex')")) { + assertThatThrownBy( + () -> + upgradeDsl.execute( + "UPDATE game_session_canonical_roster_selection SET " + + change + + " WHERE operation_uuid = ?", + UUID.fromString(createdPending.getOperationUuid()))) + .isInstanceOf(DataAccessException.class); + } + assertThat(upgradePredecessorRow(upgradeDsl, createdPending)) + .isEqualTo(createdPendingAfterAttempt); + assertThat( + upgradeRowValue(upgradeDsl, createdPending, "recovery_last_attempt_at", String.class)) + .isEqualTo(createdAttempt); var alteredSelectedReceipt = createdPendingFixture.selected().toBuilder() .setTerminal( @@ -2635,23 +2669,22 @@ void createdOriginalSurvivesSqlAndProductionMtlsOwnerReadAcknowledgementAndConfi net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner .class)); var serverIdentity = pki.identity("gs-server"); - var server = - io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder.forAddress( - new java.net.InetSocketAddress("127.0.0.1", 0)) - .maxInboundMessageSize( - CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES) - .sslContext( - io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts.configure( - io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer( - serverIdentity.privateKey(), serverIdentity.certificate())) - .trustManager(pki.caCertificate()) - .clientAuth(io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth.REQUIRE) - .build()) - .addService( - io.grpc.ServerInterceptors.intercept( - adapter, new net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor())) - .build() - .start(); + var bytePolicy = + new net.firedevops.firemud.gamesession.config.GameSessionGrpcRequestByteConfiguration() + .gameSessionGrpcRequestBytePolicy(); + var serverFactory = + new net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + pki.keyManagerFactory(serverIdentity), + pki.trustManagerFactory(), + io.grpc.TlsServerCredentials.ClientAuth.REQUIRE, + bytePolicy, + bytePolicy.transportMaximumBytes()); + serverFactory.addService( + io.grpc.ServerInterceptors.intercept( + adapter, new net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor())); + var server = serverFactory.createServer().start(); var endpoints = new net.firedevops.firemud.common.config.ServiceEndpointsProperties(); endpoints.setGameSessionService("127.0.0.1:" + server.getPort()); var client = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java index 641d6ac292..604f833f04 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java @@ -82,6 +82,12 @@ private void proveCleanInstall(MigrationSet migrations) { List installed = history(dataSource); assertMigrationPresent(installed, migrations.childVersion(), migrations.childScript()); assertMigrationPresent(installed, migrations.frontVersion(), migrations.frontScript()); + assertMigrationPresent( + installed, + migrations == GAME_SESSION ? "1022" : "1021", + migrations == GAME_SESSION + ? "V1022__canonical_roster_binary_safe_recovery_guard.sql" + : "V1021__character_create_binary_safe_immutability.sql"); assertThat(installed).allSatisfy(row -> assertThat(row).contains("\"success\": true")); assertEntitySealPrimaryKey(migrations, dataSource); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java index 0f86b3d986..dddeee0095 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java @@ -30,12 +30,14 @@ import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository.InvalidFreshTenantAssociationException; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -67,6 +69,11 @@ class GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @Test void allocatesOneStartingLaunchWithExactPolicyAndIndependentOwnerReadback() throws Exception { Fixture fixture = fixture(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java index 09291ce104..3bcb6f2597 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java @@ -12,6 +12,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -39,6 +40,8 @@ class RuntimeRegionStatusRepositoryIntegrationTest { @BeforeAll void setUpRepository() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(postgres.getDriverClassName()); dataSource.setUrl(postgres.getJdbcUrl()); 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 cc145f6f20..5b51d6ad24 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 @@ -43,6 +43,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; import net.firedevops.firemud.gamesession.service.GameSessionCanonicalLaunchPreparationService; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -51,6 +52,7 @@ import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -94,6 +96,11 @@ class GameSessionCanonicalLaunchPreparationServiceIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @Test void commitsExactFreshSourceCatalogAndSyntheticDescriptorThenReplaysWithoutChangingRetainedRows() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java index 16ba14f94c..6c6b4d86ed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java @@ -91,7 +91,7 @@ void controlledComposition() throws Exception { var route = mock(CanonicalPlayableTarget.class); when(route.targetNamespace()).thenReturn(fixture.namespace()); when(source.route()).thenReturn(route); - when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withDeadlineAfter(20L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.withMaxInboundMessageSize(anyInt())).thenReturn(stub); when(stub.listPlayerCreatedRoster(any())) .thenAnswer( @@ -502,6 +502,8 @@ void actualBuiltStubPinsTheEntityPeerAndUsesCompressionDeadlineAndCreatedRosterB assertThat(options.getValue().getCompressor()).isEqualTo("gzip"); assertThat(options.getValue().getMaxInboundMessageSize()).isEqualTo(66 * 1024); assertThat(options.getValue().getDeadline()).isNotNull(); + assertThat(options.getValue().getDeadline().timeRemaining(TimeUnit.MILLISECONDS)) + .isBetween(19_000L, 20_000L); assertThat(options.getValue().getCredentials()) .isInstanceOf( net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java new file mode 100644 index 0000000000..8dc185df0a --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java @@ -0,0 +1,334 @@ +package unit.net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; +import com.google.protobuf.Empty; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ForwardingServerCallListener; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerMethodDefinition; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.TlsServerCredentials; +import io.grpc.protobuf.ProtoUtils; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.gamesession.config.GameSessionGrpcRequestByteConfiguration; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.ShadedNettyGrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.GrpcService; + +class GameSessionGrpcRequestByteConfigurationTest { + @Test + void onlyGeneratedAcknowledgementAndConfirmationDescriptorsReceiveLargeAdmission() { + var policy = new GameSessionGrpcRequestByteConfiguration().gameSessionGrpcRequestBytePolicy(); + assertThat(policy.transportMaximumBytes()) + .isEqualTo(CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + var factory = + new BoundedGrpcServerFactory( + "127.0.0.1:0", + List.of(), + null, + null, + TlsServerCredentials.ClientAuth.NONE, + policy, + policy.transportMaximumBytes()); + Map parsedMessages = new HashMap<>(); + factory.addService( + recordOriginalMessages( + new CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase() {}.bindService(), + parsedMessages)); + var ordinary = + MethodDescriptor.newBuilder() + .setFullMethodName("test.Unrelated/Read") + .setType(MethodDescriptor.MethodType.UNARY) + .setRequestMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) + .build(); + factory.addService( + recordOriginalMessages( + ServerServiceDefinition.builder("test.Unrelated") + .addMethod( + ordinary, + io.grpc.stub.ServerCalls.asyncUnaryCall( + (request, response) -> { + response.onNext(Empty.getDefaultInstance()); + response.onCompleted(); + })) + .build(), + parsedMessages)); + Server server = factory.createServer(); + try { + // Well-formed protobuf unknown fields exercise parsing without domain authorization. + byte[] exact = rawRequest(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + byte[] oversized = rawRequest(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES + 1); + for (var service : server.getServices()) { + for (var method : service.getMethods()) { + String name = method.getMethodDescriptor().getFullMethodName(); + boolean retirementException = + name.equals( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod() + .getFullMethodName()) + || name.equals( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getConfirmCanonicalGameplayRosterRetirementAcknowledgementMethod() + .getFullMethodName()); + // The generated base reports UNIMPLEMENTED only after parsing and unary dispatch. + Status.Code admittedOutcome = + name.equals(ordinary.getFullMethodName()) + ? Status.Code.OK + : Status.Code.UNIMPLEMENTED; + assertThat(dispatch(method, exact).getCode()).isEqualTo(admittedOutcome); + assertThat(parsedMessages.get(name)).isEqualTo(1); + assertThat(dispatch(method, oversized).getCode()) + .isEqualTo(retirementException ? admittedOutcome : Status.Code.RESOURCE_EXHAUSTED); + assertThat(parsedMessages.get(name)).isEqualTo(retirementException ? 2 : 1); + if (retirementException) { + int maximum = + name.equals( + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod() + .getFullMethodName()) + ? CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_REQUEST_BYTES + : CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES; + var abovePurposeMaximum = new OversizedRawStream(maximum + 1); + assertThat(dispatch(method, abovePurposeMaximum).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED); + assertThat(abovePurposeMaximum.consumed).isEqualTo(maximum + 1); + assertThat(parsedMessages.get(name)).isEqualTo(2); + } + } + } + } finally { + server.shutdownNow(); + } + } + + @Test + void activeGameSessionPolicyFailsStartupWithoutSharedGuardOrWithPlainFactory() { + var runner = productionRunner(false); + runner.run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf( + org.springframework.beans.factory.NoSuchBeanDefinitionException.class); + }); + runner + .withBean( + GrpcServerFactory.class, + () -> + new ShadedNettyGrpcServerFactory( + "127.0.0.1:0", List.of(), null, null, TlsServerCredentials.ClientAuth.NONE)) + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf( + org.springframework.beans.factory.NoSuchBeanDefinitionException.class); + }); + } + + @Test + void realProductionDiscoverySatisfiesRequiredGameSessionGuardAndClosedPolicy() { + productionRunner(true) + .run( + context -> { + assertThat(context).hasNotFailed().hasSingleBean(GrpcServerFactory.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); + assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + }); + } + + private static byte[] rawRequest(int size) { + int payloadSize = + size + - CodedOutputStream.computeTagSize(9999) + - CodedOutputStream.computeUInt32SizeNoTag(size); + byte[] raw = + Empty.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 9999, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFrom(new byte[payloadSize])) + .build()) + .build()) + .build() + .toByteArray(); + assertThat(raw).hasSize(size); + return raw; + } + + private static ServerServiceDefinition recordOriginalMessages( + ServerServiceDefinition service, Map messages) { + return ServerInterceptors.intercept( + service, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + return new ForwardingServerCallListener.SimpleForwardingServerCallListener<>( + next.startCall(call, headers)) { + @Override + public void onMessage(Q message) { + messages.merge(call.getMethodDescriptor().getFullMethodName(), 1, Integer::sum); + super.onMessage(message); + } + }; + } + }); + } + + private static Status dispatch(ServerMethodDefinition definition, byte[] raw) { + return dispatch(definition, new ByteArrayInputStream(raw)); + } + + @SuppressWarnings("unchecked") + private static Status dispatch(ServerMethodDefinition definition, InputStream raw) { + // The bounded production factory's public adapter uses InputStream in both directions. + var method = (ServerMethodDefinition) definition; + var call = new RecordingCall(method.getMethodDescriptor()); + var listener = method.getServerCallHandler().startCall(call, new Metadata()); + listener.onMessage(method.getMethodDescriptor().parseRequest(raw)); + listener.onHalfClose(); + listener.onComplete(); + assertThat(call.closed).hasSize(1); + return call.closed.getFirst(); + } + + /** + * Finite unknown-length source; the guard's real readNBytes still allocates its admission buffer. + */ + private static final class OversizedRawStream extends InputStream { + private int remaining; + private int consumed; + + private OversizedRawStream(int size) { + remaining = size; + } + + @Override + public int read() { + if (remaining == 0) { + return -1; + } + remaining--; + consumed++; + return 255; + } + + @Override + public int read(byte[] buffer, int offset, int length) { + if (length == 0) { + return 0; + } + if (remaining == 0) { + return -1; + } + int count = Math.min(length, remaining); + Arrays.fill(buffer, offset, offset + count, (byte) 255); + remaining -= count; + consumed += count; + return count; + } + + @Override + public int available() { + return 0; + } + } + + private static final class RecordingCall extends ServerCall { + private final MethodDescriptor method; + private final List closed = new ArrayList<>(); + + private RecordingCall(MethodDescriptor method) { + this.method = method; + } + + @Override + public void request(int count) {} + + @Override + public void sendHeaders(Metadata headers) {} + + @Override + public void sendMessage(InputStream response) {} + + @Override + public void close(Status status, Metadata trailers) { + closed.add(status); + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public MethodDescriptor getMethodDescriptor() { + return method; + } + } + + private static ApplicationContextRunner productionRunner(boolean includeGuard) { + var runner = + new ApplicationContextRunner() + .withUserConfiguration(GameSessionGrpcRequestByteConfiguration.class) + .withBean(TestRosterService.class, TestRosterService::new) + .withPropertyValues( + "spring.grpc.server.port=0", "spring.grpc.server.ssl.enabled=false"); + return includeGuard + ? runner.withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonGrpcRequestBoundsAutoConfiguration.class, + GrpcServerFactoryAutoConfiguration.class, + GrpcServerAutoConfiguration.class)) + : runner.withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + GrpcServerFactoryAutoConfiguration.class, + GrpcServerAutoConfiguration.class)); + } + + @GrpcService + static class TestRosterService + extends CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase {} +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 41e9d23b1a..b99e790051 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -42,7 +42,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; -import org.springframework.grpc.server.service.GrpcServiceDiscoverer; import org.springframework.test.util.TestSocketUtils; /** Shared bootstrap helpers for nested cross-service Spring application contexts in tests. */ @@ -144,9 +143,7 @@ public static GameSessionHolder startGameSession( props.put("spring.flyway.locations", "filesystem:" + gameSessionMigrationDir()); props.put( "spring.autoconfigure.exclude", - "org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration," - + "org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration," - + "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration"); + "org.springframework.boot.grpc.server.autoconfigure.health.GrpcServerHealthAutoConfiguration"); props.put("firemud.services.gameLogicService", "localhost:" + gameLogicPort); props.put("firemud.services.accountService", "localhost:" + accountPort); props.put("firemud.grpc.plaintext", "true"); @@ -213,12 +210,6 @@ ConflictTracker conflictTracker() { return key -> {}; } - @Bean - @Primary - GrpcServiceDiscoverer grpcServiceDiscoverer() { - return org.mockito.Mockito.mock(GrpcServiceDiscoverer.class); - } - @Bean @Primary ModerationPolicyClient moderationPolicyClient() { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java index 6ec8f689bb..e9bd406aa4 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java @@ -23,6 +23,7 @@ import java.util.Map; import java.util.Objects; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidence; @@ -68,6 +69,7 @@ import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; import org.jooq.DSLContext; import org.jooq.Field; import org.jooq.SQLDialect; @@ -105,6 +107,7 @@ public final class ControlledPlayerCreatedOriginalOwnerFixture { private final CanonicalGameplayRosterReferenceOwner referenceOwner; private final CanonicalPlayableTarget route; private final WireFixture wireFixture; + private final AtomicInteger controlledWorldLifecycleReads = new AtomicInteger(); @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -323,7 +326,7 @@ public ControlledPlayerCreatedOriginalOwnerFixture( attempts.readCurrentOriginalAttempt(currentAttemptRequest); return retention.retainInOwnerTransaction(retained); }); - migrate("1020"); + migrateLatest(); routeReader = new CanonicalPlayerRouteReadService(namespace, catalogs, admissions, launches); var gameDesign = mock(AuthoredInitialActorCoreReadClient.class); when(gameDesign.read(any())) @@ -340,6 +343,7 @@ public ControlledPlayerCreatedOriginalOwnerFixture( .thenAnswer( call -> { requireOutsideSql(); + controlledWorldLifecycleReads.incrementAndGet(); var requested = (WorldCanonicalInstanceLifecycleEvidence.Request) call.getArgument(0); var base = supplied.world(); var expected = base.request(); @@ -457,19 +461,36 @@ public CanonicalPublishedPlayerRouteReadService publishedRouteReader() { return publishedRouteReader; } + /** Counts complete source resolution's independently reread World lifecycle boundary. */ + public int controlledWorldLifecycleReadCount() { + return controlledWorldLifecycleReads.get(); + } + public int retainedOriginalReferenceCount() { return dsl.fetchCount(DSL.table("game_session_canonical_roster_selection")); } private void migrate(String version) { - Flyway.configure() - .dataSource(dataSource) - .schemas(schema) - .defaultSchema(schema) - .locations("filesystem:" + migrations) - .target(MigrationVersion.fromVersion(version)) - .load() - .migrate(); + migrateTo(version); + } + + private void migrateLatest() { + migrateTo(null); + } + + private void migrateTo(String version) { + var migration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .locations("filesystem:" + migrations) + .placeholders(Map.of("serviceSchema", schema)); + if (version != null) migration.target(MigrationVersion.fromVersion(version)); + migration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + migration.load().migrate(); } private static Path resolveMigrationDirectory() { From a93b003875ca2a28c6e55416702bf8b3b4efeeb6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:34:43 +1300 Subject: [PATCH 19/22] fix: retain default gRPC bounds and recover owner fixtures --- .../game-session-service/api-contracts.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- .../player-access-and-session.md | 2 +- ...monGrpcRequestBoundsAutoConfiguration.java | 10 +- .../grpc/BoundedGrpcServerFactoryTest.java | 19 ++- ...rpcRequestBoundsAutoConfigurationTest.java | 143 ++++++++++++++++++ .../test/NoGrpcServerTestConfiguration.java | 7 + ...PlayerCreatedRosterSnapshotRepository.java | 9 +- ...haracterCreatePostgresIntegrationTest.java | 113 +------------- ...RosterSnapshotPostgresIntegrationTest.java | 22 +++ ...anonicalGameplayRosterGrpcAdapterTest.java | 25 +++ ...trolledPlayerCreatedOwnerStoreFixture.java | 2 +- ...RosterOwnerCompositionIntegrationTest.java | 13 +- ...osterReferencePostgresIntegrationTest.java | 13 +- ...rCoreRetentionPostgresIntegrationTest.java | 7 + ...RealmCatalogRepositoryIntegrationTest.java | 7 + ...ationJournalRepositoryIntegrationTest.java | 2 + ...thorizationCoordinatorIntegrationTest.java | 7 + ...lAdmissionBindPostgresIntegrationTest.java | 7 + ...ssionGrpcRequestByteConfigurationTest.java | 13 +- .../GatewayGameplayBridgeIntegrationTest.java | 35 ++--- ...xyTlsListenerAdmissionIntegrationTest.java | 5 +- 23 files changed, 316 insertions(+), 151 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index b099437791..028e4fa149 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -108,7 +108,7 @@ Entity durably records that authenticated response before confirming delivery. C Game Session consumes Entity's distinct [player-created roster and selected-character contract](../entity-management-service/api-contracts.md#player-created-roster-and-selected-character) only after independently resolving the current published `PLAYER_CREATED` source and matching the complete route, policy, descriptor and source identity. It retains the exact typed created-roster and selected-character receipts on the original operation, preserves the original menu and ordinal/frozen actor choice, and revalidates the current route around owner reads. Original-operation reservation, returned-roster qualification and selected-reference qualification require independent current published-source observations, including their Game Design, World and published-policy evidence. An earlier observation cannot be cached across those authority boundaries to remove their freshness checks. These receipts provide no membership, session-binding or gameplay-admission authority. The two created roster and selected-character client RPCs use a finite twenty-second outer deadline so the nested five-second current-source and ten-second original-owner calls retain their bounded budgets under the inherited gRPC context. Request and response validation outside those calls remains part of the caller operation; this deadline is not a production latency guarantee. The existing preseeded route remains a separate strict branch; a Common parser validates values without establishing authenticated custody. -The created reference response retains the complete selected payload within its 194 MiB purpose envelope, and retirement-observation requests retain it within the 195 MiB created-ACK envelope with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within its existing recovery purpose bound. These purpose-specific limits preserve complete owner bytes and the existing preseeded bounds. The shared server transport has one finite deframing ceiling large enough for the existing created-retirement confirmation envelope. Mandatory request marshalling at the canonical server-registration boundary checks the raw uncompressed request length before invoking any protobuf parser: only the exact generated acknowledgement and confirmation method descriptors receive their existing purpose bounds; every other method, including future or unlisted methods, retains the 4 MiB default or a smaller owning bound. Caller metadata cannot select a larger budget. Missing or duplicate admission configuration and unwrapped service registration fail closed. Semantic policy bounds, response bounds and workload authentication remain independent checks. The shared transport can buffer more than 4 MiB before method admission rejects a request; this mechanism does not establish a 4 MiB network-memory ceiling or production capacity. The corresponding local storage consequences belong to [Runtime and Data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership). +The created reference response retains the complete selected payload within its 194 MiB purpose envelope, and retirement-observation requests retain it within the 195 MiB created-ACK envelope with bounded confirmation overhead. Recovery retains only the exact typed created-roster receipt within its existing recovery purpose bound. These purpose-specific limits preserve complete owner bytes and the existing preseeded bounds. The shared server transport retains the framework 4 MiB deframing default. The existing `spring.grpc.server.max-inbound-message-size` setting may explicitly select a different positive finite ceiling no larger than the closed policy maximum for the created-retirement confirmation envelope; the policy maximum does not automatically enlarge the deployment limit. A deployment using the default rejects larger requests even on the two eligible created-retirement methods. Mandatory request marshalling at the canonical server-registration boundary checks the raw uncompressed request length before invoking any protobuf parser: only the exact generated acknowledgement and confirmation method descriptors receive their existing purpose bounds; every other method, including future or unlisted methods, retains the 4 MiB default or a smaller owning bound. Caller metadata cannot select a larger budget. Missing or duplicate admission configuration and unwrapped service registration fail closed. Semantic policy bounds, response bounds and workload authentication remain independent checks. When explicitly configured above the default, the shared transport can buffer more than 4 MiB before method admission rejects a request; method admission does not establish a 4 MiB network-memory ceiling. Before live created-owner activation, that larger configured mode requires production resource, concurrent-request memory and latency qualification. Controlled large-payload proof does not establish production capacity or select a per-connection concurrency budget. The corresponding local storage consequences belong to [Runtime and Data](./runtime-and-data.md#canonical-roster-selection-and-reference-ownership). #### Canonical gameplay roster owner read 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 abf6feeb63..58c1802175 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -85,7 +85,7 @@ Compact transfer receipts survive original removal and remain protected until En #### Player-created original roster storage -The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. Forward V1022 preserves the recovery-attempt timestamp transition with an exact typed-row comparison, so checking unchanged selected receipts does not convert large binary values to JSON; published V1020 and V1021 remain unchanged. Original-reference and retirement storage preserve the complete selected payload without truncation. Recovery retains the exact typed created-roster receipt independently of the selected terminal, while the existing preseeded storage branch remains unchanged. The [API contract](./api-contracts.md#player-created-original-roster-consequences) owns the shared transport ceiling and mandatory request admission before protobuf parsing; the shared deframing path can buffer large requests and requires separate resource qualification. Current implementation and migration qualification are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) and [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). +The created branch retains its exact typed roster receipt and selected-character receipt on the original operation, separately from the preseeded assignment receipt. Forward V1022 preserves the recovery-attempt timestamp transition with an exact typed-row comparison, so checking unchanged selected receipts does not convert large binary values to JSON; published V1020 and V1021 remain unchanged. Original-reference and retirement storage preserve the complete selected payload without truncation. Recovery retains the exact typed created-roster receipt independently of the selected terminal, while the existing preseeded storage branch remains unchanged. The [API contract](./api-contracts.md#player-created-original-roster-consequences) owns the shared transport ceiling and mandatory request admission before protobuf parsing; the default remains the framework limit, while an explicitly enlarged shared deframing path requires separate resource, concurrency and latency qualification before live created-owner activation. Current implementation and migration qualification are recorded in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#player-created-roster-consumer-preparation) and [Gameplay tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation). The unregistered bounded retention service uses the configured cadence and batch bound, pages past protected candidates, and reports oldest blocking age, cleanup lag, pending-transfer age and fixed cleanup outcomes without identity-bearing metric labels. Unfinished or unavailable authority remains protected. Production registration and real gameplay admission stay closed pending the [owning proof gate](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#canonical-sealed-roster-retention-prerequisite). diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index 3fb21ccc91..4cace24609 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -24,7 +24,7 @@ R267 passes thirteen focused shared-server cases, including actual mTLS/gzip exa The shared request guard now buffers and replays bounded 64 KiB chunks without flattening the complete request into a second byte array. R275 repeats both large compositions successfully through that guard, retaining the actual-writer and separate opaque-vector sizes above; the complete multi-call selection takes 22.170 seconds. Existing keepalive warnings do not invalidate the completed calls or establish a production latency or capacity result. The actual Spring Boot discovery regression and the cross-service fixture use real framework service discovery and the canonical factory. Tests explicitly replacing the server lifecycle retain their mock, while an explicit factory start still refuses missing configured method descriptors. -R277 passes the full enabled Common and Entity checks with 1,040 Common tests, 416 Entity unit cases and 117 Entity PostgreSQL cases, all without failures, errors or skips. Its 2,576 Game Session unit and 36 cross-service cases also pass. The Game Session integration aggregate remains a failed result: 370 reported cases include nine setup failures across two PostgreSQL fixtures and one Redis initializer, plus one skipped large-payload method. Connection refusal and port-readiness timeout do not establish a host-side cause. R278 then passes all fourteen cases in those three selected fixtures, together with the remaining Game Session enabled static, format and check tasks; it is focused recovery, not a new unfiltered integration run. PostgreSQL fixtures use the existing bounded mapped-JDBC readiness check before schema use, while the Redis fixture is unchanged. R275 separately executes the large-payload proof skipped in the ordinary aggregate. Earlier R272 and R274 heap/frontier and server-fixture failures retain their failed attribution; their corrections do not earn missing aggregate or packaging proof. Fresh-image qualification for this corrective source remains pending, as do genuine custody, causal current supersession, production registration, admission and activation. +R277 passes the full enabled Common and Entity checks with 1,040 Common tests, 416 Entity unit cases and 117 Entity PostgreSQL cases, all without failures, errors or skips. Its 2,576 Game Session unit and 36 cross-service cases also pass. The Game Session integration aggregate remains a failed result: 370 reported cases include nine setup failures across two PostgreSQL fixtures and one Redis initializer, plus one skipped large-payload method. Connection refusal and port-readiness timeout do not establish a host-side cause. R278 then passes all fourteen cases in those three selected fixtures, together with the remaining Game Session enabled static, format and check tasks; it is focused recovery, not a new unfiltered integration run. PostgreSQL fixtures use the existing bounded mapped-JDBC readiness check before schema use, while the Redis fixture is unchanged. R275 separately executes the large-payload proof skipped in the ordinary aggregate. Earlier R272 and R274 heap/frontier and server-fixture failures retain their failed attribution; their corrections do not earn missing aggregate or packaging proof. R273 rebuilds fresh Entity and Game Session images at published `8e752d6d0fcaaa146e5b4d42df4d11c2d69bbb37` and passes held Gateway/Telnet denial plus the separate isolated backend WORLDS, LOGIN, PLAY and LOOK baseline. Authenticated teardown succeeds, and independent exact-project checks find zero containers, networks or volumes. This qualifies that published source and packaging, without qualifying later local stale-snapshot and test-fixture corrections. Genuine custody, causal current supersession, production registration, admission and activation remain open. Earlier parent qualification receives #3295 at `cc33169ca1354872e101c4ef42777b0e79032473`, including its complete release/World validation correction. R116 passes the full Game Session check, formatting and affected static analysis with 2,568 unit cases, 365 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. This includes the actual initial owner-to-owner composition, which freshly passes in 30.763 seconds. The tested postimages are retained at `c9774094d76097ade5dcc5530d346e4960e613d8` after canonical fixture formatting. Unchanged Entity production source retains R113’s 402 unit and 94 PostgreSQL executions; R116 also passes both affected fixture static checks after correcting the earlier fixture-only SpotBugs failures. R117 freshly rebuilds that checkpoint and passes held Gateway/Telnet denial and isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK`, followed by authenticated teardown and independently confirmed exact-project container, network and volume absence. 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 e2983f7aff..7b1244ae5b 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -12,7 +12,7 @@ The unregistered Game Session composition consumes the independently resolved cu The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the bounded-retirement parent carry at `337f5b86665939c032b07122d391dd099ee2a4d1`, receiving #3295 `bd032b622d7696ebfeeab462d9c2907b9eed8765`. Its controlled initial owner-to-owner composition, additive typed retention, current affected Game Session checks, full Entity gate and fresh-image proof are qualified there; the earlier full Game Session gate at `c9774094d76097ade5dcc5530d346e4960e613d8` retains its separate attribution. Created recovery/retirement/ACK and current Human writer-refusal components remain separate proof: full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. -Game Session migration qualification follows the published created-reference V1020 and subsequent recovery-scheduling V1021. The unpublished runtime and creation-protection receivers previously reserved V1018/V1019; an earlier local V1021/V1022 receiving plan predates the scheduling correction and is not a current free-version assignment. Before receiving those owners, verify the actual migration frontier and next unused forward versions, preserve their SQL bytes, and prove the actual-parent upgrade and retained rows/history. Those separate owners remain unregistered; this status grants no runtime, protection or activation authority. +Game Session migration qualification follows the published created-reference V1020, recovery-scheduling V1021 and current forward binary-safe recovery guard V1022. Before receiving the unpublished canonical UUID runtime and creation-protection owners, verify the actual migration frontier and unused forward versions beyond it, preserve published SQL bytes, and prove the actual-parent upgrade and retained rows/history. Those separate owners remain unregistered; this status grants no runtime, protection or activation authority. ### Public character-creation and created-roster source preparation diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java index 472edb7a25..5ba13301fc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/CommonGrpcRequestBoundsAutoConfiguration.java @@ -28,7 +28,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; import org.springframework.grpc.server.GrpcServerFactory; import org.springframework.grpc.server.ServerBuilderCustomizer; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; @@ -59,8 +58,7 @@ BoundedGrpcServerFactory boundedGrpcServerFactory( GrpcServiceConfigurer configurer, ObjectProvider bundles, ObjectProvider> builderCustomizers, - ObjectProvider factoryCustomizers, - Environment environment) { + ObjectProvider factoryCustomizers) { KeyManagerFactory keys = null; TrustManagerFactory trust = null; if (properties.getSsl().determineEnabled()) { @@ -75,10 +73,8 @@ BoundedGrpcServerFactory boundedGrpcServerFactory( ? bundle.getManagers().getTrustManagerFactory() : InsecureTrustManagerFactory.INSTANCE; } - int transportMaximum = policy.transportMaximumBytes(); - if (environment.containsProperty("spring.grpc.server.max-inbound-message-size")) { - transportMaximum = Math.toIntExact(properties.getMaxInboundMessageSize().toBytes()); - } + // Preserve the framework's 4 MiB default; policy maxima only constrain explicit opt-in. + int transportMaximum = Math.toIntExact(properties.getMaxInboundMessageSize().toBytes()); List> customizers = List.of( builder -> configureProperties(builder, properties), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java index cade53561b..fcb12fc070 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java @@ -139,7 +139,7 @@ void mtlsCompressedOrdinaryAndFutureMethodsRejectBeforeParserAndFallbackCannotBy pki.trustManagerFactory(), TlsServerCredentials.ClientAuth.REQUIRE, policy, - policy.transportMaximumBytes()); + explicitTransportMaximum(policy)); factory.addService( ServerServiceDefinition.builder("test.Owner") .addMethod(ordinary, handler()) @@ -212,6 +212,21 @@ private static void assertRejected( .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); } + private static int explicitTransportMaximum(GrpcRequestBytePolicy policy) { + var properties = + new org.springframework.boot.context.properties.bind.Binder( + new org.springframework.boot.context.properties.source + .MapConfigurationPropertySource( + java.util.Map.of( + "spring.grpc.server.max-inbound-message-size", + policy.transportMaximumBytes() + "B"))) + .bind( + "spring.grpc.server", + org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties.class) + .get(); + return Math.toIntExact(properties.getMaxInboundMessageSize().toBytes()); + } + private static BoundedGrpcServerFactory factory(GrpcRequestBytePolicy policy) { return new BoundedGrpcServerFactory( "127.0.0.1:0", @@ -220,7 +235,7 @@ private static BoundedGrpcServerFactory factory(GrpcRequestBytePolicy policy) { null, TlsServerCredentials.ClientAuth.NONE, policy, - policy.transportMaximumBytes()); + explicitTransportMaximum(policy)); } private static MethodDescriptor method(String name, AtomicInteger parses) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java index 24b12af582..4fbf6e76b9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java @@ -5,14 +5,18 @@ 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 com.google.protobuf.ByteString; import com.google.protobuf.Empty; +import com.google.protobuf.UnknownFieldSet; import io.grpc.BindableService; import io.grpc.CallOptions; import io.grpc.ManagedChannel; import io.grpc.MethodDescriptor; import io.grpc.ServerInterceptor; import io.grpc.ServerServiceDefinition; +import io.grpc.Status; import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.protobuf.ProtoUtils; import io.grpc.stub.ClientCalls; @@ -22,6 +26,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration; +import net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterOwnerReadServiceGrpc; +import net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterRetirementAcknowledgementRequest; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import org.junit.jupiter.api.Test; import org.springframework.boot.WebApplicationType; @@ -32,6 +39,7 @@ import org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration; import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration; import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryCustomizer; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -179,6 +187,136 @@ void explicitNoServerLifecycleBacksOffWithoutWeakeningFactoryDescriptorChecks() }); } + @Test + void explicitNoServerFixtureAlsoBootsWhenFrameworkGrpcSupportIsExcluded() { + new ApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonGrpcRequestBoundsAutoConfiguration.class)) + .withUserConfiguration( + DiscoveredServiceConfiguration.class, NoGrpcServerTestConfiguration.class) + .withPropertyValues("spring.grpc.server.port=0", "spring.grpc.server.ssl.enabled=false") + .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) + .run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerLifecycle.class) + .hasSingleBean(GrpcServerFactory.class) + .hasSingleBean(GrpcServiceConfigurer.class) + .doesNotHaveBean("boundedGrpcServerLifecycle"); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); + verify(lifecycle, never()).start(); + verifyNoInteractions(context.getBean(GrpcServiceConfigurer.class)); + var factory = context.getBean(GrpcServerFactory.class); + assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact registered descriptor"); + }); + } + + @Test + void createdPolicyRequiresExplicitTransportOptInAndKeepsOrdinaryMethodsBounded() { + var createdRunner = + runner + .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) + .withBean(CreatedRosterService.class, CreatedRosterService::new); + createdRunner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat( + context.getBean(GrpcServerProperties.class).getMaxInboundMessageSize().toBytes()) + .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + assertPurposeAndOrdinaryAdmission( + context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.RESOURCE_EXHAUSTED); + assertThat(context.getBean(DiscoveryState.class).events).doesNotContain("handler"); + }); + createdRunner + .withPropertyValues( + "spring.grpc.server.max-inbound-message-size=" + + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES + + "B") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat( + context + .getBean(GrpcServerProperties.class) + .getMaxInboundMessageSize() + .toBytes()) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + // UNIMPLEMENTED comes from the generated base only after the actual eligible request + // parses. + assertPurposeAndOrdinaryAdmission( + context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.UNIMPLEMENTED); + assertThat(context.getBean(DiscoveryState.class).events).doesNotContain("handler"); + }); + createdRunner + .withPropertyValues("spring.grpc.server.max-inbound-message-size=0B") + .run(context -> assertThat(context).hasFailed()); + createdRunner + .withPropertyValues( + "spring.grpc.server.max-inbound-message-size=" + + ((long) + CanonicalGameplayRosterRetirementEvidence + .MAX_PLAYER_CREATED_CONFIRMATION_BYTES + + 1) + + "B") + .run(context -> assertThat(context).hasFailed()); + } + + private static void assertPurposeAndOrdinaryAdmission(int port, Status.Code purposeStatus) + throws Exception { + var unknown = + UnknownFieldSet.newBuilder() + .addField( + 9999, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited( + ByteString.copyFrom(new byte[GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES])) + .build()) + .build(); + var request = + CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() + .setUnknownFields(unknown) + .build(); + assertThat(request.getSerializedSize()) + .isGreaterThan(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", port).usePlaintext().build(); + try { + var options = + CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS).withCompression("gzip"); + assertThatThrownBy( + () -> + ClientCalls.blockingUnaryCall( + channel, + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod(), + options, + request)) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(purposeStatus)); + assertThatThrownBy( + () -> + ClientCalls.blockingUnaryCall( + channel, READ, options, Empty.newBuilder().setUnknownFields(unknown).build())) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + @Test void alternateFactoryAndDuplicatePoliciesFailClosed() { runner @@ -255,6 +393,11 @@ ServerInterceptor secondInterceptor(DiscoveryState state) { } } + @GrpcService + static class CreatedRosterService + extends CanonicalGameplayRosterOwnerReadServiceGrpc + .CanonicalGameplayRosterOwnerReadServiceImplBase {} + @GrpcService static class DiscoveredService implements BindableService { private final DiscoveryState state; diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java index d21104276b..1d67f596b4 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/NoGrpcServerTestConfiguration.java @@ -6,6 +6,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.GrpcServiceConfigurer; import org.springframework.grpc.server.service.GrpcServiceDiscoverer; /** Shared test configuration for contexts that should not start or discover real gRPC servers. */ @@ -18,6 +19,12 @@ GrpcServerLifecycle grpcServerLifecycle() { return mock(GrpcServerLifecycle.class); } + @Bean + @Primary + GrpcServiceConfigurer grpcServiceConfigurer() { + return mock(GrpcServiceConfigurer.class); + } + @Bean @Primary GrpcServiceDiscoverer grpcServiceDiscoverer() { diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java index c23e44afa2..cb3f589650 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java @@ -269,6 +269,9 @@ public CanonicalSelectedPlayerCreatedCharacterResponse readSelected( String digest = CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( request.getCanonicalAccountUuid(), target, sourceIdentity, wireActors); + if (!digest.equals(request.getExpectedSnapshot().getSnapshotDigest())) { + throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); + } CanonicalPlayerCreatedRosterResponse readback = readBackSnapshot( tx, @@ -279,12 +282,6 @@ public CanonicalSelectedPlayerCreatedCharacterResponse readSelected( sourceIdentity.toByteArray(), wireActors, digest); - if (!readback - .getRoster() - .getSnapshotDigest() - .equals(request.getExpectedSnapshot().getSnapshotDigest())) { - throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); - } long selectedCount = actors.stream() .filter( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 0530ecd37b..95a17b43dc 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -907,7 +907,9 @@ private static EntityCharacterCreateProofs proof( byte[] bytes = raw.getBytes(StandardCharsets.UTF_8); CharacterCreateOperatorAction action = CharacterCreateOperatorActionCodec.decode(bytes); if (rosterSource != null) { - action = requireRosterSourceAction(action, entitySource, accountId, rosterSource); + action = + ControlledPlayerCreatedOwnerStoreFixture.rosterSourceAction( + entitySource, accountId, rosterSource); bytes = CharacterCreateOperatorActionCodec.encode(action); } Instant controlledOwnerReadsAt = @@ -993,115 +995,6 @@ private static EntityCharacterCreateProofs proof( return proof; } - private static CharacterCreateOperatorAction requireRosterSourceAction( - CharacterCreateOperatorAction original, - EntityEmptySelectedSourceIntakeReceipt entitySource, - UUID accountId, - AuthenticatedSource source) { - var target = source.target(); - var request = source.response().getRequest(); - var catalog = source.response().getCatalog(); - var pointer = source.response().getPointer(); - var projection = source.authored().projections().getFirst(); - if (!entitySource.targetNamespace().equals(request.getTargetNamespace()) - || !entitySource.canonicalTenantId().equals(target.tenantUuid()) - || !entitySource.canonicalVersionId().equals(target.canonicalVersionUuid()) - || !entitySource.selectedCommitId().equals(projection.selectedCommitId())) { - throw new IllegalArgumentException( - "Controlled Entity writer fixture does not match the authenticated publication source"); - } - var authored = authoredSource(projection); - return new CharacterCreateOperatorAction( - new CharacterCreateOperatorAction.Scope( - request.getTargetNamespace(), - target.tenantUuid().toString(), - target.playableStateNamespaceId().toString(), - CharacterCreateOperatorAction.PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), - new CharacterCreateOperatorAction.Target( - accountId.toString(), - target.realmUuid().toString(), - target.worldSlug(), - target.realmSlug(), - target.gameInstanceUuid().toString(), - target.canonicalVersionUuid().toString()), - new CharacterCreateOperatorAction.ExpectedVersion( - Long.toString(target.catalogRevision()), - Long.toString(target.pointerVersion()), - Long.toString(target.activeWorldEpoch()), - EntityCharacterCreateBindings.instant(pointer.getUpdatedAt()).plusSeconds(1), - EntityCharacterCreateBindings.instant(pointer.getUpdatedAt()).plusSeconds(301)), - new CharacterCreateOperatorAction.Mutation( - original.mutation().purpose(), - original.mutation().entryPolicy(), - new CharacterCreateOperatorAction.Catalog( - target.tenantUuid().toString(), - catalog.getTenantSlug(), - target.worldSlug(), - catalog.getWorldDisplayName(), - target.realmUuid().toString(), - target.realmSlug(), - catalog.getRealmDisplayName(), - catalog.getVisible(), - catalog.getPublicProduction(), - catalog.getStateScope(), - target.playableStateNamespaceId().toString(), - catalog.getCharacterCreationPolicy(), - Long.toString(target.catalogRevision())), - new CharacterCreateOperatorAction.Pointer( - target.tenantUuid().toString(), - target.realmUuid().toString(), - target.worldSlug(), - target.realmSlug(), - pointer.getAdmissionState(), - target.gameInstanceUuid().toString(), - Long.toString(target.pointerVersion()), - Long.toString(target.catalogRevision()), - EntityCharacterCreateBindings.instant(pointer.getUpdatedAt())), - authored, - original.mutation().canonicalCreationInput()), - original.auditReason()); - } - - private static CharacterCreateOperatorAction.AuthoredSource authoredSource( - AuthoredInitialActorCoreProjection projection) { - var policy = projection.policy(); - return new CharacterCreateOperatorAction.AuthoredSource( - AuthoredInitialActorCoreProjection.SCHEMA, - projection.bindingId().toString(), - projection.bindingDigest(), - projection.canonicalTenantId().toString(), - projection.canonicalVersionId().toString(), - projection.worldSourceOperationId().toString(), - projection.worldSourceEvidenceDigest(), - projection.worldSlug(), - projection.publicationWorkflowId(), - projection.selectedCommitId().toString(), - projection.selectedCommitDigest(), - new CharacterCreateOperatorAction.Policy( - policy.commitId().toString(), - policy.revisionId().toString(), - policy.logicalRevisionId(), - policy.canonicalJson(), - policy.contentDigest()), - new CharacterCreateOperatorAction.Core(projection.core().canonicalJson()), - new CharacterCreateOperatorAction.Descriptor( - projection.descriptor().canonicalJson(), projection.descriptor().digest()), - authoredRule(projection.disposition()), - authoredRule(projection.safeFeedback())); - } - - private static CharacterCreateOperatorAction.Rule authoredRule( - AuthoredInitialActorCoreProjection.RuleDefinition rule) { - return new CharacterCreateOperatorAction.Rule( - rule.key(), - rule.definitionJson(), - rule.definitionDigest(), - rule.sourceCommitId().toString(), - rule.sourceCommitDigest(), - rule.revisionId().toString(), - rule.revisionOrder()); - } - private static PublishedIdentity published(EntityCharacterCreateProofs proof) throws Exception { return published(proof, null); } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java index 860910cbf7..c085c26aba 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java @@ -725,6 +725,28 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E selectedRequest, inputs.source(), wrongNamespaceOriginal)) .isInstanceOf(IllegalArgumentException.class); + var beforeQuarantineSnapshot = + dsl.fetchSingle( + "SELECT to_jsonb(s)::text AS row_json, xmin::text AS row_version FROM entity_canonical_gameplay_roster_snapshots s WHERE snapshot_uuid = ?", + UUID.fromString(snapshot.getRoster().getSnapshotUuid())); + var beforeQuarantineCounts = rosterRowCounts(); + assertThat( + dsl.execute( + "UPDATE characters SET actor_identity_status='QUARANTINED', actor_identity_quarantine_reason='OWNER_PROVENANCE_REVOKED' WHERE character_uuid=? AND actor_identity_status='OWNER_RESOLVED'", + actorId)) + .isOne(); + assertThatThrownBy( + () -> + snapshotRepository.readSelected(selectedRequest, inputs.source(), selectedOriginal)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_SNAPSHOT_STALE"); + assertThat(rosterRowCounts()).isEqualTo(beforeQuarantineCounts); + assertThat( + dsl.fetchSingle( + "SELECT to_jsonb(s)::text AS row_json, xmin::text AS row_version FROM entity_canonical_gameplay_roster_snapshots s WHERE snapshot_uuid = ?", + UUID.fromString(snapshot.getRoster().getSnapshotUuid()))) + .isEqualTo(beforeQuarantineSnapshot); + UUID recoveryId = UUID.randomUUID(); var recoveryRequest = CanonicalGameplayRosterRecoveryRequest.newBuilder() diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java index e36c3c3ebd..3df1920192 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java @@ -591,6 +591,31 @@ void createdOwnerDeadlineMapsToUnavailableWithoutInternalMetric() { assertThat(meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count()).isZero(); } + @Test + void changedCreatedSnapshotReturnsFailedPreconditionWithoutInternalMetric() { + var createdService = mock(EntityPlayerCreatedRosterService.class); + var request = selectedCreatedRequest(); + when(createdService.selected(request)) + .thenThrow(new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE")); + var meters = new SimpleMeterRegistry(); + var adapter = + new CanonicalGameplayRosterGrpcAdapter( + mock(CanonicalGameplayRosterService.class), + mock(CanonicalGameplayRosterSelectedAssignmentService.class), + createdService, + meters); + var observer = + new RecordingObserver< + net.firedevops.firemud.entitymanagement.v1 + .CanonicalSelectedPlayerCreatedCharacterResponse>(); + withTrustedPeer( + CanonicalGameplayRosterPeerInterceptor.SELECTED_PLAYER_CREATED_METHOD_NAME, + () -> adapter.readSelectedPlayerCreatedCharacter(request, observer)); + assertOnlyStatus(observer, Status.Code.FAILED_PRECONDITION); + assertThat(meters.counter("grpc.app_error", "code", "INTERNAL").count()).isZero(); + verify(createdService).selected(request); + } + @Test void expectedOwnerRejectionsReturnFailedPreconditionWithoutPartialResponse() { for (String reasonCode : diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java index 94efeb2018..51dd572c20 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/charactercreate/ControlledPlayerCreatedOwnerStoreFixture.java @@ -322,7 +322,7 @@ private static CharacterCreateProtectionReference protectionReference() { .build(); } - private static CharacterCreateOperatorAction rosterSourceAction( + public static CharacterCreateOperatorAction rosterSourceAction( EntityEmptySelectedSourceIntakeReceipt entitySource, UUID accountId, AuthenticatedSource source) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java index ab999a9a45..d74a4681bb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -777,6 +777,17 @@ private Server server(LoopbackMtlsTestPki.Pki pki, String alias, BindableService net.firedevops.firemud.common.grpc.GrpcRequestBytePolicy.ordinary(); default -> throw new IllegalArgumentException("Unknown controlled owner server role"); }; + var transportProperties = + new org.springframework.boot.context.properties.bind.Binder( + new org.springframework.boot.context.properties.source + .MapConfigurationPropertySource( + java.util.Map.of( + "spring.grpc.server.max-inbound-message-size", + bytePolicy.transportMaximumBytes() + "B"))) + .bind( + "spring.grpc.server", + org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties.class) + .get(); var factory = new net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory( "127.0.0.1:0", @@ -785,7 +796,7 @@ private Server server(LoopbackMtlsTestPki.Pki pki, String alias, BindableService pki.trustManagerFactory(), io.grpc.TlsServerCredentials.ClientAuth.REQUIRE, bytePolicy, - bytePolicy.transportMaximumBytes()); + Math.toIntExact(transportProperties.getMaxInboundMessageSize().toBytes())); for (var service : services) factory.addService( ServerInterceptors.intercept( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index 941a73b17f..1379095d14 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -2672,6 +2672,17 @@ void createdOriginalSurvivesSqlAndProductionMtlsOwnerReadAcknowledgementAndConfi var bytePolicy = new net.firedevops.firemud.gamesession.config.GameSessionGrpcRequestByteConfiguration() .gameSessionGrpcRequestBytePolicy(); + var transportProperties = + new org.springframework.boot.context.properties.bind.Binder( + new org.springframework.boot.context.properties.source + .MapConfigurationPropertySource( + java.util.Map.of( + "spring.grpc.server.max-inbound-message-size", + bytePolicy.transportMaximumBytes() + "B"))) + .bind( + "spring.grpc.server", + org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties.class) + .get(); var serverFactory = new net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory( "127.0.0.1:0", @@ -2680,7 +2691,7 @@ void createdOriginalSurvivesSqlAndProductionMtlsOwnerReadAcknowledgementAndConfi pki.trustManagerFactory(), io.grpc.TlsServerCredentials.ClientAuth.REQUIRE, bytePolicy, - bytePolicy.transportMaximumBytes()); + Math.toIntExact(transportProperties.getMaxInboundMessageSize().toBytes())); serverFactory.addService( io.grpc.ServerInterceptors.intercept( adapter, new net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor())); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java index 01fc9ab395..f1d5c6d6db 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java @@ -36,12 +36,14 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptClaim; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.service.FreshGameSessionTenantAssociation; +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.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -73,6 +75,11 @@ class GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @Test void v1013UpgradePreservesCombinedHistoryAndExistingOwnerRows() throws Exception { try (Fixture fixture = newFixture("1012")) { 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 86ed6859e5..5b077d0b50 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 @@ -21,6 +21,7 @@ import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException; import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository.PreparedInitialPublicProduction; import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; @@ -30,6 +31,7 @@ import org.jooq.SQLDialect; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -56,6 +58,11 @@ class GameSessionCanonicalRealmCatalogRepositoryIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @Test void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumericEvidence() { Fixture fixture = fixture(true); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java index 454b9c41d4..747bf7223f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -45,6 +45,7 @@ import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalConflictException; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository.JournalUnavailableException; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -93,6 +94,7 @@ class InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest { @BeforeAll static void controlledSigningKey() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); var generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(3072); keys = generator.generateKeyPair(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java index 296fa67c4d..93b5e15213 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java @@ -33,12 +33,14 @@ import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.AttemptSnapshot; import net.firedevops.firemud.gamesession.repository.GameSessionStartSessionOperatorAttemptRepository.ReservationResult; import net.firedevops.firemud.gamesession.service.GameSessionStartSessionOperatorAuthorizationCoordinator; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -74,6 +76,11 @@ class GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @Test void postgresClaimIsCommittedBeforeAccountAndExactRetryDoesNotRedeemAgain() throws Exception { Fixture fixture = fixture(Duration.ofSeconds(30)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 496610b03c..057567614c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -11,11 +11,13 @@ import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; import net.firedevops.firemud.gamesession.service.impl.DatabaseInitialAdmissionBindOwnerService; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -35,6 +37,11 @@ class InitialAdmissionBindPostgresIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + @Test void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFailsClosed() { DriverManagerDataSource dataSource = dataSource(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java index 8dc185df0a..627f0ccb5c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java @@ -49,6 +49,17 @@ void onlyGeneratedAcknowledgementAndConfirmationDescriptorsReceiveLargeAdmission var policy = new GameSessionGrpcRequestByteConfiguration().gameSessionGrpcRequestBytePolicy(); assertThat(policy.transportMaximumBytes()) .isEqualTo(CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + var transportProperties = + new org.springframework.boot.context.properties.bind.Binder( + new org.springframework.boot.context.properties.source + .MapConfigurationPropertySource( + java.util.Map.of( + "spring.grpc.server.max-inbound-message-size", + policy.transportMaximumBytes() + "B"))) + .bind( + "spring.grpc.server", + org.springframework.boot.grpc.server.autoconfigure.GrpcServerProperties.class) + .get(); var factory = new BoundedGrpcServerFactory( "127.0.0.1:0", @@ -57,7 +68,7 @@ void onlyGeneratedAcknowledgementAndConfirmationDescriptorsReceiveLargeAdmission null, TlsServerCredentials.ClientAuth.NONE, policy, - policy.transportMaximumBytes()); + Math.toIntExact(transportProperties.getMaxInboundMessageSize().toBytes())); Map parsedMessages = new HashMap<>(); factory.addService( recordOriginalMessages( diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java index ed0eca9cac..1515193573 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java @@ -142,21 +142,21 @@ private static GatewayHolder startGateway(String upstreamUrl) { TEST_UPSTREAM_URL.set(upstreamUrl); return new GatewayHolder( ReactiveTestApplicationSupport.startReactiveApp( - Map.of( - "spring.profiles.active", - "test", - "spring.flyway.enabled", - "false", - "firemud.database.enabled", - "false", - GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT, - "", - GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER, - ""), + Map.ofEntries( + Map.entry("spring.profiles.active", "test"), + Map.entry("spring.flyway.enabled", "false"), + Map.entry("firemud.database.enabled", "false"), + propertyEntry(GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT), + propertyEntry(GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER)), SpringCloudGatewayApplication.class, GatewayBridgeTestOverrideConfiguration.class)); } + private static Map.Entry propertyEntry(String assignment) { + int separator = assignment.indexOf('='); + return Map.entry(assignment.substring(0, separator), assignment.substring(separator + 1)); + } + private record GatewayHolder(ReactiveTestApplicationSupport.ReactiveAppHolder app) { String websocketUrl() { return app.websocketUrl(); @@ -185,13 +185,13 @@ static UpstreamHolder start(int port) { Map.entry("spring.main.allow-bean-definition-overriding", "true"), Map.entry("spring.flyway.enabled", "false"), Map.entry("firemud.database.enabled", "false"), - Map.entry(GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT, ""), - Map.entry(GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED, ""), - Map.entry(GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH, ""), - Map.entry(GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH, ""), - Map.entry(GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH, ""), + propertyEntry(GatewayTestProperties.SPRING_GRPC_SERVER_RANDOM_PORT), + propertyEntry(GatewayTestProperties.SPRING_GRPC_SERVER_SSL_DISABLED), + propertyEntry(GatewayTestProperties.FIREMUD_GRPC_CERT_CHAIN_PATH), + propertyEntry(GatewayTestProperties.FIREMUD_GRPC_PRIVATE_KEY_PATH), + propertyEntry(GatewayTestProperties.FIREMUD_GRPC_CA_CERT_PATH), Map.entry("firemud.grpc.plaintext", "true"), - Map.entry(GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER, "")), + propertyEntry(GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER)), UpstreamStubApplication.class); return new UpstreamHolder(app.context(), app.port()); } @@ -265,6 +265,7 @@ ReactorResourceFactory reactorResourceFactory() { } @Configuration + @Import(NoGrpcServerTestConfiguration.class) static class GatewayBridgeTestOverrideConfiguration { @Bean @Primary diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java index fb499af3a2..9436e1439c 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.springcloudgateway.config.GatewayTcpProxyListenerProperties; import net.firedevops.firemud.springcloudgateway.config.TcpProxyTlsListener; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; +import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.TlsTestSupport; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -56,7 +57,9 @@ class TcpProxyTlsListenerAdmissionIntegrationTest { @Test void productionConfigurationMapsHealthAndReadinessWhenInternalTlsIsDisabled() { - SpringApplication application = new SpringApplication(SpringCloudGatewayApplication.class); + SpringApplication application = + new SpringApplication( + SpringCloudGatewayApplication.class, NoGrpcServerTestConfiguration.class); application.setWebApplicationType(WebApplicationType.REACTIVE); try (ConfigurableApplicationContext context = From fe5d7f432c0fc3e16c252512faf12bbbed7dd134 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:45:27 +1300 Subject: [PATCH 20/22] Prove classification shape and proof budgets survive migrations --- ...osterRetentionPostgresIntegrationTest.java | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java index f38f62102c..395fd46a7e 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java @@ -115,6 +115,119 @@ void oldProtectedSnapshotDoesNotContributeToOldestBlockingRetirement() { assertThat(health.cleanupLagSeconds()).isZero(); } + @Test + void latestMigrationsRetainClassificationShapeAndSeparateProofBudgets() { + transaction.executeWithoutResult( + ignored -> { + var liveChecks = + dsl.fetch( + "SELECT t.relname AS table_name, pg_get_constraintdef(c.oid) AS definition " + + "FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid " + + "JOIN pg_namespace n ON n.oid = t.relnamespace " + + "WHERE c.contype = 'c' AND n.nspname = current_schema() " + + "AND t.relname IN ('entity_canonical_roster_target_classifications', " + + "'entity_canonical_roster_snapshot_targets', 'entity_canonical_roster_retired_targets')"); + assertThat(liveChecks.getValues("table_name", String.class)) + .contains( + "entity_canonical_roster_target_classifications", + "entity_canonical_roster_snapshot_targets", + "entity_canonical_roster_retired_targets"); + assertThat(liveChecks.getValues("definition", String.class)) + .anySatisfy( + definition -> + assertThat(definition) + .contains("classification_state", "target_binding", "retirement_proof") + .doesNotContain("octet_length(retirement_proof)")); + assertProofBudget( + liveChecks, + "entity_canonical_roster_target_classifications", + "octet_length(retirement_proof)", + "203423744", + "131072"); + assertProofBudget( + liveChecks, + "entity_canonical_roster_snapshot_targets", + "octet_length(source_retirement_proof)", + "203423744", + "131072"); + assertProofBudget( + liveChecks, + "entity_canonical_roster_retired_targets", + "octet_length(owner_retirement_proof)", + "203423744"); + + // This clone inherits the actual latest-migration CHECKs. It contains synthetic bytes + // only: no source triggers or owner evidence are copied, so these probes prove storage + // shape constraints and do not qualify an authenticated source or retirement authority. + dsl.execute( + "CREATE TEMP TABLE roster_classification_constraint_probe " + + "(LIKE entity_canonical_roster_target_classifications INCLUDING CONSTRAINTS INCLUDING DEFAULTS) " + + "ON COMMIT DROP"); + byte[] target = "target-binding".getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] proof = "synthetic-proof".getBytes(java.nio.charset.StandardCharsets.UTF_8); + insertClassificationProbe("ADMISSION", "UNKNOWN", null, null, null); + insertClassificationProbe("ADMISSION", "KNOWN", target, digest(target), null); + + assertRejectedClassificationProbe("ADMISSION", "UNKNOWN", target, digest(target), null); + assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, null, null); + assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, "0".repeat(64), null); + assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, digest(target), proof); + assertRejectedClassificationProbe("TRANSFER", "KNOWN", target, digest(target), proof); + assertRejectedClassificationProbe( + "TRANSFER_RETIREMENT", "KNOWN", target, digest(target), null); + }); + } + + private void assertProofBudget( + org.jooq.Result checks, + String tableName, + String columnExpression, + String... bounds) { + assertThat(checks) + .anySatisfy( + row -> { + assertThat(row.get("table_name", String.class)).isEqualTo(tableName); + String definition = row.get("definition", String.class); + assertThat(definition).contains(columnExpression).contains(bounds); + }); + } + + private void assertRejectedClassificationProbe( + String sourceKind, String state, byte[] target, String targetDigest, byte[] proof) { + dsl.execute("SAVEPOINT roster_shape_probe"); + assertThatThrownBy( + () -> insertClassificationProbe(sourceKind, state, target, targetDigest, proof)) + .isInstanceOf(DataAccessException.class); + dsl.execute("ROLLBACK TO SAVEPOINT roster_shape_probe"); + dsl.execute("RELEASE SAVEPOINT roster_shape_probe"); + } + + private void insertClassificationProbe( + String sourceKind, String state, byte[] target, String targetDigest, byte[] proof) { + dsl.execute( + "INSERT INTO roster_classification_constraint_probe " + + "(source_kind, operation_uuid, admission_uuid, source_binding, classification_state, " + + "target_binding, target_digest, retirement_proof) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + sourceKind, + UUID.randomUUID(), + UUID.randomUUID(), + new byte[] {1}, + state, + target, + targetDigest, + proof); + } + + private String digest(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is required by the JVM", impossible); + } + } + @Test void retirementHealthStartsAfterStoredHorizonAndKeepsPayloadAndCleanupLag() { var local = localRequest(); From 7f2fda0b6ead5d1dcf734299cfea119f46271c8b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:14:41 +1300 Subject: [PATCH 21/22] Refuse fresh empty created rosters that hide retained actors --- .../api-contracts.md | 2 +- .../player-access-and-session.md | 2 +- .../EntityCharacterCreateRepository.java | 43 +++++++++++++ ...PlayerCreatedRosterSnapshotRepository.java | 4 +- ...haracterCreatePostgresIntegrationTest.java | 60 ++++++++++++++++++- ...RosterSnapshotPostgresIntegrationTest.java | 58 ++++++++++++++++++ 6 files changed, 162 insertions(+), 7 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 8e4473802e..80445d859a 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -86,7 +86,7 @@ grpcurl -plaintext localhost:6565 entity_management.v1.EntityManagementService/P `CanonicalGameplayRosterService.ListPlayerCreatedRoster(CanonicalPlayerCreatedRosterRequest)` and `ReadSelectedPlayerCreatedCharacter(CanonicalSelectedPlayerCreatedCharacterRequest)` are distinct non-admitting Entity owner reads. They require the exact authenticated same-namespace Game Session workload over mTLS and a closed `PlayerExecutionContext` whose operation, account, session, tenant, realm, playable namespace/scope and runtime instance agree with the request and full target. Listing has no selected actor; selected readback requires `context.character_id` to equal the requested actor. Entity independently obtains and compares the complete current published `PLAYER_CREATED` source, descriptor, policy, canonical version and `SHARED` target before local work. Missing, changed or unsupported source evidence fails closed. `ListPreseededRoster` and `ReadSelectedPreseededAssignment` remain strictly `PRESEEDED_ONLY`; `AUTO_PROVISIONED` is unsupported by these roster methods. -The request carries the exact expected source identity: schema version 1, canonical non-nil descriptor UUID and revision UUID, descriptor digest, authored-binding UUID and authored-binding digest. Both digests use `sha256:` followed by 64 lowercase hexadecimal characters. The response retains that source identity and an ordered projection of persisted eligible actors with an immutable Entity snapshot UUID and digest. Zero actors is a valid empty snapshot and allocates none. The created digest uses domain `firemud.entity.player-created-roster.v1` and binds the canonical account, complete canonical target, exact source identity and ordered actor UUID/display-name pairs; it does not replace or recompute retained preseeded digests. The owner-issued policy digest remains distinct from authored projection content digests. Source identity and parsed wire values are comparison evidence, not peer authentication or an Account, membership, creation or admission capability. +The request carries the exact expected source identity: schema version 1, canonical non-nil descriptor UUID and revision UUID, descriptor digest, authored-binding UUID and authored-binding digest. Both digests use `sha256:` followed by 64 lowercase hexadecimal characters. The response retains that source identity and an ordered projection of persisted eligible actors with an immutable Entity snapshot UUID and digest. Zero actors is a valid empty snapshot only when no character is persisted for the exact tenant/account/namespace; when retained characters exist but none are eligible, fresh discovery and capture fail with `FAILED_PRECONDITION` rather than issuing an empty receipt. The created digest uses domain `firemud.entity.player-created-roster.v1` and binds the canonical account, complete canonical target, exact source identity and ordered actor UUID/display-name pairs; it does not replace or recompute retained preseeded digests. The owner-issued policy digest remains distinct from authored projection content digests. Source identity and parsed wire values are comparison evidence, not peer authentication or an Account, membership, creation or admission capability. Selected readback names the same original Game Session operation UUID and retained menu/selection, account, session, complete target, source identity, frozen chosen actor UUID and snapshot UUID/digest. Entity requires that actor to occur exactly once in the original immutable roster and revalidates its actual persisted creation provenance. It returns the original `COMMITTED` `CHARACTER_CREATE` operation UUID, unchanged mutation digest and complete original terminal in `CanonicalSelectedPlayerCreatedCharacterResponse`; it never returns an assignment UUID or invents a replacement operation. Original creation runtime-instance/pointer/catalog counters are not durable actor identity and are not rewritten to the current route. Selected readback allocates no actor and requires the existing local admission nonce and original receipt. 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 7b1244ae5b..31b99fd08c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -10,7 +10,7 @@ This is a non-normative implementation tracker for player access and session. Ca The unregistered Game Session composition consumes the independently resolved current published source through Entity's distinct created-roster and selected-character reads, preserving full original creation terminals, frozen menu/actor choice and the typed original-operation receipt/recovery/retirement branch. The [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#player-created-roster-and-selected-character) owns the created evidence contract; [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md#player-created-original-roster-storage) records its local storage consequences. V1020 receipt storage does not include the separate canonical UUID runtime or creation-protection owners and supplies no Account protection or admission authority. -The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the bounded-retirement parent carry at `337f5b86665939c032b07122d391dd099ee2a4d1`, receiving #3295 `bd032b622d7696ebfeeab462d9c2907b9eed8765`. Its controlled initial owner-to-owner composition, additive typed retention, current affected Game Session checks, full Entity gate and fresh-image proof are qualified there; the earlier full Game Session gate at `c9774094d76097ade5dcc5530d346e4960e613d8` retains its separate attribution. Created recovery/retirement/ACK and current Human writer-refusal components remain separate proof: full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. +The [owning gameplay tracker](./gameplay-rules-entities-and-effects.md#player-created-owner-and-roster-preparation) records the current qualification checkpoints and known failed/recovery limits. Created recovery/retirement/ACK and current Human writer-refusal components remain separate proof: full causal current supersession after original issuance → recovery/retirement closure remains unrun at the guarded Human OPEN/Account protection and settlement boundary. Genuine source custody, production PKI, registration, public admission, activation and a genuine playable journey remain open. Qualified public source-read results below retain their separate source attribution. Game Session migration qualification follows the published created-reference V1020, recovery-scheduling V1021 and current forward binary-safe recovery guard V1022. Before receiving the unpublished canonical UUID runtime and creation-protection owners, verify the actual migration frontier and unused forward versions beyond it, preserve published SQL bytes, and prove the actual-parent upgrade and retained rows/history. Those separate owners remain unregistered; this status grants no runtime, protection or activation authority. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java index d0f11b482a..ed5fda1846 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java @@ -73,6 +73,9 @@ List readPlayerCreatedRoster( published.tenantId(), account.accountId(), published.playableStateNamespaceId()); + if (actors.isEmpty()) { + requireNoPersistedPlayerCreatedRosterActors(tx, account, published); + } var result = new java.util.ArrayList(actors.size()); for (Record actor : actors) { readStoredPlayerCreatedTerminal(tx, account, published, actor, false); @@ -141,6 +144,46 @@ static List readPlayerCreatedRosterWithinOwnerTran return List.copyOf(result); } + /** Reads a fresh roster capture and refuses empty results that hide retained actors. */ + static List readFreshPlayerCreatedRosterWithinOwnerTransaction( + DSLContext tx, + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterReadService.PublishedIdentity published) { + List actors = + readPlayerCreatedRosterWithinOwnerTransaction(tx, account, published); + if (actors.isEmpty()) { + requireNoPersistedPlayerCreatedRosterActors(tx, account, published); + } + return actors; + } + + /** + * Empty fresh discovery is valid only when no actor is retained for this exact owner scope. + * Quarantined and otherwise ineligible actors remain counted by creation and cannot be replaced. + */ + static void requireNoPersistedPlayerCreatedRosterActors( + DSLContext tx, + EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector account, + EntityPlayerCreatedRosterReadService.PublishedIdentity published) { + Objects.requireNonNull(tx, "tx"); + Objects.requireNonNull(account, "account"); + Objects.requireNonNull(published, "published"); + boolean hasPersistedActor = + Boolean.TRUE.equals( + tx.fetchSingle( + "SELECT EXISTS (SELECT 1 FROM characters WHERE tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ?)", + published.tenantId(), + account.accountId(), + published.playableStateNamespaceId()) + .get(0, Boolean.class)); + if (hasPersistedActor) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Fresh PLAYER_CREATED roster is unavailable while retained characters are ineligible") + .asRuntimeException(); + } + } + /** Reads one selected created terminal inside the caller's writable owner transaction. */ static EntityCharacterCreateTerminal readSelectedPlayerCreatedTerminalWithinOwnerTransaction( DSLContext tx, diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java index cb3f589650..ebb249fa11 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java @@ -124,8 +124,8 @@ public CanonicalPlayerCreatedRosterResponse capture( lockCreationRoster(tx, currentTarget, account.accountId()); List actors = - EntityCharacterCreateRepository.readPlayerCreatedRosterWithinOwnerTransaction( - tx, account, published); + EntityCharacterCreateRepository + .readFreshPlayerCreatedRosterWithinOwnerTransaction(tx, account, published); List wireActors = actors.stream() diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 95a17b43dc..0beb2d9ea4 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -517,13 +517,52 @@ void selectedReadReturnsExactCommittedTerminalAndRejectsOutOfRosterActors() thro } @Test - void emptyDiscoveryAllocatesNothingAndOmitsLegacyQuarantinedDecoys() throws Exception { + void emptyDiscoveryIgnoresOutOfScopeDecoysAndOmitsInScopeQuarantinedDecoys() throws Exception { var proof = proof(UUID.randomUUID(), UUID.randomUUID()); var published = published(proof); var account = new AuthenticatedAccountSelector(UUID.fromString(proof.action().target().accountId())); assertThat(repository.readPlayerCreatedRoster(account, published)).isEmpty(); assertThat(dsl.fetchCount(DSL.table("characters"))).isZero(); + dsl.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, 'PLAYABLE_STATE_SCOPE_SHARED')", + published.tenantId(), + published.playableStateNamespaceId()); + UUID otherTenant = UUID.randomUUID(); + UUID otherNamespace = UUID.randomUUID(); + dsl.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)", otherTenant); + dsl.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, 'PLAYABLE_STATE_SCOPE_SHARED')", + otherTenant, + published.playableStateNamespaceId()); + dsl.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, 'PLAYABLE_STATE_SCOPE_SHARED')", + published.tenantId(), + otherNamespace); + dsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_id, tenant_id, name) VALUES (?, ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 45, 87654, ?)", + UUID.randomUUID(), + UUID.randomUUID(), + published.tenantId(), + published.playableStateNamespaceId(), + "other account decoy"); + dsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_id, tenant_id, name) VALUES (?, ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 45, 87654, ?)", + UUID.randomUUID(), + account.accountId(), + otherTenant, + published.playableStateNamespaceId(), + "other tenant decoy"); + dsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_id, tenant_id, name) VALUES (?, ?, ?, ?, 'PLAYABLE_STATE_SCOPE_SHARED', 45, 87654, ?)", + UUID.randomUUID(), + account.accountId(), + published.tenantId(), + otherNamespace, + "other namespace decoy"); + assertThat(repository.readPlayerCreatedRoster(account, published)).isEmpty(); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(3); var terminal = repository.settle(proof, null); dsl.execute( @@ -537,7 +576,7 @@ void emptyDiscoveryAllocatesNothingAndOmitsLegacyQuarantinedDecoys() throws Exce .containsExactly( new net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor( UUID.fromString(terminal.getCharacterId()), "Wayfarer")); - assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(2); + assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(5); } @Test @@ -1142,6 +1181,8 @@ private static void assertCreatedActorQuarantineBoundary( characterId) .get(0, String.class)) .isEqualTo(immutableActorBefore); + String quarantinedActor = retainedRow(ownerDsl, "characters", "character_uuid", characterId); + long characterCountBeforeFreshRead = ownerDsl.fetchCount(DSL.table("characters")); assertThat( retainedOperationRow( ownerDsl, @@ -1159,7 +1200,20 @@ private static void assertCreatedActorQuarantineBoundary( .hasStackTraceContaining("CHARACTER_CREATE authored identity/provenance is immutable"); var published = published(proof); var account = new AuthenticatedAccountSelector(accountId); - assertThat(ownerRepository.readPlayerCreatedRoster(account, published)).isEmpty(); + assertThatThrownBy(() -> ownerRepository.readPlayerCreatedRoster(account, published)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("FAILED_PRECONDITION") + .hasMessageContaining("Fresh PLAYER_CREATED roster is unavailable"); + assertThat(retainedRow(ownerDsl, "characters", "character_uuid", characterId)) + .isEqualTo(quarantinedActor); + assertThat( + retainedOperationRow( + ownerDsl, + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId()))) + .isEqualTo(operationBefore); + assertThat(ownerDsl.fetchCount(DSL.table("characters"))) + .isEqualTo(characterCountBeforeFreshRead); assertSelectedActorUnavailable(ownerRepository, account, published, characterId); assertThat(ownerRepository.replay(proof.request()).orElseThrow().toByteArray()) .containsExactly(terminal.toByteArray()); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java index c085c26aba..23f1b6781a 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java @@ -747,6 +747,64 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E UUID.fromString(snapshot.getRoster().getSnapshotUuid()))) .isEqualTo(beforeQuarantineSnapshot); + var originalReceiptReplay = + snapshotRepository.capture(inputs.request(), inputs.source(), inputs.original(), admission); + assertThat(originalReceiptReplay.toByteArray()).containsExactly(snapshot.toByteArray()); + var freshInputs = inputs(inputs.source(), accountId); + UUID freshAdmission = reserveAdmission(freshInputs.request()); + var actorBeforeFreshCapture = + dsl.fetchSingle( + "SELECT xmin::text AS row_version, to_jsonb(c)::text AS row_json FROM characters c WHERE character_uuid = ?", + actorId); + var terminalBeforeFreshCapture = + dsl.fetchSingle( + "SELECT xmin::text AS row_version, original_request, terminal_bytes, entity_source_receipt FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId())); + assertThatThrownBy( + () -> + snapshotRepository.capture( + freshInputs.request(), + freshInputs.source(), + freshInputs.original(), + freshAdmission)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageContaining("FAILED_PRECONDITION") + .hasMessageContaining("Fresh PLAYER_CREATED roster is unavailable"); + assertThat(rosterRowCounts()).isEqualTo(beforeQuarantineCounts); + assertThat( + dsl.fetchSingle( + "SELECT to_jsonb(s)::text AS row_json, xmin::text AS row_version FROM entity_canonical_gameplay_roster_snapshots s WHERE snapshot_uuid = ?", + UUID.fromString(snapshot.getRoster().getSnapshotUuid()))) + .isEqualTo(beforeQuarantineSnapshot); + var actorAfterFreshCapture = + dsl.fetchSingle( + "SELECT xmin::text AS row_version, to_jsonb(c)::text AS row_json FROM characters c WHERE character_uuid = ?", + actorId); + assertThat(actorAfterFreshCapture.get("row_version", String.class)) + .isEqualTo(actorBeforeFreshCapture.get("row_version", String.class)); + assertThat(actorAfterFreshCapture.get("row_json", String.class)) + .isEqualTo(actorBeforeFreshCapture.get("row_json", String.class)); + var terminalAfterFreshCapture = + dsl.fetchSingle( + "SELECT xmin::text AS row_version, original_request, terminal_bytes, entity_source_receipt FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", + proof.action().scope().targetNamespace(), + UUID.fromString(proof.original().getOperationId())); + assertThat(terminalAfterFreshCapture.get("row_version", String.class)) + .isEqualTo(terminalBeforeFreshCapture.get("row_version", String.class)); + assertThat(terminalAfterFreshCapture.get("original_request", byte[].class)) + .containsExactly(terminalBeforeFreshCapture.get("original_request", byte[].class)); + assertThat(terminalAfterFreshCapture.get("terminal_bytes", byte[].class)) + .containsExactly(terminalBeforeFreshCapture.get("terminal_bytes", byte[].class)); + assertThat(terminalAfterFreshCapture.get("entity_source_receipt", byte[].class)) + .containsExactly(terminalBeforeFreshCapture.get("entity_source_receipt", byte[].class)); + var failedAdmission = + dsl.fetchSingle( + "SELECT snapshot_uuid, admission_state FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", + UUID.fromString(freshInputs.request().getRequestUuid())); + assertThat(failedAdmission.get("snapshot_uuid", UUID.class)).isNull(); + assertThat(failedAdmission.get("admission_state", String.class)).isEqualTo("OPEN"); + UUID recoveryId = UUID.randomUUID(); var recoveryRequest = CanonicalGameplayRosterRecoveryRequest.newBuilder() From 1f5d97f2da4c75967f8eaee3fd0ee8d60fdb3e65 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:32:15 +1300 Subject: [PATCH 22/22] Stabilize created-roster proof and clarify classification input --- ...icalGameplayRosterRetentionRepository.java | 7 +++-- ...haracterCreatePostgresIntegrationTest.java | 28 +++++++++++++++++++ ...ayerCreatedRosterSourceClientMtlsTest.java | 4 +++ ...olledPlayerCreatedRosterSourceFixture.java | 1 + ...anonicalPlayerCreatedRosterClientTest.java | 6 ++-- 5 files changed, 42 insertions(+), 4 deletions(-) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java index 3392b41bf7..9a4fc496a9 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java @@ -39,6 +39,9 @@ value = "EI_EXPOSE_REP2", justification = "DSLContext is the owner transaction collaborator") public final class CanonicalGameplayRosterRetentionRepository { + // Admission bindings omit namespace; this valid placeholder only reconstructs comparison data. + private static final String CLASSIFICATION_ONLY_NAMESPACE = "retained-classification"; + private final DSLContext dsl; public CanonicalGameplayRosterRetentionRepository(DSLContext dsl) { @@ -1153,7 +1156,7 @@ private void classifySource(String kind, UUID operation, UUID admission) { operation, UUID.fromString(minimal.getCanonicalAccountUuid()), UUID.fromString(minimal.getPlayerExecutionContext().getSessionId()), - "entity", + CLASSIFICATION_ONLY_NAMESPACE, minimal.getExpectedTarget(), minimal.getExpectedSource()); if (!operation.toString().equals(minimal.getRequestUuid()) @@ -1173,7 +1176,7 @@ private void classifySource(String kind, UUID operation, UUID admission) { CanonicalGameplayRosterReferenceEvidence.uuid(request.getCanonicalAccountUuid()), CanonicalGameplayRosterReferenceEvidence.uuid( request.getPlayerExecutionContext().getSessionId()), - "retained-classification", + CLASSIFICATION_ONLY_NAMESPACE, canonicalTarget.toWire()); if (!operation.toString().equals(request.getRequestUuid()) || !Arrays.equals(original, admissionBinding(checked))) { diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index 0beb2d9ea4..fb0abfc27d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -516,6 +516,34 @@ void selectedReadReturnsExactCommittedTerminalAndRejectsOutOfRosterActors() thro assertThat(dsl.fetchCount(DSL.table("characters"))).isEqualTo(actorCountBefore); } + @Test + void standaloneCreatedRosterCannotExceedTheOwnerResolvedScopeUniqueIndex() throws Exception { + var proof = proof(UUID.randomUUID(), UUID.randomUUID()); + var terminal = repository.settle(proof, null); + UUID characterId = UUID.fromString(terminal.getCharacterId()); + String before = retainedRow(dsl, "characters", "character_uuid", characterId); + // Even a direct duplicate with retained terminal metadata cannot exceed the scope bound. + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) SELECT gen_random_uuid(), account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ?", + characterId)) + .isInstanceOf(org.jooq.exception.IntegrityConstraintViolationException.class) + .hasMessageContaining("ux_characters_owner_resolved_account_namespace"); + assertThat(dsl.fetchCount(DSL.table("characters"))).isOne(); + assertThat(retainedRow(dsl, "characters", "character_uuid", characterId)).isEqualTo(before); + assertThat( + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector( + UUID.fromString(proof.action().target().accountId())), + published(proof))) + .containsExactly( + new net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterActor( + characterId, "Wayfarer")); + assertThat(repository.replay(proof.request()).orElseThrow().toByteArray()) + .containsExactly(terminal.toByteArray()); + } + @Test void emptyDiscoveryIgnoresOutOfScopeDecoysAndOmitsInScopeQuarantinedDecoys() throws Exception { var proof = proof(UUID.randomUUID(), UUID.randomUUID()); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java index 4eca2550bf..34b132d0b6 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java @@ -541,6 +541,10 @@ void ownerGrpcFailuresRemainTransportStatuses(Status status, String description) assertThat(failure.getStatus().getDescription()).isEqualTo(description); }); assertThat(owner.receivedRequests()).containsExactly(fixture.request()); + owner.respondWith(fixture.response()); + assertThat(client.read(fixture.request()).response().toByteArray()) + .containsExactly(fixture.response().toByteArray()); + assertThat(owner.receivedRequests()).containsExactly(fixture.request(), fixture.request()); } } diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java index 4ea2d7b673..2906a10d89 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java @@ -199,6 +199,7 @@ public String observedPeerUri() { public void respondWith(ReadPlayerCreatedRosterSourceResponse nextResponse) { response.set(Objects.requireNonNull(nextResponse, "nextResponse")); + failure.set(null); } public void failWith(StatusRuntimeException nextFailure) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java index 6c6b4d86ed..bb13571b92 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java @@ -492,18 +492,20 @@ void actualBuiltStubPinsTheEntityPeerAndUsesCompressionDeadlineAndCreatedRosterB when(channels.buildChannel(anyString(), anyInt(), any(), anyBoolean())).thenReturn(channel); var client = client(false); client.init(); + var deadlineNotBefore = io.grpc.Deadline.after(20, TimeUnit.SECONDS); assertThatThrownBy(() -> client.listPlayerCreatedRoster(source, fixture.context())) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED)); + var deadlineNotAfter = io.grpc.Deadline.after(20, TimeUnit.SECONDS); var options = org.mockito.ArgumentCaptor.forClass(io.grpc.CallOptions.class); verify(channel).newCall(any(), options.capture()); assertThat(options.getValue().getCompressor()).isEqualTo("gzip"); assertThat(options.getValue().getMaxInboundMessageSize()).isEqualTo(66 * 1024); assertThat(options.getValue().getDeadline()).isNotNull(); - assertThat(options.getValue().getDeadline().timeRemaining(TimeUnit.MILLISECONDS)) - .isBetween(19_000L, 20_000L); + // Compare absolute deadlines so scheduling after the call cannot shrink the asserted budget. + assertThat(options.getValue().getDeadline()).isBetween(deadlineNotBefore, deadlineNotAfter); assertThat(options.getValue().getCredentials()) .isInstanceOf( net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials.class);