From a18dab712f9cec3975bf80c6526a38d3bc2be290 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:42:24 +1300 Subject: [PATCH 01/14] feat: prepare authenticated public character creation source reads --- .../api-contracts.md | 2 + .../game-session-service/api-contracts.md | 10 + .../player-access-and-session.md | 6 + .../v1/character_create_source_service.proto | 49 + .../v1/entity_character_create_service.proto | 63 + ...aracter_create_public_source_service.proto | 138 ++ ...essionTemplateAssociationReadEvidence.java | 7 +- .../PlayerCreatedPublishedPolicyFixtures.java | 255 ++++ .../build.gradle.kts | 1 + .../EntityCharacterCreateBindings.java | 152 +++ ...EntityPlayerCreatedRosterSourceClient.java | 389 ++++++ ...ayerCreatedRosterSourceClientMtlsTest.java | 1171 +++++++++++++++++ .../GameSessionCharacterCreateBinding.java | 120 ++ ...haracterCreatePublicSourceGrpcService.java | 165 +++ ...ionCharacterCreatePublicSourceService.java | 703 ++++++++++ .../GameDesignPublishedRealmPolicyClient.java | 11 +- .../CanonicalInitialAdmissionRepository.java | 61 + ...ialAdmissionRepositoryIntegrationTest.java | 18 + ...cterCreatePublicSourceGrpcServiceTest.java | 329 +++++ ...onCharacterCreatePublicSourceMtlsTest.java | 171 +++ ...haracterCreatePublicSourceServiceTest.java | 922 +++++++++++++ ...ignPublishedRealmPolicyClientMtlsTest.java | 156 +++ 22 files changed, 4895 insertions(+), 4 deletions(-) create mode 100644 protos/account/v1/character_create_source_service.proto create mode 100644 protos/entity-management/v1/entity_character_create_service.proto create mode 100644 protos/game-session/v1/character_create_public_source_service.proto create mode 100644 services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindings.java create mode 100644 services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreateBinding.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceMtlsTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index d0fd0c694e..cad1c06f56 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,6 +6,8 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status +The 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 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. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index cdabda7f9f..6f3bfb3b85 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -74,6 +74,16 @@ When the existing default-off fixture mode is enabled, the retained `RunOwnedIni The fresh canonical Human admission path also refuses preparation, commit and abort before intent reservation, World hold acquisition, pointer or audit effects while authenticated Account protection acquisition and terminal settlement are unavailable. Retained predecessor terminal records remain readable with their original bytes; storage retention does not qualify current Human execution. Existing legacy initial-bind and player flows keep their distinct boundaries. This containment supplies no strict Account `JOIN`, production activation or fixture first-`OPEN` authority; the [runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#canonical-fixture-launch-owner-stage) records current proof and remaining composition. +### Public character-creation source read + +The Entity-only roster response additionally carries the complete canonical sealed policy set from Game Design's [published realm-entry policy owner read](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read). Game Session independently reads and validates that set against the original authored association, full immutable release content and World launch, then requires exactly one matching schema-three `PLAYER_CREATED` policy with the same canonical policy, descriptor and source revision as the authored projection. Its owner-issued policy identity and `policyDigest` remain distinct from projection binding identities and content digests. The policy read occurs before final local and historical source revalidation; Account's two methods do not perform this additional RPC or carry the set. + +The same unregistered service exposes a distinct `ReadPlayerCreatedRosterSource` read to the exact same-namespace Entity Management workload certificate, rejecting Account callers, foreign namespaces and authenticated caller context; bearer credentials cannot substitute for the required certificate. Its closed selectors pin canonical tenant, realm, shared playable namespace, runtime instance, catalog and pointer revisions, expected canonical content version and active World epoch, without Account scope or evaluation/expiry timestamps. It preserves the existing original authored-source, historical launch and independent World `ACTIVE` readback composition, including full owner bytes and rereads of current local and historical source facts; expected version and epoch must still match after remote reads. The request is bounded to 16 KiB and the response to 32 MiB. Account's discovery and creation-source methods remain Account-only. This supplies current published `PLAYER_CREATED` policy and descriptor input for Entity's [actor-entry boundary](../entity-management-service/api-contracts.md#character-creation-owner-protection) under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md); it grants no roster assignment, Account authority, protection, activation or admission and does not widen the separate `PRESEEDED_ONLY` owner-read or assignment authority. + +The same unregistered Account-only workload family exposes `ResolveCharacterCreatePublicTarget` before scope issuance. Its closed request contains only schema version, read-request UUID, workload namespace and friendly world/realm slugs. Game Session resolves exactly one match through its actual canonical visible public-production route owner, requires `SHARED` and `PLAYER_CREATED`, and rereads the complete current route, catalog and `OPEN` pointer before returning their typed canonical identifiers, metadata, revisions, canonical content version, active epoch and actual pointer timestamp. Unknown, ambiguous, unsupported or changed targets fail closed. The response is bounded to 64 KiB, echoes the original request and contains no Account-issued scope, evaluation time, expiry, creation intent or membership authority. Account must independently authenticate bootstrap identity and issue its own canonical scope; friendly selectors and target discovery do not supply that authority. The request has the same 16 KiB bound and exact peer requirement as the source read below. + +The unregistered `CharacterCreatePublicSourceService.ReadCharacterCreatePublicSource` is a pre-intent source read for the exact same-namespace Account mTLS workload, without bearer or end-user-context substitutes. Its [closed protobuf contract](../../../../protos/game-session/v1/character_create_public_source_service.proto) accepts only expected canonical discovery selectors and echoes them exactly; those selectors establish no Account authentication or issued-scope authority. The initial supported source is visible public-production `SHARED` with `PLAYER_CREATED`, a current canonical `OPEN` pointer, an existing retained original authored-core source, and an independently read matching World `ACTIVE` lifecycle. The composition rereads the original Game Design source through the existing exact-replay codec and compares the complete retained bytes and digest, verifies the immutable historical StartSession association without renewing or reacquiring its claim, then rechecks the full local route, catalog, pointer, launch and retained source after remote reads. Its complete pointer source includes the actual pointer row's `updatedAt`, never a substituted terminal timestamp. Missing, conflicting, replaced, fixture-only or unsupported owner evidence fails closed. The request is bounded to 16 KiB and the complete response to 32 MiB, retaining the existing authored-source codec's 16 MiB wire and 8 MiB canonical-result bounds; downstream Account persistence and terminal budgets require separate qualification and must not truncate this source to fit. Registration remains absent; the adapter checks the closed request bound before owner work. This API constructs no Account action, acquires no protection, allocates no actor and establishes no admission or activation authority. + ### Canonical gameplay roster owner reads #### 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 c24a1263ed..d67e1db6e5 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,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Public character-creation and created-roster source preparation + +The local candidate prepares the unregistered Game Session public-target discovery and full creation-source reads, plus the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). + +This candidate has been materialized against the actual published roster-retention parent, but its independent candidate validation has not run. Earlier mixed-source proof retains its original attribution and does not qualify this comparison. The test publication/owner facts remain controlled; no genuine production source custody, created-actor roster/selection, runtime registration, protected activation or playable journey is established. The broader UUID runtime and CHARACTER_CREATE owners remain separate unfinished receiving work. + ### Retained Draft authorization fence migrations The [Account fence history fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java) executes the owning filesystem migrations from V75 through V76 and then the current default migration set. Its Account UUID and provenance come from PostgreSQL defaults; it retains the original v1 binding, commit order, stipulated World committed readback, missing Game Design outcome, pending source change and 512-byte source key. Every original column and row version in all six authorization ledger tables, and every prior complete Flyway history row, survives both upgrades. The expected V87 addition of one Global Roles serialization lock is checked separately; it supplies no authority evidence. Exact replay, current pending-mutation refusal and denied binding/readback rewrites leave the retained rows unchanged. diff --git a/protos/account/v1/character_create_source_service.proto b/protos/account/v1/character_create_source_service.proto new file mode 100644 index 0000000000..daff4da20d --- /dev/null +++ b/protos/account/v1/character_create_source_service.proto @@ -0,0 +1,49 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Unregistered receiving contract. Reads require an exact same-namespace creation protection +// owner workload: Entity Management, Game Session, or World Management. +// This API supplies original Account source readback, never Entity terminal/release authority. +service CharacterCreateSourceService { + rpc ReadOriginalCharacterCreate(ReadOriginalCharacterCreateRequest) + returns (ReadOriginalCharacterCreateResponse); + rpc ReadOriginalCharacterCreateProtection(ReadOriginalCharacterCreateProtectionRequest) + returns (ReadOriginalCharacterCreateProtectionResponse); +} + +message ReadOriginalCharacterCreateRequest { + string target_namespace = 1; + string operation_id = 2; + string mutation_digest = 3; +} + +message ReadOriginalCharacterCreateResponse { + string target_namespace = 1; + string operation_id = 2; + string create_character_request_id = 3; + string connect_scope_id = 4; + string authenticated_account_id = 5; + string purpose = 6; + bytes original_action = 7; + string mutation_digest = 8; + bytes original_source_readback = 9; +} + +message ReadOriginalCharacterCreateProtectionRequest { + ReadOriginalCharacterCreateRequest original = 1; + string account_protection_id = 2; + int64 account_protection_fence = 3; +} + +message ReadOriginalCharacterCreateProtectionResponse { + ReadOriginalCharacterCreateResponse original = 1; + string account_protection_id = 2; + int64 account_protection_fence = 3; + string acquired_at = 4; + bytes original_membership_snapshot = 5; + bytes original_entitlement_snapshot = 6; +} diff --git a/protos/entity-management/v1/entity_character_create_service.proto b/protos/entity-management/v1/entity_character_create_service.proto new file mode 100644 index 0000000000..b6278dbc4c --- /dev/null +++ b/protos/entity-management/v1/entity_character_create_service.proto @@ -0,0 +1,63 @@ +syntax = "proto3"; + +package entity_management.v1; +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +import "account/v1/character_create_source_service.proto"; + +// Unregistered exact-purpose owner boundary. Only Account may commit or explicitly abort; +// Account, Game Session and World independently authenticate to read the immutable terminal. +service EntityCharacterCreateService { + rpc CommitProtectedCharacterCreate(CommitProtectedCharacterCreateRequest) + returns (EntityCharacterCreateTerminal); + rpc AbortProtectedCharacterCreate(AbortProtectedCharacterCreateRequest) + returns (EntityCharacterCreateTerminal); + rpc ReadEntityCharacterCreateTerminal(ReadEntityCharacterCreateTerminalRequest) + returns (EntityCharacterCreateTerminal); +} + +message CharacterCreateProtectionReference { + string protection_id = 1; + int64 protection_fence = 2; +} + +// References only: the receiver reads each original directly from its authenticated owner. +message CommitProtectedCharacterCreateRequest { + account.v1.ReadOriginalCharacterCreateRequest original = 1; + CharacterCreateProtectionReference account_protection = 2; + CharacterCreateProtectionReference game_session_protection = 3; + CharacterCreateProtectionReference world_protection = 4; +} + +message AbortProtectedCharacterCreateRequest { + CommitProtectedCharacterCreateRequest creation = 1; + string abort_request_id = 2; +} + +message ReadEntityCharacterCreateTerminalRequest { + account.v1.ReadOriginalCharacterCreateRequest original = 1; +} + +enum EntityCharacterCreateOutcome { + ENTITY_CHARACTER_CREATE_OUTCOME_UNSPECIFIED = 0; + ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED = 1; + ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED = 2; +} + +message EntityCharacterCreateTerminal { + CommitProtectedCharacterCreateRequest original_request = 1; + account.v1.ReadOriginalCharacterCreateResponse account_original = 2; + bytes original_account_protection = 3; + bytes original_game_session_protection = 4; + bytes original_world_protection = 5; + // Full Entity selected-source receipt stays local under its existing 80 MiB bound. + string entity_intake_request_id = 6; + EntityCharacterCreateOutcome outcome = 7; + string character_id = 8; + string terminal_id = 9; + int64 terminal_fence = 10; + string completed_at = 11; + string abort_request_id = 12; + string entity_source_receipt_digest = 13; +} diff --git a/protos/game-session/v1/character_create_public_source_service.proto b/protos/game-session/v1/character_create_public_source_service.proto new file mode 100644 index 0000000000..4e68448253 --- /dev/null +++ b/protos/game-session/v1/character_create_public_source_service.proto @@ -0,0 +1,138 @@ +syntax = "proto3"; + +package game_session.v1; + +import "game-design/v1/authored_initial_actor_core_read.proto"; + +option java_package = "net.firedevops.firemud.gamesession.v1"; +option java_multiple_files = true; + +// Unregistered same-namespace workload reads with method-specific Account or Entity peers. +// Selectors are comparison inputs, never Account, launch, protection or admission authority. +service CharacterCreatePublicSourceService { + // Pre-scope discovery: canonical identities come only from actual Game Session owner rows. + rpc ResolveCharacterCreatePublicTarget(ResolveCharacterCreatePublicTargetRequest) + returns (ResolveCharacterCreatePublicTargetResponse); + rpc ReadCharacterCreatePublicSource(ReadCharacterCreatePublicSourceRequest) + returns (ReadCharacterCreatePublicSourceResponse); + // Entity-only published PLAYER_CREATED roster input; carries no Account-issued scope or clock. + rpc ReadPlayerCreatedRosterSource(ReadPlayerCreatedRosterSourceRequest) + returns (ReadPlayerCreatedRosterSourceResponse); +} + +message ReadPlayerCreatedRosterSourceRequest { + uint32 schema_version = 1; + string read_request_id = 2; + string target_namespace = 3; + string canonical_tenant_id = 4; + string realm_id = 5; + string world_slug = 6; + string realm_slug = 7; + string playable_state_namespace_id = 8; + string playable_state_scope = 9; + string canonical_game_instance_id = 10; + int64 catalog_revision = 11; + int64 pointer_version = 12; + string expected_canonical_version_id = 13; + int64 active_world_epoch = 14; +} + +message ReadPlayerCreatedRosterSourceResponse { + uint32 schema_version = 1; + ReadPlayerCreatedRosterSourceRequest request = 2; + CharacterCreatePublicCatalog catalog = 3; + CharacterCreatePublicPointer pointer = 4; + string canonical_version_id = 5; + int64 active_lifecycle_epoch = 6; + string original_control_plane_request_id = 7; + string original_owner_attempt_id = 8; + int64 original_owner_fence = 9; + game_design.v1.ReadAuthoredInitialActorCoreResponse authored_source = 10; + bytes world_lifecycle_evidence = 11; + // Actual owner-sealed policy identities and digests, not authored-projection content digests. + bytes published_policy_set_evidence = 12; +} + +message ResolveCharacterCreatePublicTargetRequest { + uint32 schema_version = 1; + string read_request_id = 2; + string target_namespace = 3; + string world_slug = 4; + string realm_slug = 5; +} + +message ResolveCharacterCreatePublicTargetResponse { + uint32 schema_version = 1; + ResolveCharacterCreatePublicTargetRequest request = 2; + CharacterCreatePublicCatalog catalog = 3; + CharacterCreatePublicPointer pointer = 4; + string canonical_game_instance_id = 5; + string canonical_version_id = 6; + int64 active_lifecycle_epoch = 7; +} + +message ReadCharacterCreatePublicSourceRequest { + uint32 schema_version = 1; + string read_request_id = 2; + string target_namespace = 3; + string canonical_tenant_id = 4; + string realm_id = 5; + string world_slug = 6; + string realm_slug = 7; + string playable_state_namespace_id = 8; + string playable_state_scope = 9; + string canonical_game_instance_id = 10; + int64 catalog_revision = 11; + int64 pointer_version = 12; + string evaluated_at = 13; + string connect_scope_expires_at = 14; +} + +message CharacterCreatePublicCatalog { + string tenant_id = 1; + string tenant_slug = 2; + string world_slug = 3; + string world_display_name = 4; + string realm_id = 5; + string realm_slug = 6; + string realm_display_name = 7; + bool visible = 8; + bool public_production = 9; + string state_scope = 10; + string playable_state_namespace_id = 11; + string character_creation_policy = 12; + int64 catalog_revision = 13; + string creation_request_id = 14; + string receipt_digest = 15; +} + +message CharacterCreatePublicPointer { + string tenant_id = 1; + string realm_id = 2; + string world_slug = 3; + string realm_slug = 4; + string admission_state = 5; + string admissible_game_instance_id = 6; + int64 pointer_version = 7; + int64 catalog_revision = 8; + string updated_at = 9; + string initial_admission_request_id = 10; + string initial_admission_owner_proof_digest = 11; + string admission_pointer_snapshot_digest = 12; +} + +message ReadCharacterCreatePublicSourceResponse { + uint32 schema_version = 1; + ReadCharacterCreatePublicSourceRequest request = 2; + CharacterCreatePublicCatalog catalog = 3; + CharacterCreatePublicPointer pointer = 4; + string canonical_version_id = 5; + int64 active_lifecycle_epoch = 6; + string original_control_plane_request_id = 7; + string original_owner_attempt_id = 8; + int64 original_owner_fence = 9; + // Existing closed owner codec; request preserves the exact original association/launch selectors. + game_design.v1.ReadAuthoredInitialActorCoreResponse authored_source = 10; + // Existing WorldCanonicalInstanceLifecycleEvidence canonical bytes, including its exact request. + bytes world_lifecycle_evidence = 11; +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java index 7658e47a9b..c350bc6a44 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java @@ -256,7 +256,7 @@ public record Result( "World published selector differs from exact association and release identity"); } requireNoUnknownFields(releaseBundle, "PublishedReleaseBundle"); - requireCompleteRelease(releaseBundle, worldPublishedStartLocationEvidence); + releaseContent(releaseBundle, worldPublishedStartLocationEvidence); if (request.selection() instanceof ExactReplay replay && (!replay.canonicalVersionId().equals(association.canonicalVersionId()) || !replay.selectedCommitId().equals(association.selectedCommitId()) @@ -311,7 +311,8 @@ private static void requireNoUnknownFields(Message message, String label) { } } - private static void requireCompleteRelease( + /** Maps the complete original bundle through the canonical immutable release-content contract. */ + public static GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( PublishedReleaseBundle bundle, WorldPublishedStartLocationEvidence worldEvidence) { if (bundle.getId() <= 0L || bundle.getVersionId() <= 0L @@ -346,7 +347,7 @@ private static void requireCompleteRelease( null, null)) .toList(); - new GameDesignPublicationTerminalEvidence.ReleaseContent( + return new GameDesignPublicationTerminalEvidence.ReleaseContent( UUID.fromString(bundle.getCanonicalTenantId()), UUID.fromString(bundle.getCanonicalVersionId()), bundle.getPublishedReleaseBundleRef(), diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java new file mode 100644 index 0000000000..ac0366deff --- /dev/null +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java @@ -0,0 +1,255 @@ +package net.firedevops.firemud.common.testing; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.WorldDraftTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed PLAYER_CREATED publication carriers for source receiver tests. Account authorization, + * World application/inventory and publication custody are controlled fixtures, not executed owners. + */ +public final class PlayerCreatedPublishedPolicyFixtures { + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private PlayerCreatedPublishedPolicyFixtures() {} + + /** Adds the existing controlled World graph to the receiver's selected authored source. */ + public static DraftCommitBinding withWorldSource(DraftCommitBinding source) throws Exception { + var original = AuthoringFixtures.freshGraphRequest().accountBinding(); + var graph = + DraftCommitBinding.fromStored( + new String(original.gameDesignBinding(), StandardCharsets.UTF_8), + original.inputDigest()); + var revisions = new ArrayList<>(source.revisions()); + for (var revision : graph.revisions()) { + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(revisions.size()), + revision.revisionId(), + revision.owner(), + revision.payload())); + } + var affected = new ArrayList<>(source.affectedUnits()); + affected.addAll(graph.affectedUnits()); + return DraftCommitBinding.create( + source.target(), + graph.requestId(), + graph.commitId(), + graph.baseCommitId(), + revisions, + affected); + } + + public record Prepared( + DraftCommitBinding selected, + AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world) {} + + /** Builds a matching selected publication operation prefix with real closed World codecs. */ + public static Prepared prepare(DraftCommitBinding selected) throws Exception { + var original = + DraftAuthorizationFenceBinding.fromStored(AuthoringFixtures.accountBinding(selected)); + String request = "publication-request"; + long epoch = 5L; + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + selected.target().canonicalTenantId(), + selected.target().canonicalVersionId(), + request, + Long.toString(epoch), + "controlled PLAYER_CREATED source", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-07T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-dddddddddddd"), + new AccountPublicationAuthorizationBinding.PreallocationInput( + original.actorAccountId(), selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + original.actorAccountId().toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + var terminalRequest = + new WorldDraftTerminalReadEvidence.Request( + 1, + "test", + UUID.fromString("33333333-3333-4333-8333-333333333333"), + original.canonicalBytes()); + var applied = AuthoringFixtures.committedFreshGraphReadback(terminalRequest); + var result = JSON.readTree(applied.result()); + var tuples = + selected.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList(); + var world = + new WorldPublishedStartLocationEvidence( + new WorldPublishedStartLocationEvidence.Request( + "test", + selected.target().canonicalTenantId(), + selected.target().canonicalVersionId(), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + request, + selection.digest().substring(7), + epoch, + PublicationDigestRequestBinding.full( + selected.target().canonicalTenantId().toString(), + Long.toString(selected.target().gameDesignVersionRowId()), + request) + .derivedWorkflowIdentity(), + selected.commitId().toString(), + "b".repeat(64), + 3, + tuples), + Base64.getDecoder().decode(result.get("startLocationReceiptBase64").textValue()), + original.canonicalBytes(), + applied.result()); + return new Prepared(selected, account, world); + } + + /** + * Caller supplies the existing explicitly stipulated inventory fixture; no owner is simulated. + */ + public static PublishedRealmEntryPolicySetEvidence seal( + Prepared prepared, + WorldSelectedPublicationArtifactInventoryEvidence inventory, + GameDesignPublicationTerminalEvidence.ReleaseContent release, + AuthoredInitialActorCoreProjection projection) + throws Exception { + var operation = + new GameDesignPublicationOperationBinding(prepared.account(), prepared.world(), inventory); + var terminal = + new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED, + release, + prepared.world().request().versionStateEpoch() + 1L); + var source = projection.policy(); + var policy = RealmEntryPolicy.parseCanonical(source.canonicalJson(), JSON); + UUID policyId = UUID.fromString("33333333-3333-4333-8333-333333333333"); + var selectedPolicy = + new PublishedRealmEntryPolicyEvidence( + policyId, + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy, + PublishedRealmEntryPolicyEvidence.calculateDigest( + policyId, + prepared.selected().target(), + release.versionNumber(), + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy)); + var snapshot = + Map.of( + "schema", + PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA, + "bindingJson", + prepared.selected().canonicalJson(), + "bindingDigest", + prepared.selected().digest(), + "sourceEpoch", + "1", + "policies", + List.of( + Map.of( + "commitId", + source.commitId().toString(), + "revisionId", + source.revisionId().toString(), + "logicalRevisionId", + source.logicalRevisionId(), + "policy", + JSON.readTree(policy.canonicalJson())))); + var capture = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + capture, PublishedRealmEntryPolicySetEvidence.CAPTURE_SCHEMA); + DraftAuthorizationFenceBinding.frame(capture, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + capture, Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(snapshot))); + var policies = List.of(selectedPolicy); + var digest = + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + prepared.selected().target(), + release.versionNumber(), + prepared.selected().commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + policies); + return new PublishedRealmEntryPolicySetEvidence( + prepared.selected().target(), + release.versionNumber(), + prepared.selected().commitId(), + "1", + release.publishedReleaseBundleRef(), + release.contentDigest(), + release.publishWorkflowId(), + release.manifestHash(), + terminal.publicationVersionStateEpoch(), + operation.canonicalBytes(), + capture.toByteArray(), + terminal.canonicalBytes(), + 1, + digest, + policies); + } +} diff --git a/services/entity-management-service/build.gradle.kts b/services/entity-management-service/build.gradle.kts index 548b296313..68a5100a5c 100644 --- a/services/entity-management-service/build.gradle.kts +++ b/services/entity-management-service/build.gradle.kts @@ -14,6 +14,7 @@ dependencies { implementation(project(":common-platform-core")) implementation(project(":common-security")) implementation(libs.spring.boot.starter.cache) + testImplementation(testFixtures(project(":common-platform-core"))) } // 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/EntityCharacterCreateBindings.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindings.java new file mode 100644 index 0000000000..f91c6c712d --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindings.java @@ -0,0 +1,152 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import com.google.protobuf.Message; +import io.grpc.Status; +import java.time.Instant; +import java.util.Arrays; +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.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; +import net.firedevops.firemud.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; + +/** Closed receiving validation; no caller-supplied action or proof becomes owner authority. */ +public final class EntityCharacterCreateBindings { + public static final int MAX_REQUEST_BYTES = 16 * 1024; + public static final int MAX_ACCOUNT_ORIGINAL_RESPONSE_BYTES = 36 * 1024 * 1024; + public static final int MAX_SOURCE_READBACK_BYTES = 32 * 1024 * 1024; + public static final int MAX_ACCOUNT_RESPONSE_BYTES = 40 * 1024 * 1024; + public static final int MAX_GAME_SESSION_RESPONSE_BYTES = 48 * 1024 * 1024; + public static final int MAX_WORLD_RESPONSE_BYTES = 48 * 1024 * 1024; + public static final int MAX_TERMINAL_BYTES = 192 * 1024 * 1024; + + private EntityCharacterCreateBindings() {} + + public static void requireOriginalRequest(ReadOriginalCharacterCreateRequest request) { + exact(request); + if (!GrpcPeerIdentity.isValidNamespace(request.getTargetNamespace()) + || !request.getMutationDigest().matches("[0-9a-f]{64}")) throw invalid(); + id(request.getOperationId()); + } + + public static void requireRequest(CommitProtectedCharacterCreateRequest request) { + exact(request); + if (!request.hasOriginal() + || !request.hasAccountProtection() + || !request.hasGameSessionProtection() + || !request.hasWorldProtection() + || request.getSerializedSize() > MAX_REQUEST_BYTES) throw invalid(); + requireOriginalRequest(request.getOriginal()); + requireReference(request.getAccountProtection()); + requireReference(request.getGameSessionProtection()); + requireReference(request.getWorldProtection()); + } + + public static void requireReference(CharacterCreateProtectionReference reference) { + exact(reference); + id(reference.getProtectionId()); + if (reference.getProtectionFence() <= 0L) throw invalid(); + } + + public static CharacterCreateOperatorAction requireOriginal( + ReadOriginalCharacterCreateRequest request, ReadOriginalCharacterCreateResponse original) { + requireOriginalRequest(request); + requireBound(original, MAX_ACCOUNT_ORIGINAL_RESPONSE_BYTES); + id(original.getCreateCharacterRequestId()); + requireConnectScope(original.getConnectScopeId()); + id(original.getAuthenticatedAccountId()); + if (!request.getTargetNamespace().equals(original.getTargetNamespace()) + || !request.getOperationId().equals(original.getOperationId()) + || !request.getMutationDigest().equals(original.getMutationDigest()) + || !"CHARACTER_CREATE".equals(original.getPurpose()) + || original.getOriginalAction().isEmpty() + || original.getOriginalAction().size() > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + || original.getOriginalSourceReadback().isEmpty() + || original.getOriginalSourceReadback().size() > MAX_SOURCE_READBACK_BYTES) throw invalid(); + byte[] bytes = original.getOriginalAction().toByteArray(); + CharacterCreateOperatorAction action = CharacterCreateOperatorActionCodec.decode(bytes); + if (!Arrays.equals(bytes, CharacterCreateOperatorActionCodec.encode(action)) + || !request + .getMutationDigest() + .equals(CharacterCreateOperatorActionCodec.mutationDigest(action)) + || !original.getAuthenticatedAccountId().equals(action.target().accountId()) + || !original.getTargetNamespace().equals(action.scope().targetNamespace()) + || !action.mutation().catalog().publicProduction() + || !action.mutation().catalog().visible()) throw invalid(); + return action; + } + + public static void requireAccountProtection( + CommitProtectedCharacterCreateRequest request, + ReadOriginalCharacterCreateResponse original, + ReadOriginalCharacterCreateProtectionResponse protection) { + requireBound(protection, MAX_ACCOUNT_RESPONSE_BYTES); + if (!protection.hasOriginal() + || !original.equals(protection.getOriginal()) + || !request + .getAccountProtection() + .getProtectionId() + .equals(protection.getAccountProtectionId()) + || request.getAccountProtection().getProtectionFence() + != protection.getAccountProtectionFence() + || protection.getOriginalMembershipSnapshot().isEmpty() + || protection.getOriginalEntitlementSnapshot().isEmpty()) throw invalid(); + instant(protection.getAcquiredAt()); + } + + private static void requireConnectScope(String value) { + if (value == null + || value.isBlank() + || value.length() > 2048 + || value.indexOf(0) >= 0 + || !java.nio.charset.StandardCharsets.UTF_8.newEncoder().canEncode(value)) throw invalid(); + } + + public static UUID id(String value) { + if (value == null) throw invalid(); + try { + UUID id = UUID.fromString(value); + if (!id.toString().equals(value) || id.equals(new UUID(0L, 0L))) throw invalid(); + return id; + } catch (IllegalArgumentException malformed) { + throw invalid(); + } + } + + public static Instant instant(String value) { + try { + Instant instant = Instant.parse(value); + if (!instant.toString().equals(value)) throw invalid(); + return instant; + } catch (java.time.DateTimeException malformed) { + throw invalid(); + } + } + + public static void exact(Message message) { + if (message == null + || !message.getUnknownFields().asMap().isEmpty() + || message.getSerializedSize() > MAX_TERMINAL_BYTES) throw invalid(); + } + + public static void requireBound(Message message, int maximumBytes) { + exact(message); + if (message.getSerializedSize() > maximumBytes) throw invalid(); + } + + public static RuntimeException invalid() { + return Status.INVALID_ARGUMENT + .withDescription("Exact CHARACTER_CREATE binding required") + .asRuntimeException(); + } + + public static RuntimeException conflict() { + return Status.ALREADY_EXISTS + .withDescription("CHARACTER_CREATE immutable intent conflict") + .asRuntimeException(); + } +} 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 new file mode 100644 index 0000000000..addac1fbc2 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java @@ -0,0 +1,389 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.util.Arrays; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +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.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PlayerCreationDescriptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; +import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.entitymanagement.validation.CanonicalEntitySourceValues; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse; + +/** + * Unregistered Entity read of the complete published PLAYER_CREATED source. The authenticated + * result binds an actual read from the configured Game Session owner only; it grants no Account, + * roster assignment, protection, activation or admission authority. + */ +public final class EntityPlayerCreatedRosterSourceClient + extends AbstractReloadingBlockingGrpcClient< + CharacterCreatePublicSourceServiceGrpc.CharacterCreatePublicSourceServiceBlockingStub> { + public static final int MAX_SOURCE_WIRE_BYTES = 32 * 1024 * 1024; + private final String namespace; + + public EntityPlayerCreatedRosterSourceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Entity PLAYER_CREATED roster source"), + channels, + EntityPlayerCreatedRosterSourceClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw invalid(); + this.namespace = namespace; + } + + public void init() throws IOException { + initOnce("Creation public source client is closed", "Creation public source is unavailable"); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected CharacterCreatePublicSourceServiceGrpc.CharacterCreatePublicSourceServiceBlockingStub + buildStub(io.grpc.ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"; + return CharacterCreatePublicSourceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withMaxInboundMessageSize(MAX_SOURCE_WIRE_BYTES); + } + + public AuthenticatedSource read(ReadPlayerCreatedRosterSourceRequest request) { + requireNoAmbientSql("Public creation source read requires no ambient Entity transaction"); + requireRequest(request); + var response = + requireInitializedStub("Creation public source is unavailable") + .withDeadlineAfter(5L, TimeUnit.SECONDS) + .readPlayerCreatedRosterSource(request); + if (response == null + || !response.getUnknownFields().asMap().isEmpty() + || response.getSchemaVersion() != 1 + || response.getSerializedSize() > MAX_SOURCE_WIRE_BYTES + || !request.equals(response.getRequest()) + || !response.hasCatalog() + || !response.hasPointer() + || !response.hasAuthoredSource() + || response.getWorldLifecycleEvidence().isEmpty() + || response.getPublishedPolicySetEvidence().isEmpty()) throw invalid(); + var catalog = response.getCatalog(); + var pointer = response.getPointer(); + if (!catalog.getUnknownFields().asMap().isEmpty() + || !pointer.getUnknownFields().asMap().isEmpty() + || !catalog.getVisible() + || !catalog.getPublicProduction() + || !"PLAYER_CREATED".equals(catalog.getCharacterCreationPolicy()) + || !"SHARED".equals(catalog.getStateScope()) + || !request.getCanonicalTenantId().equals(catalog.getTenantId()) + || !request.getRealmId().equals(catalog.getRealmId()) + || !request.getWorldSlug().equals(catalog.getWorldSlug()) + || !request.getRealmSlug().equals(catalog.getRealmSlug()) + || !request.getPlayableStateNamespaceId().equals(catalog.getPlayableStateNamespaceId()) + || request.getCatalogRevision() != catalog.getCatalogRevision() + || !request.getCanonicalTenantId().equals(pointer.getTenantId()) + || !request.getRealmId().equals(pointer.getRealmId()) + || !request.getWorldSlug().equals(pointer.getWorldSlug()) + || !request.getRealmSlug().equals(pointer.getRealmSlug()) + || !request.getCanonicalGameInstanceId().equals(pointer.getAdmissibleGameInstanceId()) + || !"OPEN".equals(pointer.getAdmissionState()) + || request.getCatalogRevision() != pointer.getCatalogRevision() + || request.getPointerVersion() != pointer.getPointerVersion() + || !request.getExpectedCanonicalVersionId().equals(response.getCanonicalVersionId()) + || response.getActiveLifecycleEpoch() != request.getActiveWorldEpoch() + || response.getOriginalOwnerFence() <= 0) throw invalid(); + EntityCharacterCreateBindings.id(response.getCanonicalVersionId()); + opaque(response.getOriginalControlPlaneRequestId()); + EntityCharacterCreateBindings.id(response.getOriginalOwnerAttemptId()); + EntityCharacterCreateBindings.id(catalog.getCreationRequestId()); + if (!RealmEntryPolicy.isCanonicalSlug(catalog.getTenantSlug()) + || !catalog.getReceiptDigest().matches("sha256:[0-9a-f]{64}") + || !pointer.getInitialAdmissionOwnerProofDigest().matches("sha256:[0-9a-f]{64}") + || !pointer.getAdmissionPointerSnapshotDigest().matches("[0-9a-f]{64}")) throw invalid(); + opaque(pointer.getInitialAdmissionRequestId()); + EntityCharacterCreateBindings.instant(pointer.getUpdatedAt()); + var authored = + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + response.getAuthoredSource().getRequest()), + response.getAuthoredSource()); + var world = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + response.getWorldLifecycleEvidence().toByteArray()); + var association = authored.associationRead().association(); + var lifecycleRequest = world.request(); + if (!namespace.equals(authored.request().targetNamespace()) + || !response + .getOriginalOwnerAttemptId() + .equals(authored.request().ownerAttemptId().toString()) + || response.getOriginalOwnerFence() != authored.request().ownerFence() + || !response + .getOriginalControlPlaneRequestId() + .equals(authored.request().decodedTuple().controlPlaneRequestId()) + || !authored.descriptor().equals(world.launchBinding().descriptor()) + || !association + .publishWorkflowId() + .equals(world.launchBinding().releaseAttestation().publishWorkflowId()) + || !association + .selectedCommitId() + .toString() + .equals(world.launchBinding().releaseAttestation().commitId()) + || !request.getCanonicalTenantId().equals(association.canonicalTenantId().toString()) + || !request.getWorldSlug().equals(association.worldSlug()) + || !response.getCanonicalVersionId().equals(association.canonicalVersionId().toString()) + || !namespace.equals(lifecycleRequest.targetNamespace()) + || !request.getCanonicalTenantId().equals(lifecycleRequest.canonicalTenantId().toString()) + || !request.getWorldSlug().equals(lifecycleRequest.worldSlug()) + || !request + .getCanonicalGameInstanceId() + .equals(lifecycleRequest.canonicalGameInstanceId().toString()) + || !request + .getPlayableStateNamespaceId() + .equals(lifecycleRequest.playableStateNamespaceId().toString()) + || !response + .getCanonicalVersionId() + .equals(lifecycleRequest.canonicalVersionId().toString()) + || !response + .getOriginalControlPlaneRequestId() + .equals(lifecycleRequest.controlPlaneRequestId()) + || !"SHARED".equals(lifecycleRequest.playableStateScope()) + || !lifecycleRequest.publicProduction() + || !"ACTIVE".equals(world.lifecycleStatus()) + || response.getActiveLifecycleEpoch() != world.lifecycleEpoch()) throw invalid(); + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + var selected = + authored.projections().stream() + .filter( + projection -> + RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), json) + .realmSlug() + .equals(request.getRealmSlug())) + .toList(); + if (selected.size() != 1) throw invalid(); + var policy = + RealmEntryPolicy.parseCanonical(selected.getFirst().policy().canonicalJson(), json); + if (policy.schemaVersion() != RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + || policy.creationDescriptor() == null + || policy.initialActorCore() == null + || !policy + .creationDescriptor() + .canonicalJson() + .equals(selected.getFirst().descriptor().canonicalJson()) + || !policy + .initialActorCore() + .canonicalJson() + .equals(selected.getFirst().core().canonicalJson()) + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !policy.worldSlug().equals(catalog.getWorldSlug()) + || !policy.worldDisplayName().equals(catalog.getWorldDisplayName()) + || !policy.realmDisplayName().equals(catalog.getRealmDisplayName())) throw invalid(); + var projection = selected.getFirst(); + var set = + PublishedRealmEntryPolicySetEvidence.fromStored( + response.getPublishedPolicySetEvidence().toByteArray()) + .requireValidDigest(); + var operation = GameDesignPublicationOperationBinding.fromStored(set.operationBytes()); + var release = world.launchBinding().releaseAttestation(); + var bundle = authored.associationRead().releaseBundle(); + var expectedRelease = + StartSessionTemplateAssociationReadEvidence.releaseContent( + bundle, authored.associationRead().worldPublishedStartLocationEvidence()); + var terminal = GameDesignPublicationTerminalEvidence.fromStored(set.terminalEvidenceBytes()); + if (!namespace.equals(operation.world().request().targetNamespace()) + || !association.canonicalTenantId().equals(set.target().canonicalTenantId()) + || !association.canonicalVersionId().equals(set.target().canonicalVersionId()) + || !association.selectedCommitId().equals(set.sourceCommitId()) + || !projection + .selectedCommitDigest() + .equals(operation.account().input().selection().selectedCommit().digest()) + || !association.publishWorkflowId().equals(set.publishWorkflowId()) + || !release.publishWorkflowId().equals(set.publishWorkflowId()) + || !release.commitId().equals(set.sourceCommitId().toString()) + || !release.publishedReleaseBundleRef().equals(set.publishedReleaseBundleRef()) + || !bundle.getPublishedReleaseBundleRef().equals(set.publishedReleaseBundleRef()) + || !release.manifestHash().equals(set.manifestHash()) + || expectedRelease.manifestSchemaVersion() != release.manifestSchemaVersion() + || !expectedRelease.artifactDigests().equals(release.artifactDigests()) + || !expectedRelease.requiredManifestAssetKeys().equals(release.requiredManifestAssetKeys()) + || !expectedRelease.commandDefinitions().equals(release.commandDefinitions()) + || !expectedRelease.generationConfigRevision().equals(release.generationConfigRevision()) + || !expectedRelease.participantDigests().stream() + .map( + value -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId() != null, + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + value.digestSchemaVersion(), + value.abilitySchemaDigest() != null, + value.abilitySchemaDigest())) + .toList() + .equals(release.participantDigests()) + || !expectedRelease.contentDigest().equals(set.publishedReleaseBundleDigest()) + || !Arrays.equals( + expectedRelease.canonicalBytes(), terminal.releaseContent().canonicalBytes()) + || !Arrays.equals( + release.worldStartLocationEvidence().canonicalBytes(), + operation.world().canonicalBytes())) throw invalid(); + var policies = + set.policies().stream() + .filter( + candidate -> + candidate.policy().worldSlug().equals(request.getWorldSlug()) + && candidate.policy().realmSlug().equals(request.getRealmSlug())) + .toList(); + if (policies.size() != 1) throw invalid(); + var sealed = policies.getFirst().requireValidDigest(set); + if (!sealed.policy().canonicalJson().equals(policy.canonicalJson()) + || !sealed.sourceCommitId().equals(projection.policy().commitId()) + || !sealed.sourceRevisionId().equals(projection.policy().revisionId()) + || !sealed.logicalRevisionId().equals(projection.policy().logicalRevisionId())) + throw invalid(); + var target = + new CanonicalGameplayRosterTarget( + UUID.fromString(catalog.getTenantId()), + UUID.fromString(catalog.getRealmId()), + catalog.getWorldSlug(), + catalog.getRealmSlug(), + UUID.fromString(pointer.getAdmissibleGameInstanceId()), + catalog.getCatalogRevision(), + pointer.getPointerVersion(), + world.lifecycleEpoch(), + UUID.fromString(response.getCanonicalVersionId()), + CanonicalEntitySourceValues.normalizeSha256ToRawHex(sealed.policyDigest()), + set.publishedReleaseBundleRef(), + pointer.getAdmissionPointerSnapshotDigest(), + CanonicalEntitySourceValues.normalizeSha256ToRawHex( + pointer.getInitialAdmissionOwnerProofDigest()), + UUID.fromString(catalog.getPlayableStateNamespaceId()), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED); + return new AuthenticatedSource( + response, + authored, + world, + PlayerCreationDescriptor.parse(projection.descriptor().canonicalJson()), + set, + target); + } + + private void requireRequest(ReadPlayerCreatedRosterSourceRequest request) { + if (request == null + || !request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != 1 + || request.getSerializedSize() > 16 * 1024 + || !namespace.equals(request.getTargetNamespace()) + || !"SHARED".equals(request.getPlayableStateScope()) + || !RealmEntryPolicy.isCanonicalSlug(request.getWorldSlug()) + || !RealmEntryPolicy.isCanonicalSlug(request.getRealmSlug()) + || request.getCatalogRevision() <= 0 + || request.getPointerVersion() <= 0 + || request.getActiveWorldEpoch() <= 0) throw invalid(); + for (String id : + java.util.List.of( + request.getReadRequestId(), + request.getCanonicalTenantId(), + request.getRealmId(), + request.getPlayableStateNamespaceId(), + request.getCanonicalGameInstanceId(), + request.getExpectedCanonicalVersionId())) EntityCharacterCreateBindings.id(id); + } + + private static void opaque(String value) { + if (value == null + || value.isBlank() + || value.length() > 128 + || value.indexOf(0) >= 0 + || !java.nio.charset.StandardCharsets.UTF_8.newEncoder().canEncode(value)) throw invalid(); + } + + private static RuntimeException invalid() { + return EntityCharacterCreateBindings.invalid(); + } + + /** Constructor custody establishes this transport read, never the other owners' authority. */ + public static final class AuthenticatedSource { + private final ReadPlayerCreatedRosterSourceResponse response; + private final AuthoredInitialActorCoreReadEvidence.ReadResult authored; + private final WorldCanonicalInstanceLifecycleEvidence world; + private final PlayerCreationDescriptor creationDescriptor; + private final PublishedRealmEntryPolicySetEvidence publishedPolicySet; + private final CanonicalGameplayRosterTarget target; + + private AuthenticatedSource( + ReadPlayerCreatedRosterSourceResponse response, + AuthoredInitialActorCoreReadEvidence.ReadResult authored, + WorldCanonicalInstanceLifecycleEvidence world, + PlayerCreationDescriptor creationDescriptor, + PublishedRealmEntryPolicySetEvidence publishedPolicySet, + CanonicalGameplayRosterTarget target) { + this.response = response; + this.authored = authored; + this.world = world; + this.creationDescriptor = creationDescriptor; + this.publishedPolicySet = publishedPolicySet; + this.target = target; + } + + @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Protobuf messages are immutable.") + public ReadPlayerCreatedRosterSourceResponse response() { + return response; + } + + public AuthoredInitialActorCoreReadEvidence.ReadResult authored() { + return authored; + } + + public PublishedRealmEntryPolicySetEvidence publishedPolicySet() { + return publishedPolicySet; + } + + public CanonicalGameplayRosterTarget target() { + return target; + } + + public PlayerCreationDescriptor creationDescriptor() { + return creationDescriptor; + } + + public WorldCanonicalInstanceLifecycleEvidence world() { + return world; + } + } +} 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 new file mode 100644 index 0000000000..d46f84d686 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java @@ -0,0 +1,1171 @@ +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 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; +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.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.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.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; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Production client init/channel and closed owner-codec proof over controlled loopback PKI. Valid + * owner-shaped results are stipulated fixtures with a matching closed authored projection. This + * proves Entity transport and complete byte/target binding with the real peer interceptor. The + * test-local owner stub does not execute the production Game Session adapter or prove genuine + * publication, bootstrap issuance, issued scope, membership, protection, allocation or admission. + */ +@Timeout(120) +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; + + @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(); + } + + @Test + void actualInitializedClientPreservesExactRequestAndCompleteTypedOwnerSources() throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + var result = client.read(fixture.request()); + assertThat(owner.received).containsExactly(fixture.request()); + assertThat(owner.observedPeer.get()) + .isEqualTo("spiffe://firemud/ns/test/sa/entity-management-service"); + assertThat(result.publishedPolicySet().canonicalBytes()) + .containsExactly(fixture.policySet().canonicalBytes()); + assertThat(result.target()) + .isEqualTo( + new CanonicalGameplayRosterTarget( + fixture.world().request().canonicalTenantId(), + FIXTURE_ID, + "synthetic-world", + "realm", + fixture.world().request().canonicalGameInstanceId(), + 3L, + 5L, + 7L, + fixture.world().request().canonicalVersionId(), + fixture.policySet().policies().getFirst().policyDigest().substring(7), + fixture.policySet().publishedReleaseBundleRef(), + "c".repeat(64), + "b".repeat(64), + fixture.world().request().playableStateNamespaceId(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED)); + assertThat(result.creationDescriptor().canonicalJson()) + .isEqualTo(fixture.authored().projections().getFirst().descriptor().canonicalJson()); + assertThat(result.response().toByteArray()).containsExactly(fixture.response().toByteArray()); + assertThat(result.authored().canonicalBytes()) + .containsExactly(fixture.authored().canonicalBytes()); + assertThat(result.authored().projections()).hasSize(1); + assertThat(result.world().canonicalBytes()).containsExactly(fixture.world().canonicalBytes()); + assertThat(result.response().getOriginalControlPlaneRequestId()) + .isEqualTo("world-lifecycle-control-request"); + assertThat(result.response().getPointer().getUpdatedAt()) + .isEqualTo("2026-10-24T00:00:00.123456789Z"); + } + } + + @Test + void constructionRequiresFileBackedMtlsAndCanonicalNamespace() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var channels = new GrpcChannelFactory(); + assertThatThrownBy( + () -> + new EntityPlayerCreatedRosterSourceClient( + endpoints, new CommonGrpcClientProperties(), channels, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + var plaintext = pki.clientProperties(directory, pki.identity("entity")); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new EntityPlayerCreatedRosterSourceClient( + endpoints, plaintext, channels, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new EntityPlayerCreatedRosterSourceClient( + endpoints, + pki.clientProperties(directory, pki.identity("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)) { + client.init(); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(owner.received).isEmpty(); + } + } + } + + @Test + void absentInitializationAndAmbientSqlRefuseBeforeAnyReceivedRpc() throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(IllegalStateException.class); + client.init(); + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(owner.received).isEmpty(); + } + } + + @Test + void malformedAndChangedRequestSelectorsRefuseBeforeAnyReceivedRpc() throws Exception { + var request = fixture.request(); + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + for (var changed : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setPlayableStateScope("ISOLATED").build(), + request.toBuilder().setCanonicalGameInstanceId("invalid").build(), + request.toBuilder().setWorldSlug("x".repeat(16 * 1024)).build(), + request.toBuilder().setUnknownFields(unknown()).build(), + request.toBuilder().setExpectedCanonicalVersionId("42").build(), + request.toBuilder().setActiveWorldEpoch(0).build(), + request.toBuilder().setRealmSlug("Realm").build(), + 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); + } + assertThat(owner.received).isEmpty(); + } + } + + @Test + void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws Exception { + var good = fixture.response(); + var world = fixture.world(); + var inactive = + new WorldCanonicalInstanceLifecycleEvidence( + world.request(), + world.launchBinding(), + world.startLocation(), + world.runtimeRoomInstanceId(), + "TERMINATING", + world.lifecycleEpoch(), + world.rowVersion(), + world.captureId(), + world.graphSha256(), + world.preparationInputDigest(), + world.operationalRegionAssignments()); + var otherLaunch = fixture("other-authored-launch-descriptor").world(); + var authored = fixture.authored(); + var noProjections = + AuthoredInitialActorCoreReadGrpcCodec.toResponse( + new AuthoredInitialActorCoreReadEvidence.ReadResult( + authored.request(), authored.associationRead(), authored.descriptor(), List.of())); + var privateProjection = + AuthoredInitialActorCoreReadGrpcCodec.toResponse( + new AuthoredInitialActorCoreReadEvidence.ReadResult( + authored.request(), + authored.associationRead(), + authored.descriptor(), + List.of( + AuthoredInitialActorCoreProjection.fromValidatedBinding( + FIXTURE_ID, + sourceBinding( + authored.associationRead().association(), + authored.associationRead().association().sourceOperationId(), + false))))); + var extraProjection = + AuthoredInitialActorCoreProjection.fromValidatedBinding( + UUID.randomUUID(), + sourceBinding( + authored.associationRead().association(), + authored.associationRead().association().sourceOperationId())); + var ambiguousProjections = + AuthoredInitialActorCoreReadGrpcCodec.toResponse( + new AuthoredInitialActorCoreReadEvidence.ReadResult( + authored.request(), + authored.associationRead(), + authored.descriptor(), + List.of(authored.projections().getFirst(), extraProjection))); + var operation = + GameDesignPublicationOperationBinding.fromStored(fixture.policySet().operationBytes()); + var originalRelease = + GameDesignPublicationTerminalEvidence.fromStored( + fixture.policySet().terminalEvidenceBytes()) + .releaseContent(); + var changedRelease = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + originalRelease.canonicalTenantId(), + originalRelease.canonicalVersionId(), + "other-release", + originalRelease.versionNumber(), + originalRelease.attestationSchemaVersion(), + originalRelease.publishWorkflowId(), + originalRelease.manifestHash(), + originalRelease.manifestSchemaVersion(), + originalRelease.artifactDigests(), + originalRelease.requiredManifestAssetKeys(), + originalRelease.participantDigests(), + originalRelease.commandDefinitions(), + originalRelease.generationConfigRevision(), + originalRelease.worldStartLocationEvidence()); + var otherReleaseSet = + PlayerCreatedPublishedPolicyFixtures.seal( + new PlayerCreatedPublishedPolicyFixtures.Prepared( + operation.account().input().selection().selectedCommit(), + operation.account(), + operation.world()), + operation.inventory(), + changedRelease, + authored.projections().getFirst()); + var mismatchedSources = + new java.util.ArrayList< + net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse>(); + for (String field : List.of("commitId", "revisionId", "logicalRevisionId")) { + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + var originalProjection = authored.projections().getFirst(); + var node = + (tools.jackson.databind.node.ObjectNode) + json.readTree(originalProjection.canonicalBytes()); + ((tools.jackson.databind.node.ObjectNode) node.get("policy")) + .put( + field, + field.equals("logicalRevisionId") + ? "another-source-revision" + : UUID.randomUUID().toString()); + byte[] bytes = Rfc8785CanonicalJson.canonicalizeUtf8(json.writeValueAsString(node)); + var changedProjection = + AuthoredInitialActorCoreProjection.fromStored(bytes, CommandSource.sha256(bytes)); + mismatchedSources.add( + AuthoredInitialActorCoreReadGrpcCodec.toResponse( + new AuthoredInitialActorCoreReadEvidence.ReadResult( + authored.request(), + authored.associationRead(), + authored.descriptor(), + List.of(changedProjection)))); + } + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + for (var changed : + List.of( + good.toBuilder() + .setRequest(good.getRequest().toBuilder().setPointerVersion(99)) + .build(), + good.toBuilder() + .setCatalog( + good.getCatalog().toBuilder().setRealmId(UUID.randomUUID().toString())) + .build(), + good.toBuilder() + .setPointer( + good.getPointer().toBuilder() + .setAdmissibleGameInstanceId(UUID.randomUUID().toString())) + .build(), + good.toBuilder().setCatalog(good.getCatalog().toBuilder().setVisible(false)).build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setPublicProduction(false)) + .build(), + good.toBuilder() + .setCatalog( + good.getCatalog().toBuilder().setCharacterCreationPolicy("PRESEEDED_ONLY")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setReceiptDigest("bad")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setCreationRequestId("42")) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setUpdatedAt("bad")) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().clearInitialAdmissionRequestId()) + .build(), + good.toBuilder() + .setPointer( + good.getPointer().toBuilder().setInitialAdmissionOwnerProofDigest("bad")) + .build(), + good.toBuilder() + .setPointer( + good.getPointer().toBuilder().setAdmissionPointerSnapshotDigest("bad")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setWorldDisplayName("Different world")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setRealmDisplayName("Different realm")) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setAdmissionState("CLOSED")) + .build(), + good.toBuilder() + .setCatalog(good.getCatalog().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder() + .setPointer(good.getPointer().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder().setCanonicalVersionId(UUID.randomUUID().toString()).build(), + good.toBuilder().setOriginalControlPlaneRequestId("different-original").build(), + good.toBuilder().setOriginalOwnerAttemptId(UUID.randomUUID().toString()).build(), + good.toBuilder().setOriginalOwnerFence(good.getOriginalOwnerFence() + 1).build(), + good.toBuilder().setActiveLifecycleEpoch(good.getActiveLifecycleEpoch() + 1).build(), + good.toBuilder().setAuthoredSource(noProjections).build(), + good.toBuilder().setAuthoredSource(privateProjection).build(), + good.toBuilder().setAuthoredSource(ambiguousProjections).build(), + good.toBuilder() + .setAuthoredSource( + good.getAuthoredSource().toBuilder() + .setCanonicalResultBytes(ByteString.copyFromUtf8("{}"))) + .build(), + good.toBuilder() + .setAuthoredSource( + good.getAuthoredSource().toBuilder().setResultDigest(digest('0'))) + .build(), + good.toBuilder() + .setAuthoredSource( + good.getAuthoredSource().toBuilder().setUnknownFields(unknown())) + .build(), + good.toBuilder().setWorldLifecycleEvidence(ByteString.copyFromUtf8("{}")).build(), + good.toBuilder() + .setWorldLifecycleEvidence(ByteString.copyFrom(inactive.canonicalBytes())) + .build(), + good.toBuilder() + .setWorldLifecycleEvidence(ByteString.copyFrom(otherLaunch.canonicalBytes())) + .build(), + good.toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFrom(otherReleaseSet.canonicalBytes())) + .build(), + good.toBuilder().setAuthoredSource(mismatchedSources.get(0)).build(), + good.toBuilder().setAuthoredSource(mismatchedSources.get(1)).build(), + good.toBuilder().setAuthoredSource(mismatchedSources.get(2)).build(), + good.toBuilder().clearPublishedPolicySetEvidence().build(), + good.toBuilder().setPublishedPolicySetEvidence(ByteString.copyFromUtf8("{}")).build(), + good.toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFromUtf8( + fixture + .policySet() + .canonicalJson() + .replace( + fixture.policySet().publishedReleaseBundleRef(), + "other-release"))) + .build(), + good.toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFromUtf8( + fixture + .policySet() + .canonicalJson() + .replace( + fixture.policySet().sourceCommitId().toString(), + UUID.randomUUID().toString()))) + .build(), + good.toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFromUtf8( + fixture.policySet().canonicalJson().replace("Wayfarer", "Other actor"))) + .build(), + good.toBuilder().clearAuthoredSource().build(), + good.toBuilder().clearWorldLifecycleEvidence().build(), + good.toBuilder().clearCatalog().build(), + good.toBuilder().clearPointer().build(), + good.toBuilder().setOriginalControlPlaneRequestId("x".repeat(129)).build(), + good.toBuilder().setUnknownFields(unknown()).build())) { + owner.response.set(changed); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(RuntimeException.class); + } + assertThat(owner.received).isNotEmpty().allMatch(fixture.request()::equals); + owner.response.set(good); + assertThat(client.read(fixture.request()).response()).isEqualTo(good); + } + } + + @Test + void inboundTransportRejectsResponseBeyond32MiBBeforeSourceDecoding() throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + owner.response.set( + fixture.response().toBuilder() + .setWorldLifecycleEvidence( + ByteString.copyFrom( + new byte[EntityPlayerCreatedRosterSourceClient.MAX_SOURCE_WIRE_BYTES])) + .build()); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.RESOURCE_EXHAUSTED)); + assertThat(owner.received).containsExactly(fixture.request()); + } + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .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 = + 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/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreateBinding.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreateBinding.java new file mode 100644 index 0000000000..d1f0ddbfc8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreateBinding.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.gamesession.charactercreate; + +import io.grpc.Status; +import java.time.Instant; +import java.util.Arrays; +import java.util.UUID; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionRequest; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateProtectionResponse; +import net.firedevops.firemud.account.v1.ReadOriginalCharacterCreateResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorAction; +import net.firedevops.firemud.common.operator.CharacterCreateOperatorActionCodec; + +/** + * Passive exact-purpose binding checks; only the separate authenticated owner client reads Account. + */ +public final class GameSessionCharacterCreateBinding { + // These larger bounds are local to this closed creation family, not shared gRPC defaults. + public static final int MAX_ACCOUNT_ORIGINAL_BYTES = 36 * 1024 * 1024; + public static final int MAX_ACCOUNT_PROTECTION_BYTES = 40 * 1024 * 1024; + public static final int MAX_SOURCE_READBACK_BYTES = 32 * 1024 * 1024; + public static final int MAX_WIRE_BYTES = 48 * 1024 * 1024; + + private GameSessionCharacterCreateBinding() {} + + public static void requireSelector( + ReadOriginalCharacterCreateProtectionRequest selector, String namespace) { + if (selector == null + || !selector.hasOriginal() + || !selector.getUnknownFields().asMap().isEmpty() + || !selector.getOriginal().getUnknownFields().asMap().isEmpty() + || !GrpcPeerIdentity.isValidNamespace(namespace) + || !namespace.equals(selector.getOriginal().getTargetNamespace()) + || !selector.getOriginal().getMutationDigest().matches("[0-9a-f]{64}") + || selector.getAccountProtectionFence() <= 0) throw invalid(); + id(selector.getOriginal().getOperationId()); + id(selector.getAccountProtectionId()); + } + + public static CharacterCreateOperatorAction requireAccountProtection( + ReadOriginalCharacterCreateProtectionRequest selector, + ReadOriginalCharacterCreateResponse original, + ReadOriginalCharacterCreateProtectionResponse protection, + String namespace) { + requireSelector(selector, namespace); + if (original == null + || protection == null + || !protection.hasOriginal() + || original.getSerializedSize() > MAX_ACCOUNT_ORIGINAL_BYTES + || protection.getSerializedSize() > MAX_ACCOUNT_PROTECTION_BYTES + || !original.getUnknownFields().asMap().isEmpty() + || !protection.getUnknownFields().asMap().isEmpty() + || !Arrays.equals(original.toByteArray(), protection.getOriginal().toByteArray()) + || !namespace.equals(original.getTargetNamespace()) + || !selector.getOriginal().getOperationId().equals(original.getOperationId()) + || !selector.getOriginal().getMutationDigest().equals(original.getMutationDigest()) + || !selector.getAccountProtectionId().equals(protection.getAccountProtectionId()) + || selector.getAccountProtectionFence() != protection.getAccountProtectionFence() + || !"CHARACTER_CREATE".equals(original.getPurpose()) + || original.getOriginalAction().isEmpty() + || original.getOriginalAction().size() > CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + || original.getOriginalSourceReadback().isEmpty() + || original.getOriginalSourceReadback().size() > MAX_SOURCE_READBACK_BYTES + || protection.getOriginalMembershipSnapshot().size() > 1024 * 1024 + || protection.getOriginalEntitlementSnapshot().size() > 1024 * 1024 + || protection.getOriginalMembershipSnapshot().isEmpty() + || protection.getOriginalEntitlementSnapshot().isEmpty()) throw invalid(); + id(original.getOperationId()); + id(original.getCreateCharacterRequestId()); + requireConnectScope(original.getConnectScopeId()); + id(original.getAuthenticatedAccountId()); + instant(protection.getAcquiredAt()); + var bytes = original.getOriginalAction().toByteArray(); + var action = CharacterCreateOperatorActionCodec.decode(bytes); + if (!Arrays.equals(bytes, CharacterCreateOperatorActionCodec.encode(action)) + || !namespace.equals(action.scope().targetNamespace()) + || !original.getAuthenticatedAccountId().equals(action.target().accountId()) + || !original + .getMutationDigest() + .equals(CharacterCreateOperatorActionCodec.mutationDigest(action)) + || !action.mutation().catalog().visible() + || !action.mutation().catalog().publicProduction()) throw invalid(); + return action; + } + + private static void requireConnectScope(String value) { + if (value == null + || value.isBlank() + || value.length() > 2048 + || value.indexOf(0) >= 0 + || !java.nio.charset.StandardCharsets.UTF_8.newEncoder().canEncode(value)) throw invalid(); + } + + public static UUID id(String value) { + if (value == null) throw invalid(); + try { + var id = UUID.fromString(value); + if (id.equals(new UUID(0L, 0L)) || !id.toString().equals(value)) throw invalid(); + return id; + } catch (IllegalArgumentException malformed) { + throw invalid(); + } + } + + public static Instant instant(String value) { + try { + var instant = Instant.parse(value); + if (!instant.toString().equals(value)) throw invalid(); + return instant; + } catch (IllegalArgumentException | java.time.format.DateTimeParseException malformed) { + throw invalid(); + } + } + + static RuntimeException invalid() { + return Status.INVALID_ARGUMENT + .withDescription("Exact original CHARACTER_CREATE binding required") + .asRuntimeException(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java new file mode 100644 index 0000000000..075253682f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.gamesession.charactercreate; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; + +/** + * Unregistered purpose-specific certificate boundary. Closed request bounds are checked before + * owner work; full owner proofs are bounded response messages. + */ +public final class GameSessionCharacterCreatePublicSourceGrpcService + extends CharacterCreatePublicSourceServiceGrpc.CharacterCreatePublicSourceServiceImplBase { + private final GameSessionCharacterCreatePublicSourceService source; + private final String namespace; + + public GameSessionCharacterCreatePublicSourceGrpcService( + GameSessionCharacterCreatePublicSourceService source, String namespace) { + this.source = Objects.requireNonNull(source); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Fixed GS namespace required"); + this.namespace = namespace; + } + + @Override + public void resolveCharacterCreatePublicTarget( + ResolveCharacterCreatePublicTargetRequest request, + StreamObserver observer) { + try { + requirePeer("account-service"); + GameSessionCharacterCreatePublicSourceService.outsideSql(); + GameSessionCharacterCreatePublicSourceService.requireResolveRequest(request, namespace); + var result = source.resolve(request); + if (result.getSerializedSize() + > GameSessionCharacterCreatePublicSourceService.MAX_TARGET_RESPONSE_BYTES + || !result.getRequest().equals(request) + || result.getSchemaVersion() != 1) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact bounded public target response required") + .asRuntimeException(); + } + observer.onNext(result); + observer.onCompleted(); + } catch (StatusRuntimeException status) { + observer.onError(status); + } catch (IllegalArgumentException invalid) { + observer.onError(GameSessionCharacterCreatePublicSourceService.invalid()); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException storage) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Public target owner storage unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact public creation target unavailable") + .asRuntimeException()); + } + } + + @Override + public void readCharacterCreatePublicSource( + ReadCharacterCreatePublicSourceRequest request, + StreamObserver observer) { + try { + requirePeer("account-service"); + GameSessionCharacterCreatePublicSourceService.outsideSql(); + GameSessionCharacterCreatePublicSourceService.requireRequest(request, namespace); + var result = source.read(request); + if (result.getSerializedSize() + > GameSessionCharacterCreatePublicSourceService.MAX_RESPONSE_BYTES + || !result.getRequest().equals(request) + || result.getSchemaVersion() != 1) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact bounded source response required") + .asRuntimeException(); + } + observer.onNext(result); + observer.onCompleted(); + } catch (StatusRuntimeException status) { + observer.onError(status); + } catch (IllegalArgumentException invalid) { + observer.onError(GameSessionCharacterCreatePublicSourceService.invalid()); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException storage) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Creation source owner storage unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact creation source unavailable") + .asRuntimeException()); + } + } + + @Override + public void readPlayerCreatedRosterSource( + ReadPlayerCreatedRosterSourceRequest request, + StreamObserver observer) { + try { + requirePeer("entity-management-service"); + GameSessionCharacterCreatePublicSourceService.outsideSql(); + GameSessionCharacterCreatePublicSourceService.requireRosterRequest(request, namespace); + var result = source.readPlayerCreatedRosterSource(request); + if (result.getSerializedSize() + > GameSessionCharacterCreatePublicSourceService.MAX_RESPONSE_BYTES + || !result.getUnknownFields().asMap().isEmpty() + || !result.getRequest().equals(request) + || result.getSchemaVersion() != 1) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact bounded roster source response required") + .asRuntimeException(); + } + observer.onNext(result); + observer.onCompleted(); + } catch (StatusRuntimeException status) { + observer.onError(status); + } catch (IllegalArgumentException invalid) { + observer.onError(GameSessionCharacterCreatePublicSourceService.invalid()); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException storage) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Roster source owner storage unavailable") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Exact PLAYER_CREATED roster source unavailable") + .asRuntimeException()); + } + } + + private void requirePeer(String service) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) + throw Status.UNAUTHENTICATED + .withDescription("Verified workload mTLS identity required") + .asRuntimeException(); + if (!peer.isService(service) + || !peer.isInNamespace(namespace) + || !peer.uri().equals("spiffe://firemud/ns/" + namespace + "/sa/" + service) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + throw Status.PERMISSION_DENIED + .withDescription( + "account-service".equals(service) + ? "Exact same-namespace Account workload required" + : "Exact same-namespace Entity Management workload required") + .asRuntimeException(); + } + } +} 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 new file mode 100644 index 0000000000..ff02b13548 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java @@ -0,0 +1,703 @@ +package net.firedevops.firemud.gamesession.charactercreate; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import io.grpc.Status; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; +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.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository.CurrentOpenSource; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicCatalog; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicPointer; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered source composition for Account creation intent and Entity PLAYER_CREATED roster + * input. Reads existing original evidence; never captures a source, renews a launch claim, creates + * an action or acquires a protection. + */ +public final class GameSessionCharacterCreatePublicSourceService { + public static final int MAX_REQUEST_BYTES = 16 * 1024; + public static final int MAX_RESPONSE_BYTES = 32 * 1024 * 1024; + public static final int MAX_TARGET_RESPONSE_BYTES = 64 * 1024; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final String namespace; + private final CanonicalPlayerRouteReadService routes; + private final GameSessionCanonicalRealmCatalogRepository catalogs; + private final CanonicalInitialAdmissionRepository admissions; + private final CanonicalGameInstanceLaunchAssociationRepository launches; + private final GameSessionAuthoredActorCoreRetentionRepository retainedSources; + private final AuthoredInitialActorCoreReadClient gameDesign; + private final WorldCanonicalInstanceLifecycleClient world; + private final GameDesignPublishedRealmPolicyClient publishedPolicies; + + public GameSessionCharacterCreatePublicSourceService( + String namespace, + CanonicalPlayerRouteReadService routes, + GameSessionCanonicalRealmCatalogRepository catalogs, + CanonicalInitialAdmissionRepository admissions, + CanonicalGameInstanceLaunchAssociationRepository launches, + GameSessionAuthoredActorCoreRetentionRepository retainedSources, + AuthoredInitialActorCoreReadClient gameDesign, + WorldCanonicalInstanceLifecycleClient world, + GameDesignPublishedRealmPolicyClient publishedPolicies) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw invalid(); + this.namespace = namespace; + this.routes = Objects.requireNonNull(routes); + this.catalogs = Objects.requireNonNull(catalogs); + this.admissions = Objects.requireNonNull(admissions); + this.launches = Objects.requireNonNull(launches); + this.retainedSources = Objects.requireNonNull(retainedSources); + this.gameDesign = Objects.requireNonNull(gameDesign); + this.world = Objects.requireNonNull(world); + this.publishedPolicies = Objects.requireNonNull(publishedPolicies); + } + + /** Resolves friendly selectors before Account has issued any canonical scope. */ + public ResolveCharacterCreatePublicTargetResponse resolve( + ResolveCharacterCreatePublicTargetRequest request) { + outsideSql(); + requireResolveRequest(request, namespace); + var visible = routes.readVisiblePublicProductionTargets(); + if (visible == null || visible.stream().anyMatch(Objects::isNull)) throw missing(); + var selected = + visible.stream() + .filter( + route -> + request.getWorldSlug().equals(route.worldSlug()) + && request.getRealmSlug().equals(route.realmSlug())) + .toList(); + if (selected.size() != 1) throw missing(); + CanonicalPlayableTarget discovery = selected.getFirst(); + requirePublicCreatedTarget(discovery); + CanonicalPlayableTarget before = routes.readCurrentTarget(discovery.canonicalTenantId()); + if (!discovery.equals(before)) throw missing(); + requirePublicCreatedTarget(before); + CanonicalRealmCatalogSnapshot catalog = catalog(before); + CurrentOpenSource pointer = pointer(before); + CanonicalPlayableTarget after = routes.readCurrentTarget(before.canonicalTenantId()); + if (!before.equals(after) || !catalog.equals(catalog(after)) || !pointer.equals(pointer(after))) + throw missing(); + var response = + ResolveCharacterCreatePublicTargetResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setCatalog(catalogMessage(catalog)) + .setPointer(pointerMessage(pointer)) + .setCanonicalGameInstanceId(before.canonicalGameInstanceId().toString()) + .setCanonicalVersionId(before.canonicalVersionId().toString()) + .setActiveLifecycleEpoch(before.activeWorldEpoch()) + .build(); + if (response.getSerializedSize() > MAX_TARGET_RESPONSE_BYTES) throw missing(); + return response; + } + + private void requirePublicCreatedTarget(CanonicalPlayableTarget route) { + if (route == null + || !namespace.equals(route.targetNamespace()) + || !"SHARED".equals(route.playableStateScope()) + || !"PLAYER_CREATED".equals(route.characterCreationPolicy())) throw missing(); + } + + static void requireResolveRequest( + ResolveCharacterCreatePublicTargetRequest request, String namespace) { + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != 1 + || !namespace.equals(request.getTargetNamespace()) + || !RealmEntryPolicy.isCanonicalSlug(request.getWorldSlug()) + || !RealmEntryPolicy.isCanonicalSlug(request.getRealmSlug())) throw invalid(); + GameSessionCharacterCreateBinding.id(request.getReadRequestId()); + } + + public ReadCharacterCreatePublicSourceResponse read( + ReadCharacterCreatePublicSourceRequest request) { + outsideSql(); + requireRequest(request, namespace); + var facts = + readSource( + UUID.fromString(request.getReadRequestId()), + UUID.fromString(request.getCanonicalTenantId()), + route -> requireTarget(request, route), + false); + var response = + ReadCharacterCreatePublicSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setCatalog(catalogMessage(facts.catalog())) + .setPointer(pointerMessage(facts.pointer())) + .setCanonicalVersionId(facts.route().canonicalVersionId().toString()) + .setActiveLifecycleEpoch(facts.lifecycle().lifecycleEpoch()) + .setOriginalControlPlaneRequestId(facts.launch().controlPlaneRequestId()) + .setOriginalOwnerAttemptId(facts.retained().ownerAttemptId().toString()) + .setOriginalOwnerFence(facts.retained().ownerFence()) + .setAuthoredSource(AuthoredInitialActorCoreReadGrpcCodec.toResponse(facts.authored())) + .setWorldLifecycleEvidence(ByteString.copyFrom(facts.lifecycle().canonicalBytes())) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) throw missing(); + return response; + } + + /** Exact current published PLAYER_CREATED input for Entity roster policy resolution only. */ + public ReadPlayerCreatedRosterSourceResponse readPlayerCreatedRosterSource( + ReadPlayerCreatedRosterSourceRequest request) { + outsideSql(); + requireRosterRequest(request, namespace); + var facts = + readSource( + UUID.fromString(request.getReadRequestId()), + UUID.fromString(request.getCanonicalTenantId()), + route -> requireRosterTarget(request, route), + true); + var response = + ReadPlayerCreatedRosterSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setCatalog(catalogMessage(facts.catalog())) + .setPointer(pointerMessage(facts.pointer())) + .setCanonicalVersionId(facts.route().canonicalVersionId().toString()) + .setActiveLifecycleEpoch(facts.lifecycle().lifecycleEpoch()) + .setOriginalControlPlaneRequestId(facts.launch().controlPlaneRequestId()) + .setOriginalOwnerAttemptId(facts.retained().ownerAttemptId().toString()) + .setOriginalOwnerFence(facts.retained().ownerFence()) + .setAuthoredSource(AuthoredInitialActorCoreReadGrpcCodec.toResponse(facts.authored())) + .setWorldLifecycleEvidence(ByteString.copyFrom(facts.lifecycle().canonicalBytes())) + .setPublishedPolicySetEvidence(ByteString.copyFrom(facts.policySet().canonicalBytes())) + .build(); + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) throw missing(); + return response; + } + + private SourceFacts readSource( + UUID readRequestId, + UUID tenant, + Consumer requireSelectedTarget, + boolean includePublishedPolicies) { + CanonicalPlayableTarget before = routes.readCurrentTarget(tenant); + requireSelectedTarget.accept(before); + CanonicalRealmCatalogSnapshot catalog = catalog(before); + CurrentOpenSource pointer = pointer(before); + CanonicalGameInstanceLaunchAssociation launch = launch(before); + Candidate retained = retained(launch); + var sourceRequest = sourceRequest(retained); + var historicalRequest = + new HistoricalOriginalStartSessionOwnerEvidence.Request( + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + readRequestId, + namespace, + tenant, + before.worldSlug(), + before.canonicalGameInstanceId(), + launch.controlPlaneRequestId(), + launch.launchDescriptorId(), + launch.launchBindingEvidence().descriptor().requestDigest(), + launch.launchBindingEvidence().descriptor().resultDigest(), + launch.launchBindingEvidence().releaseAttestation().evidenceDigest()), + retained.ownerAttemptId(), + retained.ownerFence()); + var historical = + launches + .readHistoricalOriginalStartSessionOwnerEvidence(historicalRequest) + .orElseThrow(GameSessionCharacterCreatePublicSourceService::missing); + requireOriginal(retained, launch, historical, sourceRequest); + + outsideSql(); + var authored = gameDesign.read(sourceRequest); + if (!Arrays.equals(authored.canonicalBytes(), retained.canonicalSourceResultBytes()) + || !authored.digest().equals(retained.sourceResultDigest()) + || !sourceRequest.associationRequest().equals(authored.request()) + || !launch.launchBindingEvidence().descriptor().equals(authored.descriptor())) + throw missing(); + requireProjection(before, catalog, retained, authored); + var descriptor = launch.launchBindingEvidence().descriptor(); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + 1, + readRequestId, + namespace, + tenant, + before.worldSlug(), + before.canonicalGameInstanceId(), + before.playableStateNamespaceId(), + "SHARED", + true, + launch.controlPlaneRequestId(), + before.canonicalVersionId(), + descriptor.requestDigest(), + descriptor.resultDigest(), + launch.launchBindingEvidence().releaseAttestation().evidenceDigest()); + outsideSql(); + var lifecycle = world.read(lifecycleRequest); + if (!lifecycleRequest.equals(lifecycle.request()) + || !"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() + || !launch.launchBindingEvidence().equals(lifecycle.launchBinding())) throw missing(); + + var policySet = + includePublishedPolicies ? readPublishedPolicies(before, authored, lifecycle) : null; + + // Re-read every complete local source after all remote calls; never select a newer target. + CanonicalPlayableTarget after = routes.readCurrentTarget(tenant); + requireSelectedTarget.accept(after); + if (!before.equals(after) + || !catalog.equals(catalog(after)) + || !pointer.equals(pointer(after)) + || !launch.equals(launch(after))) throw missing(); + Candidate confirmed = retained(launch); + var confirmedHistorical = + launches + .readHistoricalOriginalStartSessionOwnerEvidence(historicalRequest) + .orElseThrow(GameSessionCharacterCreatePublicSourceService::missing); + requireOriginal(confirmed, launch, confirmedHistorical, sourceRequest); + 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); + } + + private record SourceFacts( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + CurrentOpenSource pointer, + CanonicalGameInstanceLaunchAssociation launch, + Candidate retained, + AuthoredInitialActorCoreReadEvidence.ReadResult authored, + WorldCanonicalInstanceLifecycleEvidence lifecycle, + PublishedRealmEntryPolicySetEvidence policySet) {} + + private PublishedRealmEntryPolicySetEvidence readPublishedPolicies( + CanonicalPlayableTarget route, + AuthoredInitialActorCoreReadEvidence.ReadResult authored, + WorldCanonicalInstanceLifecycleEvidence lifecycle) { + outsideSql(); + var set = + publishedPolicies.listPublishedRealmEntryPolicies( + route.canonicalTenantId(), route.canonicalVersionId()); + if (set == null) throw missing(); + set.requireValidDigest(); + var operation = GameDesignPublicationOperationBinding.fromStored(set.operationBytes()); + var terminal = GameDesignPublicationTerminalEvidence.fromStored(set.terminalEvidenceBytes()); + var association = authored.associationRead().association(); + var bundle = authored.associationRead().releaseBundle(); + var worldRelease = lifecycle.launchBinding().releaseAttestation(); + var sourceRelease = + net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence + .releaseContent(bundle, worldRelease.worldStartLocationEvidence()); + if (!namespace.equals(operation.world().request().targetNamespace()) + || !route.canonicalTenantId().equals(set.target().canonicalTenantId()) + || !route.canonicalVersionId().equals(set.target().canonicalVersionId()) + || !set.sourceCommitId().equals(association.selectedCommitId()) + || !set.publishWorkflowId().equals(association.publishWorkflowId()) + || !set.publishWorkflowId().equals(worldRelease.publishWorkflowId()) + || !set.sourceCommitId().toString().equals(worldRelease.commitId()) + || !set.publishedReleaseBundleRef().equals(bundle.getPublishedReleaseBundleRef()) + || !set.publishedReleaseBundleRef().equals(worldRelease.publishedReleaseBundleRef()) + || !set.publishedReleaseBundleDigest().equals(sourceRelease.contentDigest()) + || !set.publishedReleaseBundleDigest().equals(terminal.publishedReleaseBundleDigest()) + || !Arrays.equals( + sourceRelease.canonicalBytes(), terminal.releaseContent().canonicalBytes()) + || !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( + evidence -> + evidence.policy().worldSlug().equals(route.worldSlug()) + && evidence.policy().realmSlug().equals(route.realmSlug())) + .toList(); + if (matches.size() != 1) throw missing(); + var evidence = matches.getFirst().requireValidDigest(set); + var policy = evidence.policy(); + if (policy.schemaVersion() != RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION + || policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !policy.canonicalJson().equals(projection.policy().canonicalJson()) + || !evidence.sourceCommitId().equals(projection.policy().commitId()) + || !evidence.sourceRevisionId().equals(projection.policy().revisionId()) + || !evidence.logicalRevisionId().equals(projection.policy().logicalRevisionId()) + || !operation + .account() + .input() + .selection() + .selectedCommit() + .digest() + .equals(projection.selectedCommitDigest())) throw missing(); + return set; + } + + static void requireRosterRequest(ReadPlayerCreatedRosterSourceRequest request, String namespace) { + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != 1 + || !namespace.equals(request.getTargetNamespace()) + || !RealmEntryPolicy.isCanonicalSlug(request.getWorldSlug()) + || !RealmEntryPolicy.isCanonicalSlug(request.getRealmSlug()) + || !"SHARED".equals(request.getPlayableStateScope()) + || request.getCatalogRevision() <= 0 + || request.getPointerVersion() <= 0 + || request.getActiveWorldEpoch() <= 0) throw invalid(); + for (String id : + new String[] { + request.getReadRequestId(), + request.getCanonicalTenantId(), + request.getRealmId(), + request.getPlayableStateNamespaceId(), + request.getCanonicalGameInstanceId(), + request.getExpectedCanonicalVersionId() + }) GameSessionCharacterCreateBinding.id(id); + } + + private static void requireRosterTarget( + ReadPlayerCreatedRosterSourceRequest request, CanonicalPlayableTarget route) { + if (route == null + || !request.getTargetNamespace().equals(route.targetNamespace()) + || !request.getCanonicalTenantId().equals(route.canonicalTenantId().toString()) + || !request.getRealmId().equals(route.realmId().toString()) + || !request.getWorldSlug().equals(route.worldSlug()) + || !request.getRealmSlug().equals(route.realmSlug()) + || !request + .getPlayableStateNamespaceId() + .equals(route.playableStateNamespaceId().toString()) + || !request.getPlayableStateScope().equals(route.playableStateScope()) + || !request.getCanonicalGameInstanceId().equals(route.canonicalGameInstanceId().toString()) + || request.getCatalogRevision() != route.catalogRevision() + || request.getPointerVersion() != route.pointerVersion() + || !request.getExpectedCanonicalVersionId().equals(route.canonicalVersionId().toString()) + || request.getActiveWorldEpoch() != route.activeWorldEpoch() + || !"PLAYER_CREATED".equals(route.characterCreationPolicy())) throw missing(); + } + + private CanonicalRealmCatalogSnapshot catalog(CanonicalPlayableTarget route) { + var catalog = + catalogs + .readUniqueVisiblePublicProduction(namespace, route.canonicalTenantId()) + .orElseThrow(GameSessionCharacterCreatePublicSourceService::missing); + if (!catalog.targetNamespace().equals(namespace) + || !catalog.tenantId().equals(route.canonicalTenantId()) + || !catalog.tenantSlug().equals(route.tenantSlug()) + || !catalog.realmId().equals(route.realmId()) + || !catalog.worldSlug().equals(route.worldSlug()) + || !catalog.realmSlug().equals(route.realmSlug()) + || !catalog.realmDisplayName().equals(route.realmDisplayName()) + || !catalog + .sourceIntakeReceipt() + .source() + .worldDisplayName() + .equals(route.worldDisplayName()) + || !catalog.playableStateNamespaceId().equals(route.playableStateNamespaceId()) + || !"SHARED".equals(catalog.stateScope()) + || !catalog.visible() + || !catalog.publicProduction() + || !"PLAYER_CREATED".equals(catalog.characterCreationPolicy()) + || catalog.catalogRevision() != route.catalogRevision()) throw missing(); + return catalog; + } + + private CurrentOpenSource pointer(CanonicalPlayableTarget route) { + var pointer = + admissions.readCurrentOpenSourceForRealm( + namespace, route.canonicalTenantId(), route.realmId()); + if (!pointer.tenantId().equals(route.canonicalTenantId()) + || !pointer.realmId().equals(route.realmId()) + || !pointer.worldSlug().equals(route.worldSlug()) + || !pointer.realmSlug().equals(route.realmSlug()) + || !"OPEN".equals(pointer.admissionState()) + || !pointer.canonicalGameInstanceId().equals(route.canonicalGameInstanceId()) + || pointer.catalogRevision() != route.catalogRevision() + || pointer.pointerVersion() != route.pointerVersion() + || !pointer + .snapshot() + .admissionPointerSnapshotDigest() + .equals(route.admissionPointerSnapshotDigest()) + || !pointer.snapshot().ownerProof().proofDigest().equals(route.ownerProofDigest()) + || pointer.snapshot().ownerProof().activeLifecycleEpoch() != route.activeWorldEpoch() + || pointer.updatedAt() == null) throw missing(); + return pointer; + } + + private CanonicalGameInstanceLaunchAssociation launch(CanonicalPlayableTarget route) { + var launch = + launches + .readForInitialAdmission( + namespace, + route.canonicalTenantId(), + route.realmId(), + route.canonicalGameInstanceId()) + .orElseThrow(GameSessionCharacterCreatePublicSourceService::missing) + .association(); + if (!namespace.equals(launch.targetNamespace()) + || !launch.canonicalTenantId().equals(route.canonicalTenantId()) + || !launch.worldSlug().equals(route.worldSlug()) + || !launch.gameInstanceUuid().equals(route.canonicalGameInstanceId()) + || !launch.playableStateNamespaceId().equals(route.playableStateNamespaceId()) + || !launch.publicProduction() + || launch.playableStateScope() != RealmEntryPolicy.StateScope.SHARED + || launch.currentGameInstanceStatus() + != CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING + || !launch + .launchBindingEvidence() + .releaseAttestation() + .canonicalVersionId() + .equals(route.canonicalVersionId())) throw missing(); + return launch; + } + + private Candidate retained(CanonicalGameInstanceLaunchAssociation launch) { + return retainedSources + .readByOriginalOperation(namespace, launch.controlPlaneRequestId()) + .orElseThrow(GameSessionCharacterCreatePublicSourceService::missing) + .candidate(); + } + + private static AuthoredInitialActorCoreReadEvidence.ReadRequest sourceRequest( + Candidate retained) { + try { + var encoded = + ReadStartSessionTemplateAssociationRequest.parseFrom(retained.sourceReadRequestBytes()); + var decoded = StartSessionTemplateAssociationReadGrpcCodec.fromRequest(encoded); + if (!Arrays.equals( + StartSessionTemplateAssociationReadGrpcCodec.toRequest(decoded).toByteArray(), + retained.sourceReadRequestBytes())) throw missing(); + return new AuthoredInitialActorCoreReadEvidence.ReadRequest(decoded); + } catch (InvalidProtocolBufferException invalid) { + throw missing(); + } + } + + private static void requireOriginal( + Candidate retained, + CanonicalGameInstanceLaunchAssociation launch, + HistoricalOriginalStartSessionOwnerEvidence.Result historical, + AuthoredInitialActorCoreReadEvidence.ReadRequest request) { + var original = historical.launchAssociation(); + var selection = historical.descriptorPin().associationRead(); + if (!retained.targetNamespace().equals(launch.targetNamespace()) + || !retained.canonicalTenantId().equals(launch.canonicalTenantId()) + || !retained.gameInstanceUuid().equals(launch.gameInstanceUuid()) + || !retained.controlPlaneRequestId().equals(launch.controlPlaneRequestId()) + || !retained.worldSlug().equals(launch.worldSlug()) + || !retained.ownerAttemptId().equals(historical.ownerAttemptId()) + || retained.ownerFence() != historical.ownerFence() + || !Arrays.equals( + retained.originalPostAuthorizationTuple(), historical.originalTuple().canonicalBytes()) + || !Arrays.equals( + retained.accountRedemptionProjection(), historical.accountRedemptionProjection()) + || !request.associationRequest().equals(selection.request()) + || !original.targetNamespace().equals(launch.targetNamespace()) + || !original.canonicalTenantId().equals(launch.canonicalTenantId()) + || !original.gameInstanceUuid().equals(launch.gameInstanceUuid()) + || !original.worldSlug().equals(launch.worldSlug()) + || !original.controlPlaneRequestId().equals(launch.controlPlaneRequestId()) + || !original.launchDescriptorId().equals(launch.launchDescriptorId()) + || !original.playableStateNamespaceId().equals(launch.playableStateNamespaceId()) + || !original.publicProduction() + || original.playableStateScope() != RealmEntryPolicy.StateScope.SHARED + || !original.launchBindingEvidence().equals(launch.launchBindingEvidence()) + || !retained.canonicalVersionId().equals(selection.association().canonicalVersionId()) + || !retained.selectedCommitId().equals(selection.association().selectedCommitId()) + || !retained.publishWorkflowId().equals(selection.association().publishWorkflowId()) + || !retained.associationDigest().equals(selection.association().associationDigest()) + || !retained.worldSourceOperationId().equals(selection.association().sourceOperationId()) + || !retained + .worldSourceEvidenceDigest() + .equals(selection.association().sourceEvidenceDigest()) + || !retained.launchDescriptorId().equals(launch.launchDescriptorId()) + || !retained + .descriptorRequestDigest() + .equals(launch.launchBindingEvidence().descriptor().requestDigest()) + || !retained + .descriptorResultDigest() + .equals(launch.launchBindingEvidence().descriptor().resultDigest()) + || !retained + .releaseAttestationEvidenceDigest() + .equals(launch.launchBindingEvidence().releaseAttestation().evidenceDigest())) + throw missing(); + } + + private static void requireProjection( + CanonicalPlayableTarget route, + CanonicalRealmCatalogSnapshot catalog, + Candidate retained, + AuthoredInitialActorCoreReadEvidence.ReadResult source) { + var selected = + source.projections().stream() + .filter( + projection -> + RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), JSON) + .realmSlug() + .equals(route.realmSlug())) + .toList(); + if (selected.size() != 1) throw missing(); + var projection = selected.getFirst(); + var policy = RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), JSON); + if (policy.entryPolicy() != RealmEntryPolicy.EntryPolicy.PLAYER_CREATED + || !policy.visible() + || !policy.publicProduction() + || policy.stateScope() != RealmEntryPolicy.StateScope.SHARED + || !policy.worldSlug().equals(catalog.worldSlug()) + || !policy.realmSlug().equals(catalog.realmSlug()) + || !policy.worldDisplayName().equals(route.worldDisplayName()) + || !policy.realmDisplayName().equals(catalog.realmDisplayName()) + || !projection.canonicalTenantId().equals(route.canonicalTenantId()) + || !projection.canonicalVersionId().equals(route.canonicalVersionId()) + || !projection + .worldSourceOperationId() + .equals(catalog.sourceIntakeReceipt().source().operationId()) + || !projection + .worldSourceEvidenceDigest() + .equals(catalog.sourceIntakeReceipt().source().evidenceDigest()) + || !projection.selectedCommitId().equals(retained.selectedCommitId()) + || !projection.publicationWorkflowId().equals(retained.publishWorkflowId())) + throw missing(); + } + + static void requireRequest(ReadCharacterCreatePublicSourceRequest request, String namespace) { + if (request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.getUnknownFields().asMap().isEmpty() + || request.getSchemaVersion() != 1 + || !namespace.equals(request.getTargetNamespace()) + || !"SHARED".equals(request.getPlayableStateScope()) + || !request.getWorldSlug().matches("[a-z0-9]+(?:-[a-z0-9]+)*") + || !request.getRealmSlug().matches("[a-z0-9]+(?:-[a-z0-9]+)*") + || request.getCatalogRevision() <= 0 + || request.getPointerVersion() <= 0) throw invalid(); + for (String id : + new String[] { + request.getReadRequestId(), + request.getCanonicalTenantId(), + request.getRealmId(), + request.getPlayableStateNamespaceId(), + request.getCanonicalGameInstanceId() + }) { + GameSessionCharacterCreateBinding.id(id); + } + try { + Instant evaluated = Instant.parse(request.getEvaluatedAt()); + Instant expires = Instant.parse(request.getConnectScopeExpiresAt()); + if (!evaluated.toString().equals(request.getEvaluatedAt()) + || !expires.toString().equals(request.getConnectScopeExpiresAt()) + || !expires.isAfter(evaluated)) throw invalid(); + } catch (java.time.format.DateTimeParseException malformed) { + throw invalid(); + } + } + + private static void requireTarget( + ReadCharacterCreatePublicSourceRequest request, CanonicalPlayableTarget route) { + if (!request.getTargetNamespace().equals(route.targetNamespace()) + || !request.getCanonicalTenantId().equals(route.canonicalTenantId().toString()) + || !request.getRealmId().equals(route.realmId().toString()) + || !request.getWorldSlug().equals(route.worldSlug()) + || !request.getRealmSlug().equals(route.realmSlug()) + || !request + .getPlayableStateNamespaceId() + .equals(route.playableStateNamespaceId().toString()) + || !request.getPlayableStateScope().equals(route.playableStateScope()) + || !request.getCanonicalGameInstanceId().equals(route.canonicalGameInstanceId().toString()) + || request.getCatalogRevision() != route.catalogRevision() + || request.getPointerVersion() != route.pointerVersion() + || !"PLAYER_CREATED".equals(route.characterCreationPolicy())) throw missing(); + } + + private static CharacterCreatePublicCatalog catalogMessage( + CanonicalRealmCatalogSnapshot catalog) { + return CharacterCreatePublicCatalog.newBuilder() + .setTenantId(catalog.tenantId().toString()) + .setTenantSlug(catalog.tenantSlug()) + .setWorldSlug(catalog.worldSlug()) + .setWorldDisplayName(catalog.sourceIntakeReceipt().source().worldDisplayName()) + .setRealmId(catalog.realmId().toString()) + .setRealmSlug(catalog.realmSlug()) + .setRealmDisplayName(catalog.realmDisplayName()) + .setVisible(catalog.visible()) + .setPublicProduction(catalog.publicProduction()) + .setStateScope(catalog.stateScope()) + .setPlayableStateNamespaceId(catalog.playableStateNamespaceId().toString()) + .setCharacterCreationPolicy(catalog.characterCreationPolicy()) + .setCatalogRevision(catalog.catalogRevision()) + .setCreationRequestId(catalog.creationRequestId().toString()) + .setReceiptDigest(catalog.receiptDigest()) + .build(); + } + + private static CharacterCreatePublicPointer pointerMessage(CurrentOpenSource pointer) { + return CharacterCreatePublicPointer.newBuilder() + .setTenantId(pointer.tenantId().toString()) + .setRealmId(pointer.realmId().toString()) + .setWorldSlug(pointer.worldSlug()) + .setRealmSlug(pointer.realmSlug()) + .setAdmissionState(pointer.admissionState()) + .setAdmissibleGameInstanceId(pointer.canonicalGameInstanceId().toString()) + .setPointerVersion(pointer.pointerVersion()) + .setCatalogRevision(pointer.catalogRevision()) + .setUpdatedAt(pointer.updatedAt().toString()) + .setInitialAdmissionRequestId(pointer.snapshot().ownerProof().initialAdmissionRequestId()) + .setInitialAdmissionOwnerProofDigest(pointer.snapshot().ownerProof().proofDigest()) + .setAdmissionPointerSnapshotDigest(pointer.snapshot().admissionPointerSnapshotDigest()) + .build(); + } + + static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) + throw new IllegalStateException("Creation source reads must not join an ambient transaction"); + } + + static RuntimeException invalid() { + return Status.INVALID_ARGUMENT + .withDescription("Exact bounded public CHARACTER_CREATE selectors required") + .asRuntimeException(); + } + + private static RuntimeException missing() { + return Status.FAILED_PRECONDITION + .withDescription("Exact original public CHARACTER_CREATE source is unavailable or changed") + .asRuntimeException(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java index 3faa05af4f..8d9d191f1b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClient.java @@ -10,6 +10,7 @@ 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.publication.PublishedRealmEntryPolicyReadGrpcCodec; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; @@ -20,6 +21,7 @@ public final class GameDesignPublishedRealmPolicyClient extends AbstractReloadingBlockingGrpcClient< PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub> { private static final long CALL_DEADLINE_SECONDS = 5L; + private static final int MAX_RESPONSE_BYTES = 32 * 1024 * 1024; private static final UUID NIL_UUID = new UUID(0L, 0L); private final String workloadNamespace; @@ -59,10 +61,14 @@ protected String defaultTarget() { protected PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceBlockingStub buildStub(ManagedChannel channel) { return PublishedRealmEntryPolicyServiceGrpc.newBlockingStub(channel) + .withCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) .withInterceptors( new GrpcServerPeerIdentityClientInterceptor( "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service")) - .withCompression("gzip"); + .withCompression("gzip") + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES); } /** Reads and verifies the complete bounded owner set for an exact published tenant version. */ @@ -85,6 +91,9 @@ public PublishedRealmEntryPolicySetEvidence listPublishedRealmEntryPolicies( .listPublishedRealmEntryPolicies( PublishedRealmEntryPolicyReadGrpcCodec.toRequest(request)); try { + if (response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Complete published policy response exceeds its bound"); + } return PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(request, response); } catch (IllegalArgumentException invalid) { throw new InvalidResponseException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index d679ca0be7..4a3109614c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -178,6 +178,55 @@ public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( return new CurrentOpenSnapshot(proof, snapshotDigestOrReconciliation(before, proof)); } + /** + * Complete current public pointer content, independently qualified by its committed owner proof. + */ + public record CurrentOpenSource( + CurrentOpenSnapshot snapshot, + UUID tenantId, + UUID realmId, + String worldSlug, + String realmSlug, + String admissionState, + UUID canonicalGameInstanceId, + long pointerVersion, + long catalogRevision, + Instant updatedAt) {} + + /** Reads exact pointer content without deriving timestamps from a terminal proof. */ + @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true) + public CurrentOpenSource readCurrentOpenSourceForRealm( + String targetNamespace, UUID canonicalTenantUuid, UUID realmUuid) { + requireOutsideTransaction(); + requireCurrentOpenReadSelector(targetNamespace, canonicalTenantUuid, realmUuid); + CurrentOpenPointer before = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + CurrentOpenSnapshot qualified = + readCurrentOpenSnapshotForRealm(targetNamespace, canonicalTenantUuid, realmUuid); + CurrentOpenPointer pointer = + readCurrentOpenPointer(targetNamespace, canonicalTenantUuid, realmUuid); + pointer.requireCanonicalOpen(targetNamespace, canonicalTenantUuid, realmUuid); + if (!before.equals(pointer) + || !pointer.matches(qualified.ownerProof()) + || !qualified + .admissionPointerSnapshotDigest() + .equals(snapshotDigestOrReconciliation(pointer, qualified.ownerProof()))) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current OPEN pointer changed during complete source read"); + } + return new CurrentOpenSource( + qualified, + pointer.value("canonical_tenant_id", UUID.class), + pointer.value("realm_id", UUID.class), + pointer.value("world_slug", String.class), + pointer.value("realm_slug", String.class), + pointer.value("admission_state", String.class), + pointer.value("canonical_game_instance_id", UUID.class), + pointer.value("pointer_version", Long.class), + pointer.value("catalog_revision", Long.class), + pointer.updatedAt()); + } + /** * Revalidates an already committed outside-transaction snapshot under exact owner row locks. This * grants no new admission authority and never calls a remote owner from SQL. @@ -914,6 +963,18 @@ private String snapshotDigest(CanonicalInitialAdmissionOwnerProof proof) { proof.terminalAt())); } + private Instant updatedAt() { + Object value = fields.get("updated_at"); + // This owner column is TIMESTAMP WITHOUT TIME ZONE. Plain JDBC SQL returns Timestamp; + // generated jOOQ projections may expose LocalDateTime. Both retain the same UTC wall time. + if (value instanceof java.sql.Timestamp timestamp) + return toInstant(timestamp.toLocalDateTime()); + if (value instanceof java.time.LocalDateTime timestamp) return toInstant(timestamp); + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Current realm pointer updated_at is not an owning SQL timestamp: " + + (value == null ? "null" : value.getClass().getName())); + } + private T value(String key, Class type) { Object value = fields.get(key); if (value == null) { 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 7cd837586f..b6cd0c2194 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 @@ -120,6 +120,24 @@ void rosterRetirementUsesRealCommittedAdmissionReaderAndLocksCurrentPointerUnder fixture.initialAdmissionRepository, fixture.launchRepository); var current = routes.readCurrentTarget(TENANT); + var sourcePointer = + fixture.initialAdmissionRepository.readCurrentOpenSourceForRealm( + NAMESPACE, TENANT, current.realmId()); + assertThat(sourcePointer.updatedAt()) + .isEqualTo( + fixture + .dsl + .fetchSingle( + "SELECT updated_at FROM gameplay_admission_pointer WHERE target_namespace=? AND canonical_tenant_id=? AND realm_id=?", + NAMESPACE, + TENANT, + current.realmId()) + .get(0, java.time.LocalDateTime.class) + .toInstant(java.time.ZoneOffset.UTC)); + assertThat(sourcePointer.canonicalGameInstanceId()) + .isEqualTo(current.canonicalGameInstanceId()); + assertThat(sourcePointer.snapshot().admissionPointerSnapshotDigest()) + .isEqualTo(current.admissionPointerSnapshotDigest()); var target = net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterTarget.newBuilder() .setTenantUuid(TENANT.toString()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java new file mode 100644 index 0000000000..901f889ffa --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java @@ -0,0 +1,329 @@ +package net.firedevops.firemud.gamesession.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetRequest; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; +import org.junit.jupiter.api.Test; + +class GameSessionCharacterCreatePublicSourceGrpcServiceTest { + @Test + void rosterSourceRequiresExactEntityPeerAndRejectsCallerContextBeforeSourceAccess() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + var request = GameSessionCharacterCreatePublicSourceServiceTest.rosterRequest(); + assertThat(roster(adapter, null, "firemud", request).code) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(roster(adapter, "account-service", "firemud", request).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(roster(adapter, "entity-management-service", "other", request).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + try { + assertThat(roster(adapter, "entity-management-service", "firemud", request).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + SessionContext.setContext(null, List.of(), Map.of(), true, "entity-management-service", "test"); + try { + assertThat(roster(adapter, "entity-management-service", "firemud", request).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + verifyNoInteractions(source); + } + + @Test + void rosterSourceRejectsMalformedClosedRequestAndAmbientSqlBeforeSourceAccess() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + var request = GameSessionCharacterCreatePublicSourceServiceTest.rosterRequest(); + for (var invalid : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setReadRequestId("not-uuid").build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setPlayableStateScope("ISOLATED").build(), + request.toBuilder().setExpectedCanonicalVersionId("42").build(), + request.toBuilder().setActiveWorldEpoch(0).build(), + request.toBuilder().setCatalogRevision(0).build(), + request.toBuilder().setPointerVersion(0).build(), + request.toBuilder().setWorldSlug("W").build(), + request.toBuilder().setRealmSlug("").build(), + request.toBuilder().setWorldSlug("w".repeat(17000)).build(), + request.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 88, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) { + assertThat(roster(adapter, "entity-management-service", "firemud", invalid).code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + org.springframework.transaction.support.TransactionSynchronizationManager.initSynchronization(); + try { + assertThat(roster(adapter, "entity-management-service", "firemud", request).code) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .clearSynchronization(); + } + verifyNoInteractions(source); + } + + @Test + void rosterSourcePreservesExactResponseOwnerErrorAndRefusesChangedEcho() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + var request = GameSessionCharacterCreatePublicSourceServiceTest.rosterRequest(); + var response = + ReadPlayerCreatedRosterSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .setPublishedPolicySetEvidence( + com.google.protobuf.ByteString.copyFromUtf8("controlled-original-sealed-set")) + .build(); + when(source.readPlayerCreatedRosterSource(request)) + .thenReturn(response) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()) + .thenReturn( + response.toBuilder().setRequest(request.toBuilder().setActiveWorldEpoch(8)).build()); + assertThat(roster(adapter, "entity-management-service", "firemud", request).value) + .isEqualTo(response); + assertThat(roster(adapter, "entity-management-service", "firemud", request).code) + .isEqualTo(Status.Code.UNAVAILABLE); + assertThat(roster(adapter, "entity-management-service", "firemud", request).code) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + private static RosterCollector roster( + GameSessionCharacterCreatePublicSourceGrpcService service, + String peer, + String namespace, + ReadPlayerCreatedRosterSourceRequest request) { + var collector = new RosterCollector(); + var context = + peer == null + ? Context.current() + : Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + peer, namespace, peer)); + context.run(() -> service.readPlayerCreatedRosterSource(request, collector)); + return collector; + } + + private static final class RosterCollector + implements StreamObserver { + ReadPlayerCreatedRosterSourceResponse value; + Status.Code code = Status.Code.OK; + + @Override + public void onNext(ReadPlayerCreatedRosterSourceResponse value) { + this.value = value; + } + + @Override + public void onError(Throwable failure) { + code = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } + + @Test + void preScopeResolutionRequiresExactAccountPeerAndCanonicalFriendlySelectors() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + var request = GameSessionCharacterCreatePublicSourceServiceTest.resolveRequest(); + assertThat(resolve(adapter, null, "firemud", request).code) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(resolve(adapter, "entity-management-service", "firemud", request).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(resolve(adapter, "account-service", "other", request).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + try { + assertThat(resolve(adapter, "account-service", "firemud", request).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + for (var invalid : + List.of( + request.toBuilder().setSchemaVersion(2).build(), + request.toBuilder().setReadRequestId("not-uuid").build(), + request.toBuilder().setTargetNamespace("other").build(), + request.toBuilder().setWorldSlug("World").build(), + request.toBuilder().setRealmSlug("").build(), + request.toBuilder().setWorldSlug("w".repeat(17000)).build())) { + assertThat(resolve(adapter, "account-service", "firemud", invalid).code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(source); + var response = + ResolveCharacterCreatePublicTargetResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .build(); + when(source.resolve(request)).thenReturn(response); + assertThat(resolve(adapter, "account-service", "firemud", request).value).isEqualTo(response); + } + + @Test + void rejectsMissingWrongAndForeignPeersBeforeSourceAccess() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + assertThat(call(adapter, null, "firemud", request()).code) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(call(adapter, "entity-management-service", "firemud", request()).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(call(adapter, "account-service", "other", request()).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(source); + } + + @Test + void rejectsBearerCallerContextAndMalformedFieldsBeforeSourceAccess() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + SessionContext.setContext(UUID.randomUUID().toString(), List.of(), Map.of()); + try { + assertThat(call(adapter, "account-service", "firemud", request()).code) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + SessionContext.clear(); + } + for (var invalid : + List.of( + request().toBuilder().setSchemaVersion(2).build(), + request().toBuilder().setReadRequestId("not-uuid").build(), + request().toBuilder().setTargetNamespace("other").build(), + request().toBuilder().setPlayableStateScope("ISOLATED").build(), + request().toBuilder().setEvaluatedAt("2026-10-24T00:00:00.000Z").build(), + request().toBuilder().setConnectScopeExpiresAt(request().getEvaluatedAt()).build(), + request().toBuilder().setWorldSlug("x".repeat(17000)).build())) { + assertThat(call(adapter, "account-service", "firemud", invalid).code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(source); + } + + @Test + void echoesExactSelectorsAndPreservesOwnerUnavailableWithoutSubstitution() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + var expected = + ReadCharacterCreatePublicSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request()) + .build(); + when(source.read(request())) + .thenReturn(expected) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + assertThat(call(adapter, "account-service", "firemud", request()).value).isEqualTo(expected); + assertThat(call(adapter, "account-service", "firemud", request()).code) + .isEqualTo(Status.Code.UNAVAILABLE); + } + + private static ReadCharacterCreatePublicSourceRequest request() { + return GameSessionCharacterCreatePublicSourceServiceTest.request(); + } + + private static Collector call( + GameSessionCharacterCreatePublicSourceGrpcService service, + String peer, + String namespace, + ReadCharacterCreatePublicSourceRequest request) { + var collector = new Collector(); + var context = + peer == null + ? Context.current() + : Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + peer, namespace, peer)); + context.run(() -> service.readCharacterCreatePublicSource(request, collector)); + return collector; + } + + private static final class Collector + implements StreamObserver { + ReadCharacterCreatePublicSourceResponse value; + Status.Code code = Status.Code.OK; + + @Override + public void onNext(ReadCharacterCreatePublicSourceResponse value) { + this.value = value; + } + + @Override + public void onError(Throwable failure) { + code = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } + + private static ResolveCollector resolve( + GameSessionCharacterCreatePublicSourceGrpcService service, + String peer, + String namespace, + ResolveCharacterCreatePublicTargetRequest request) { + var collector = new ResolveCollector(); + var context = + peer == null + ? Context.current() + : Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + peer, namespace, peer)); + context.run(() -> service.resolveCharacterCreatePublicTarget(request, collector)); + return collector; + } + + private static final class ResolveCollector + implements StreamObserver { + ResolveCharacterCreatePublicTargetResponse value; + Status.Code code = Status.Code.OK; + + @Override + public void onNext(ResolveCharacterCreatePublicTargetResponse value) { + this.value = value; + } + + @Override + public void onError(Throwable failure) { + code = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() {} + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceMtlsTest.java new file mode 100644 index 0000000000..d50a81c94c --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceMtlsTest.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.gamesession.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.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +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.stub.MetadataUtils; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.gamesession.v1.CharacterCreatePublicSourceServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetResponse; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Socket/certificate adapter proof only; the source composition is a controlled double. */ +class GameSessionCharacterCreatePublicSourceMtlsTest { + @TempDir Path temporary; + + @Test + void onlyExactAccountCertificateCanReadAndBearerCannotReplacePeerIdentity() throws Exception { + var pki = + LoopbackMtlsTestPki.create( + temporary, + "Creation public source proof CA", + new LoopbackMtlsTestPki.IdentitySpec( + "server", "spiffe://firemud/ns/firemud/sa/game-session-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/firemud/sa/account-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "entity", "spiffe://firemud/ns/firemud/sa/entity-management-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign", "spiffe://firemud/ns/other/sa/account-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "foreign-entity", "spiffe://firemud/ns/other/sa/entity-management-service", false)); + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var request = GameSessionCharacterCreatePublicSourceServiceTest.request(); + var result = + ReadCharacterCreatePublicSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(request) + .build(); + when(source.read(request)).thenReturn(result); + var targetRequest = GameSessionCharacterCreatePublicSourceServiceTest.resolveRequest(); + var targetResult = + ResolveCharacterCreatePublicTargetResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(targetRequest) + .build(); + when(source.resolve(targetRequest)).thenReturn(targetResult); + var rosterRequest = GameSessionCharacterCreatePublicSourceServiceTest.rosterRequest(); + var rosterResult = + ReadPlayerCreatedRosterSourceResponse.newBuilder() + .setSchemaVersion(1) + .setRequest(rosterRequest) + .setPublishedPolicySetEvidence( + com.google.protobuf.ByteString.copyFromUtf8("controlled-original-sealed-set")) + .build(); + when(source.readPlayerCreatedRosterSource(rosterRequest)).thenReturn(rosterResult); + var serverIdentity = pki.identity("server"); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .maxInboundMessageSize(GameSessionCharacterCreatePublicSourceService.MAX_REQUEST_BYTES) + .addService( + ServerInterceptors.intercept( + new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"), + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + for (String caller : new String[] {"account", "entity", "foreign", "foreign-entity"}) { + ManagedChannel channel = channel(pki, caller, server.getPort()); + try { + String expected = "spiffe://firemud/ns/firemud/sa/game-session-service"; + var stub = + CharacterCreatePublicSourceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expected)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expected)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + if (caller.equals("account")) { + assertThat(stub.readCharacterCreatePublicSource(request)).isEqualTo(result); + assertThat(stub.resolveCharacterCreatePublicTarget(targetRequest)) + .isEqualTo(targetResult); + } else { + var headers = new Metadata(); + headers.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer controlled-not-authority"); + var bearerStub = + stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(headers)); + assertThatThrownBy(() -> bearerStub.readCharacterCreatePublicSource(request)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThatThrownBy(() -> bearerStub.resolveCharacterCreatePublicTarget(targetRequest)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + if (caller.equals("entity")) { + assertThat(stub.readPlayerCreatedRosterSource(rosterRequest)).isEqualTo(rosterResult); + } else { + var headers = new Metadata(); + headers.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), + "Bearer controlled-entity-assertion-not-authority"); + var bearerStub = + stub.withInterceptors(MetadataUtils.newAttachHeadersInterceptor(headers)); + assertThatThrownBy(() -> bearerStub.readPlayerCreatedRosterSource(rosterRequest)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } + } finally { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + verify(source, times(1)).read(request); + verify(source, times(1)).resolve(targetRequest); + verify(source, times(1)).readPlayerCreatedRosterSource(rosterRequest); + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private static ManagedChannel channel(LoopbackMtlsTestPki.Pki pki, String name, int port) + throws Exception { + var identity = pki.identity(name); + return NettyChannelBuilder.forAddress("127.0.0.1", port) + .sslContext( + GrpcSslContexts.configure( + io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forClient()) + .trustManager(pki.caCertificate()) + .keyManager(identity.privateKey(), identity.certificate()) + .build()) + .maxInboundMessageSize(GameSessionCharacterCreatePublicSourceService.MAX_RESPONSE_BYTES) + .build(); + } +} 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 new file mode 100644 index 0000000000..eca7c2edc3 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java @@ -0,0 +1,922 @@ +package net.firedevops.firemud.gamesession.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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.StatusRuntimeException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +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; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; +import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; +import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; +import net.firedevops.firemud.gamesession.client.GameDesignPublishedRealmPolicyClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalRealmCatalogSnapshot; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredActorCoreRetentionRepository.Candidate; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceRequest; +import net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceRequest; +import net.firedevops.firemud.gamesession.v1.ResolveCharacterCreatePublicTargetRequest; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Controlled composition proof. Owner repositories, cryptographic clients and source codecs are + * doubles here; this does not qualify genuine issuance, publication, lifecycle or deployed custody. + */ +class GameSessionCharacterCreatePublicSourceServiceTest { + private static final String NAMESPACE = "firemud"; + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID REALM = UUID.randomUUID(); + private static final UUID INSTANCE = UUID.randomUUID(); + private static final UUID PLAYABLE = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void accountReadsDoNotCallTheRosterPublishedPolicyOwner() { + try (var fixture = new Fixture()) { + fixture.service.read(request()); + fixture.service.resolve(resolveRequest()); + verifyNoInteractions(fixture.publishedPolicies); + } + } + + @Test + void entityRosterRejectsMissingOrChangedSealedPolicyAndOriginalSourceIdentity() { + List> invalidations = + List.of( + fixture -> + when(fixture.publishedPolicies.listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenReturn(null), + fixture -> + when(fixture.policySet.requireValidDigest()) + .thenThrow(new IllegalArgumentException("invalid set")), + fixture -> + when(fixture.publicationOperation.world().request().targetNamespace()) + .thenReturn("other"), + fixture -> + when(fixture.policySet.target().canonicalTenantId()).thenReturn(UUID.randomUUID()), + fixture -> + when(fixture.policySet.target().canonicalVersionId()).thenReturn(UUID.randomUUID()), + fixture -> when(fixture.policySet.sourceCommitId()).thenReturn(UUID.randomUUID()), + fixture -> when(fixture.policySet.publishWorkflowId()).thenReturn("other-publication"), + fixture -> + when(fixture.policySet.publishedReleaseBundleRef()).thenReturn("other-release"), + fixture -> + when(fixture.policySet.publishedReleaseBundleDigest()) + .thenReturn("sha256:" + "4".repeat(64)), + fixture -> + when(fixture.policySet.manifestHash()).thenReturn("sha256:" + "4".repeat(64)), + fixture -> when(fixture.policySet.versionNumber()).thenReturn(2), + fixture -> + when(fixture.publicationTerminal.publishedReleaseBundleDigest()) + .thenReturn("sha256:" + "4".repeat(64)), + fixture -> + when(fixture.publicationTerminal.releaseContent().canonicalBytes()) + .thenReturn(new byte[] {9}), + fixture -> when(fixture.policySet.policies()).thenReturn(List.of()), + fixture -> + when(fixture.policySet.policies()) + .thenReturn(List.of(fixture.policyEvidence, fixture.policyEvidence)), + fixture -> + when(fixture.policyEvidence.requireValidDigest(fixture.policySet)) + .thenThrow(new IllegalArgumentException("invalid policy")), + fixture -> when(fixture.policy.schemaVersion()).thenReturn(2), + fixture -> + when(fixture.policy.canonicalJson()).thenReturn("different-policy-and-descriptor"), + fixture -> when(fixture.policyEvidence.sourceCommitId()).thenReturn(UUID.randomUUID()), + fixture -> + when(fixture.policyEvidence.sourceRevisionId()).thenReturn(UUID.randomUUID()), + fixture -> + when(fixture.policyEvidence.logicalRevisionId()) + .thenReturn("different-logical-revision"), + fixture -> + when(fixture + .publicationOperation + .account() + .input() + .selection() + .selectedCommit() + .digest()) + .thenReturn("sha256:" + "5".repeat(64))); + for (var invalidate : invalidations) { + try (var fixture = new Fixture()) { + invalidate.accept(fixture); + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(RuntimeException.class); + } + } + } + + @Test + void finalTargetRereadOccursAfterTheAdditionalPublishedPolicyOwnerCall() { + try (var fixture = new Fixture()) { + var changed = mock(CanonicalPlayableTarget.class); + when(changed.targetNamespace()).thenReturn("other"); + when(fixture.publishedPolicies.listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenAnswer( + invocation -> { + when(fixture.routes.readCurrentTarget(TENANT)).thenReturn(changed); + return fixture.policySet; + }); + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(StatusRuntimeException.class); + verify(fixture.gameDesign).read(any()); + verify(fixture.world).read(any()); + verify(fixture.publishedPolicies).listPublishedRealmEntryPolicies(TENANT, VERSION); + } + } + + @Test + void entityRosterSourcePreservesFullOriginalOwnerProofWithoutAccountScopeOrClock() { + try (var fixture = new Fixture()) { + var account = fixture.service.read(request()); + var result = fixture.service.readPlayerCreatedRosterSource(rosterRequest()); + assertThat(result.getRequest()).isEqualTo(rosterRequest()); + assertThat(result.getCatalog()).isEqualTo(account.getCatalog()); + assertThat(result.getPointer()).isEqualTo(account.getPointer()); + assertThat(result.getCanonicalVersionId()).isEqualTo(VERSION.toString()); + assertThat(result.getActiveLifecycleEpoch()).isEqualTo(7); + assertThat(result.getOriginalControlPlaneRequestId()) + .isEqualTo(account.getOriginalControlPlaneRequestId()); + assertThat(result.getOriginalOwnerAttemptId()).isEqualTo(account.getOriginalOwnerAttemptId()); + assertThat(result.getOriginalOwnerFence()).isEqualTo(account.getOriginalOwnerFence()); + assertThat(result.getAuthoredSource().toByteArray()) + .containsExactly(account.getAuthoredSource().toByteArray()); + assertThat(result.getWorldLifecycleEvidence()).isEqualTo(account.getWorldLifecycleEvidence()); + assertThat(result.getPublishedPolicySetEvidence().toByteArray()) + .containsExactly(fixture.policySet.canonicalBytes()); + verify(fixture.publishedPolicies).listPublishedRealmEntryPolicies(TENANT, VERSION); + assertThat(result.getPointer().getUpdatedAt()).isEqualTo("2026-10-24T00:00:00.123456789Z"); + verify(fixture.gameDesign, org.mockito.Mockito.times(2)).read(any()); + verify(fixture.world, org.mockito.Mockito.times(2)).read(any()); + } + } + + @Test + void entityRosterRequiresExactVersionEpochAndTargetBeforeAnyOtherOwner() { + try (var fixture = new Fixture()) { + for (var changed : + List.of( + rosterRequest().toBuilder() + .setExpectedCanonicalVersionId(UUID.randomUUID().toString()) + .build(), + rosterRequest().toBuilder().setActiveWorldEpoch(8).build(), + rosterRequest().toBuilder() + .setCanonicalTenantId(UUID.randomUUID().toString()) + .build(), + rosterRequest().toBuilder().setRealmId(UUID.randomUUID().toString()).build(), + rosterRequest().toBuilder().setWorldSlug("other").build(), + rosterRequest().toBuilder().setRealmSlug("other").build(), + rosterRequest().toBuilder() + .setCanonicalGameInstanceId(UUID.randomUUID().toString()) + .build(), + rosterRequest().toBuilder() + .setPlayableStateNamespaceId(UUID.randomUUID().toString()) + .build(), + rosterRequest().toBuilder().setCatalogRevision(2).build(), + rosterRequest().toBuilder().setPointerVersion(4).build())) { + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(changed)) + .isInstanceOf(StatusRuntimeException.class); + } + verifyNoInteractions( + fixture.catalogs, + fixture.admissions, + fixture.launches, + fixture.retention, + fixture.gameDesign, + fixture.world); + } + } + + @Test + void entityRosterRechecksExpectedVersionAndEpochAfterIndependentOwnerCalls() { + for (boolean changeVersion : List.of(true, false)) { + try (var fixture = new Fixture()) { + var changed = mock(CanonicalPlayableTarget.class); + when(changed.targetNamespace()).thenReturn(NAMESPACE); + when(changed.canonicalTenantId()).thenReturn(TENANT); + when(changed.realmId()).thenReturn(REALM); + when(changed.worldSlug()).thenReturn("world"); + when(changed.realmSlug()).thenReturn("realm"); + when(changed.playableStateNamespaceId()).thenReturn(PLAYABLE); + when(changed.playableStateScope()).thenReturn("SHARED"); + when(changed.canonicalGameInstanceId()).thenReturn(INSTANCE); + when(changed.catalogRevision()).thenReturn(1L); + when(changed.pointerVersion()).thenReturn(3L); + when(changed.canonicalVersionId()).thenReturn(changeVersion ? UUID.randomUUID() : VERSION); + when(changed.activeWorldEpoch()).thenReturn(changeVersion ? 7L : 8L); + when(changed.characterCreationPolicy()).thenReturn("PLAYER_CREATED"); + when(fixture.routes.readCurrentTarget(TENANT)).thenReturn(fixture.route, changed); + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(StatusRuntimeException.class); + verify(fixture.gameDesign).read(any()); + verify(fixture.world).read(any()); + } + } + } + + @Test + void entityRosterRefusesOriginalSourceSubstitutionAndInactiveWorld() { + try (var fixture = new Fixture()) { + when(fixture.authored.canonicalBytes()).thenReturn(new byte[] {9}); + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(fixture.world); + } + try (var fixture = new Fixture()) { + when(fixture.lifecycle.lifecycleStatus()).thenReturn("TERMINATING"); + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(StatusRuntimeException.class); + } + try (var fixture = new Fixture()) { + when(fixture.candidate.canonicalSourceResultBytes()) + .thenReturn("retained".getBytes(java.nio.charset.StandardCharsets.UTF_8), new byte[] {9}); + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(StatusRuntimeException.class); + verify(fixture.world).read(any()); + } + } + + @Test + void entityRosterRefusesAmbientSqlBeforeReadingAnyOwner() { + try (var fixture = new Fixture()) { + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions( + fixture.routes, + fixture.catalogs, + fixture.admissions, + fixture.launches, + fixture.retention, + fixture.gameDesign, + fixture.world); + } + } + + static ReadPlayerCreatedRosterSourceRequest rosterRequest() { + return ReadPlayerCreatedRosterSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId("60000000-0000-4000-8000-000000000003") + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(TENANT.toString()) + .setRealmId(REALM.toString()) + .setWorldSlug("world") + .setRealmSlug("realm") + .setPlayableStateNamespaceId(PLAYABLE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceId(INSTANCE.toString()) + .setCatalogRevision(1) + .setPointerVersion(3) + .setExpectedCanonicalVersionId(VERSION.toString()) + .setActiveWorldEpoch(7) + .build(); + } + + @Test + void resolvesFriendlySelectorsToFullActualCanonicalTargetBeforeScopeIssuance() { + try (var fixture = new Fixture()) { + var response = fixture.service.resolve(resolveRequest()); + assertThat(response.getRequest()).isEqualTo(resolveRequest()); + assertThat(response.getCatalog().getTenantId()).isEqualTo(TENANT.toString()); + assertThat(response.getCatalog().getTenantSlug()).isEqualTo("tenant"); + assertThat(response.getCatalog().getRealmId()).isEqualTo(REALM.toString()); + assertThat(response.getCatalog().getWorldSlug()).isEqualTo("world"); + assertThat(response.getCatalog().getRealmSlug()).isEqualTo("realm"); + assertThat(response.getCatalog().getWorldDisplayName()).isEqualTo("Published world"); + assertThat(response.getCatalog().getRealmDisplayName()).isEqualTo("Published realm"); + assertThat(response.getCatalog().getPlayableStateNamespaceId()) + .isEqualTo(PLAYABLE.toString()); + assertThat(response.getCatalog().getStateScope()).isEqualTo("SHARED"); + assertThat(response.getCatalog().getVisible()).isTrue(); + assertThat(response.getCatalog().getPublicProduction()).isTrue(); + assertThat(response.getCatalog().getCharacterCreationPolicy()).isEqualTo("PLAYER_CREATED"); + assertThat(response.getCatalog().getCatalogRevision()).isEqualTo(1); + assertThat(response.getPointer().getPointerVersion()).isEqualTo(3); + assertThat(response.getPointer().getAdmissionState()).isEqualTo("OPEN"); + assertThat(response.getPointer().getUpdatedAt()).isEqualTo("2026-10-24T00:00:00.123456789Z"); + assertThat(response.getCanonicalGameInstanceId()).isEqualTo(INSTANCE.toString()); + assertThat(response.getCanonicalVersionId()).isEqualTo(VERSION.toString()); + assertThat(response.getActiveLifecycleEpoch()).isEqualTo(7); + assertThat(fixture.service.resolve(resolveRequest())).isEqualTo(response); + verifyNoInteractions(fixture.launches, fixture.retention, fixture.gameDesign, fixture.world); + } + } + + @Test + void friendlyResolutionRejectsUnknownAmbiguousAndUnsupportedTargets() { + try (var fixture = new Fixture()) { + var unknown = resolveRequest().toBuilder().setWorldSlug("unknown").build(); + assertThatThrownBy(() -> fixture.service.resolve(unknown)) + .isInstanceOf(StatusRuntimeException.class); + when(fixture.routes.readVisiblePublicProductionTargets()).thenReturn(List.of()); + assertThatThrownBy(() -> fixture.service.resolve(resolveRequest())) + .isInstanceOf(StatusRuntimeException.class); + when(fixture.routes.readVisiblePublicProductionTargets()) + .thenReturn(List.of(fixture.route, fixture.route)); + assertThatThrownBy(() -> fixture.service.resolve(resolveRequest())) + .isInstanceOf(StatusRuntimeException.class); + when(fixture.routes.readVisiblePublicProductionTargets()).thenReturn(List.of(fixture.route)); + when(fixture.route.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + assertThatThrownBy(() -> fixture.service.resolve(resolveRequest())) + .isInstanceOf(StatusRuntimeException.class); + when(fixture.route.characterCreationPolicy()).thenReturn("PLAYER_CREATED"); + when(fixture.route.playableStateScope()).thenReturn("ISOLATED"); + assertThatThrownBy(() -> fixture.service.resolve(resolveRequest())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions( + fixture.catalogs, + fixture.admissions, + fixture.launches, + fixture.retention, + fixture.gameDesign, + fixture.world); + } + } + + @Test + void friendlyResolutionRejectsPublicPolicyDenialAndCurrentRouteReplacement() { + try (var fixture = new Fixture()) { + when(fixture.catalog.publicProduction()).thenReturn(false); + assertThatThrownBy(() -> fixture.service.resolve(resolveRequest())) + .isInstanceOf(StatusRuntimeException.class); + when(fixture.catalog.publicProduction()).thenReturn(true); + when(fixture.catalog.visible()).thenReturn(false); + assertThatThrownBy(() -> fixture.service.resolve(resolveRequest())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(fixture.gameDesign, fixture.world); + } + try (var fixture = new Fixture()) { + var changed = mock(CanonicalPlayableTarget.class); + when(fixture.routes.readCurrentTarget(TENANT)).thenReturn(fixture.route, changed); + assertThatThrownBy(() -> fixture.service.resolve(resolveRequest())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(fixture.gameDesign, fixture.world); + } + } + + static ResolveCharacterCreatePublicTargetRequest resolveRequest() { + return ResolveCharacterCreatePublicTargetRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId("60000000-0000-4000-8000-000000000002") + .setTargetNamespace(NAMESPACE) + .setWorldSlug("world") + .setRealmSlug("realm") + .build(); + } + + @Test + void failedFixtureConstructionClosesOnlyItsPartiallyOpenedStaticCodecs() { + try (var existingPolicyMock = mockStatic(RealmEntryPolicy.class)) { + assertThatThrownBy(Fixture::new) + .isInstanceOf(org.mockito.exceptions.base.MockitoException.class); + assertThat(existingPolicyMock.isClosed()).isFalse(); + } + try (var fixture = new Fixture()) { + assertThat(fixture.service.read(request()).getRequest()).isEqualTo(request()); + } + } + + @Test + void returnsExactOriginalSourceAndFullPointerTimestampAfterIndependentOwnerReads() { + try (var fixture = new Fixture()) { + var result = fixture.service.read(request()); + assertThat(result.getRequest()).isEqualTo(request()); + assertThat(result.getCatalog().getCharacterCreationPolicy()).isEqualTo("PLAYER_CREATED"); + assertThat(result.getCatalog().getWorldDisplayName()).isEqualTo("Published world"); + assertThat(result.getCatalog().getRealmDisplayName()).isEqualTo("Published realm"); + assertThat(result.getPointer().getUpdatedAt()).isEqualTo("2026-10-24T00:00:00.123456789Z"); + assertThat(result.getPointer().getAdmissionState()).isEqualTo("OPEN"); + assertThat(result.getCanonicalVersionId()).isEqualTo(VERSION.toString()); + assertThat(result.getActiveLifecycleEpoch()).isEqualTo(7); + assertThat(result.getAuthoredSource().getCanonicalResultBytes()) + .isEqualTo(ByteString.copyFromUtf8("retained")); + assertThat(result.getWorldLifecycleEvidence()) + .isEqualTo(ByteString.copyFromUtf8("world-original")); + verify(fixture.gameDesign).read(any()); + verify(fixture.world).read(any()); + assertThat(fixture.service.read(request())).isEqualTo(result); + } + } + + @Test + void rejectsChangedSelectorsAndUnsupportedScopesBeforeAnyOtherOwner() { + try (var fixture = new Fixture()) { + for (var altered : + List.of( + request().toBuilder().setRealmId(UUID.randomUUID().toString()).build(), + request().toBuilder() + .setCanonicalGameInstanceId(UUID.randomUUID().toString()) + .build(), + request().toBuilder() + .setPlayableStateNamespaceId(UUID.randomUUID().toString()) + .build(), + request().toBuilder().setCatalogRevision(2).build(), + request().toBuilder().setPointerVersion(4).build(), + request().toBuilder().setRealmSlug("other").build(), + request().toBuilder().setPlayableStateScope("ISOLATED").build())) { + assertThatThrownBy(() -> fixture.service.read(altered)) + .isInstanceOf(StatusRuntimeException.class); + } + verifyNoInteractions( + fixture.catalogs, + fixture.admissions, + fixture.launches, + fixture.retention, + fixture.gameDesign, + fixture.world); + } + } + + @Test + void rejectsMissingRetainedOriginalWithoutCapturingOrCallingRemoteOwners() { + try (var fixture = new Fixture()) { + when(fixture.retention.readByOriginalOperation(NAMESPACE, "original-launch")) + .thenReturn(Optional.empty()); + assertThatThrownBy(() -> fixture.service.read(request())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(fixture.gameDesign, fixture.world); + } + } + + @Test + void rejectsChangedPublicationProvenanceBeforeAuthoredOwnerCall() { + try (var fixture = new Fixture()) { + when(fixture.candidate.selectedCommitId()).thenReturn(UUID.randomUUID()); + assertThatThrownBy(() -> fixture.service.read(request())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(fixture.gameDesign, fixture.world); + } + } + + @Test + void rejectsOriginalSourceReplacementWithoutCallingWorld() { + try (var fixture = new Fixture()) { + when(fixture.authored.canonicalBytes()).thenReturn(new byte[] {9}); + assertThatThrownBy(() -> fixture.service.read(request())) + .isInstanceOf(StatusRuntimeException.class); + verifyNoInteractions(fixture.world); + } + } + + @Test + void rejectsWorldNonActiveAndChangedCurrentTargetAfterRemoteReads() { + try (var fixture = new Fixture()) { + when(fixture.lifecycle.lifecycleStatus()).thenReturn("TERMINATING"); + assertThatThrownBy(() -> fixture.service.read(request())) + .isInstanceOf(StatusRuntimeException.class); + } + try (var fixture = new Fixture()) { + var changed = mock(CanonicalPlayableTarget.class); + when(changed.targetNamespace()).thenReturn("other"); + when(fixture.routes.readCurrentTarget(TENANT)).thenReturn(fixture.route, changed); + assertThatThrownBy(() -> fixture.service.read(request())) + .isInstanceOf(StatusRuntimeException.class); + } + } + + @Test + void rejectsAmbientTransactionBeforeReadingAnyOwner() { + try (var fixture = new Fixture()) { + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> fixture.service.read(request())) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + verifyNoInteractions( + fixture.routes, + fixture.catalogs, + fixture.admissions, + fixture.launches, + fixture.retention, + fixture.gameDesign, + fixture.world); + } + } + + static ReadCharacterCreatePublicSourceRequest request() { + return ReadCharacterCreatePublicSourceRequest.newBuilder() + .setSchemaVersion(1) + .setReadRequestId("60000000-0000-4000-8000-000000000001") + .setTargetNamespace(NAMESPACE) + .setCanonicalTenantId(TENANT.toString()) + .setRealmId(REALM.toString()) + .setWorldSlug("world") + .setRealmSlug("realm") + .setPlayableStateNamespaceId(PLAYABLE.toString()) + .setPlayableStateScope("SHARED") + .setCanonicalGameInstanceId(INSTANCE.toString()) + .setCatalogRevision(1) + .setPointerVersion(3) + .setEvaluatedAt("2026-10-24T00:00:00Z") + .setConnectScopeExpiresAt("2026-10-24T00:05:00Z") + .build(); + } + + private static final class Fixture implements AutoCloseable { + final CanonicalPlayerRouteReadService routes = mock(CanonicalPlayerRouteReadService.class); + final GameSessionCanonicalRealmCatalogRepository catalogs = + mock(GameSessionCanonicalRealmCatalogRepository.class); + final CanonicalInitialAdmissionRepository admissions = + mock(CanonicalInitialAdmissionRepository.class); + final CanonicalGameInstanceLaunchAssociationRepository launches = + mock(CanonicalGameInstanceLaunchAssociationRepository.class); + final GameSessionAuthoredActorCoreRetentionRepository retention = + mock(GameSessionAuthoredActorCoreRetentionRepository.class); + final AuthoredInitialActorCoreReadClient gameDesign = + mock(AuthoredInitialActorCoreReadClient.class); + final WorldCanonicalInstanceLifecycleClient world = + mock(WorldCanonicalInstanceLifecycleClient.class); + final GameDesignPublishedRealmPolicyClient publishedPolicies = + mock(GameDesignPublishedRealmPolicyClient.class); + final PublishedRealmEntryPolicySetEvidence policySet = + mock(PublishedRealmEntryPolicySetEvidence.class, RETURNS_DEEP_STUBS); + final PublishedRealmEntryPolicyEvidence policyEvidence = + mock(PublishedRealmEntryPolicyEvidence.class); + final AuthoredInitialActorCoreProjection projection = + mock(AuthoredInitialActorCoreProjection.class, RETURNS_DEEP_STUBS); + final RealmEntryPolicy policy = mock(RealmEntryPolicy.class); + final GameDesignPublicationOperationBinding publicationOperation = + mock(GameDesignPublicationOperationBinding.class, RETURNS_DEEP_STUBS); + final GameDesignPublicationTerminalEvidence publicationTerminal = + mock(GameDesignPublicationTerminalEvidence.class, RETURNS_DEEP_STUBS); + final CanonicalPlayableTarget route = mock(CanonicalPlayableTarget.class); + final CanonicalRealmCatalogSnapshot catalog = + mock(CanonicalRealmCatalogSnapshot.class, RETURNS_DEEP_STUBS); + final Candidate candidate = mock(Candidate.class); + final AuthoredInitialActorCoreReadEvidence.ReadResult authored = + mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); + final WorldCanonicalInstanceLifecycleEvidence lifecycle = + mock(WorldCanonicalInstanceLifecycleEvidence.class); + private org.mockito.MockedStatic associationCodec; + private org.mockito.MockedStatic sourceCodec; + private org.mockito.MockedStatic policyCodec; + private org.mockito.MockedStatic + publicationOperationCodec; + private org.mockito.MockedStatic + publicationTerminalCodec; + private org.mockito.MockedConstruction + releaseContentCodec; + final GameSessionCharacterCreatePublicSourceService service; + + Fixture() { + try { + associationCodec = mockStatic(StartSessionTemplateAssociationReadGrpcCodec.class); + sourceCodec = mockStatic(AuthoredInitialActorCoreReadGrpcCodec.class); + policyCodec = mockStatic(RealmEntryPolicy.class); + publicationOperationCodec = mockStatic(GameDesignPublicationOperationBinding.class); + publicationTerminalCodec = mockStatic(GameDesignPublicationTerminalEvidence.class); + releaseContentCodec = + org.mockito.Mockito.mockConstruction( + GameDesignPublicationTerminalEvidence.ReleaseContent.class, + (value, context) -> { + when(value.contentDigest()).thenReturn("sha256:" + "1".repeat(64)); + when(value.canonicalBytes()).thenReturn(new byte[] {8}); + }); + policyCodec.when(() -> RealmEntryPolicy.isCanonicalSlug(anyString())).thenCallRealMethod(); + UUID sourceOperation = UUID.randomUUID(); + UUID commit = UUID.randomUUID(); + UUID owner = UUID.randomUUID(); + byte[] tuple = new byte[] {1}; + byte[] account = new byte[] {2}; + byte[] sourceBytes = "retained".getBytes(java.nio.charset.StandardCharsets.UTF_8); + var launch = mock(CanonicalGameInstanceLaunchAssociation.class, RETURNS_DEEP_STUBS); + var proof = mock(CanonicalInitialAdmissionOwnerProof.class); + when(proof.provesCommit()).thenReturn(true); + when(proof.proofDigest()).thenReturn("sha256:" + "a".repeat(64)); + when(proof.initialAdmissionRequestId()).thenReturn("open-original"); + when(proof.activeLifecycleEpoch()).thenReturn(7L); + var pointer = + new CanonicalInitialAdmissionRepository.CurrentOpenSource( + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, "b".repeat(64)), + TENANT, + REALM, + "world", + "realm", + "OPEN", + INSTANCE, + 3, + 1, + Instant.parse("2026-10-24T00:00:00.123456789Z")); + when(routes.readCurrentTarget(TENANT)).thenReturn(route); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(route)); + when(route.targetNamespace()).thenReturn(NAMESPACE); + when(route.canonicalTenantId()).thenReturn(TENANT); + when(route.tenantSlug()).thenReturn("tenant"); + when(route.realmId()).thenReturn(REALM); + when(route.worldSlug()).thenReturn("world"); + when(route.realmSlug()).thenReturn("realm"); + when(route.worldDisplayName()).thenReturn("Published world"); + when(route.realmDisplayName()).thenReturn("Published realm"); + when(route.playableStateNamespaceId()).thenReturn(PLAYABLE); + when(route.playableStateScope()).thenReturn("SHARED"); + when(route.canonicalGameInstanceId()).thenReturn(INSTANCE); + when(route.canonicalVersionId()).thenReturn(VERSION); + when(route.catalogRevision()).thenReturn(1L); + when(route.pointerVersion()).thenReturn(3L); + when(route.characterCreationPolicy()).thenReturn("PLAYER_CREATED"); + when(route.activeWorldEpoch()).thenReturn(7L); + when(route.ownerProofDigest()).thenReturn("sha256:" + "a".repeat(64)); + when(route.admissionPointerSnapshotDigest()).thenReturn("b".repeat(64)); + when(catalogs.readUniqueVisiblePublicProduction(NAMESPACE, TENANT)) + .thenReturn(Optional.of(catalog)); + when(catalog.targetNamespace()).thenReturn(NAMESPACE); + when(catalog.tenantId()).thenReturn(TENANT); + when(catalog.tenantSlug()).thenReturn("tenant"); + when(catalog.realmId()).thenReturn(REALM); + when(catalog.worldSlug()).thenReturn("world"); + when(catalog.realmSlug()).thenReturn("realm"); + when(catalog.realmDisplayName()).thenReturn("Published realm"); + when(catalog.sourceIntakeReceipt().source().worldDisplayName()) + .thenReturn("Published world"); + when(catalog.sourceIntakeReceipt().source().operationId()).thenReturn(sourceOperation); + when(catalog.sourceIntakeReceipt().source().evidenceDigest()).thenReturn("source-digest"); + when(catalog.playableStateNamespaceId()).thenReturn(PLAYABLE); + when(catalog.stateScope()).thenReturn("SHARED"); + when(catalog.visible()).thenReturn(true); + when(catalog.publicProduction()).thenReturn(true); + when(catalog.characterCreationPolicy()).thenReturn("PLAYER_CREATED"); + when(catalog.catalogRevision()).thenReturn(1L); + when(catalog.creationRequestId()).thenReturn(UUID.randomUUID()); + when(catalog.receiptDigest()).thenReturn("catalog-receipt"); + when(admissions.readCurrentOpenSourceForRealm(NAMESPACE, TENANT, REALM)) + .thenReturn(pointer); + when(launch.targetNamespace()).thenReturn(NAMESPACE); + when(launch.canonicalTenantId()).thenReturn(TENANT); + when(launch.gameInstanceUuid()).thenReturn(INSTANCE); + when(launch.worldSlug()).thenReturn("world"); + when(launch.controlPlaneRequestId()).thenReturn("original-launch"); + when(launch.launchDescriptorId()).thenReturn("original-descriptor"); + when(launch.playableStateNamespaceId()).thenReturn(PLAYABLE); + when(launch.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(launch.publicProduction()).thenReturn(true); + when(launch.currentGameInstanceStatus()) + .thenReturn(CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.RUNNING); + when(launch.launchBindingEvidence().descriptor().requestDigest()) + .thenReturn("sha256:" + "c".repeat(64)); + when(launch.launchBindingEvidence().descriptor().resultDigest()) + .thenReturn("sha256:" + "d".repeat(64)); + when(launch.launchBindingEvidence().releaseAttestation().evidenceDigest()) + .thenReturn("sha256:" + "e".repeat(64)); + when(launch.launchBindingEvidence().releaseAttestation().canonicalVersionId()) + .thenReturn(VERSION); + var launchBinding = launch.launchBindingEvidence(); + var launchDescriptor = launchBinding.descriptor(); + String descriptorRequestDigest = launchDescriptor.requestDigest(); + String descriptorResultDigest = launchDescriptor.resultDigest(); + String releaseDigest = launchBinding.releaseAttestation().evidenceDigest(); + var launchTarget = mock(CanonicalInitialAdmissionLaunchTarget.class); + when(launchTarget.association()).thenReturn(launch); + when(launches.readForInitialAdmission(NAMESPACE, TENANT, REALM, INSTANCE)) + .thenReturn(Optional.of(launchTarget)); + when(retention.readByOriginalOperation(NAMESPACE, "original-launch")) + .thenReturn( + Optional.of( + new GameSessionAuthoredActorCoreRetentionRepository.StoredSource( + candidate, Instant.EPOCH))); + when(candidate.targetNamespace()).thenReturn(NAMESPACE); + when(candidate.canonicalTenantId()).thenReturn(TENANT); + when(candidate.gameInstanceUuid()).thenReturn(INSTANCE); + when(candidate.controlPlaneRequestId()).thenReturn("original-launch"); + when(candidate.worldSlug()).thenReturn("world"); + when(candidate.ownerAttemptId()).thenReturn(owner); + when(candidate.ownerFence()).thenReturn(8L); + when(candidate.originalPostAuthorizationTuple()).thenReturn(tuple); + when(candidate.accountRedemptionProjection()).thenReturn(account); + when(candidate.canonicalVersionId()).thenReturn(VERSION); + when(candidate.selectedCommitId()).thenReturn(commit); + when(candidate.publishWorkflowId()).thenReturn("publication"); + when(candidate.associationDigest()).thenReturn("association"); + when(candidate.worldSourceOperationId()).thenReturn(sourceOperation); + when(candidate.worldSourceEvidenceDigest()).thenReturn("source-digest"); + when(candidate.launchDescriptorId()).thenReturn("original-descriptor"); + when(candidate.descriptorRequestDigest()).thenReturn(descriptorRequestDigest); + when(candidate.descriptorResultDigest()).thenReturn(descriptorResultDigest); + when(candidate.releaseAttestationEvidenceDigest()).thenReturn(releaseDigest); + when(candidate.sourceReadRequestBytes()).thenReturn(new byte[0]); + when(candidate.canonicalSourceResultBytes()).thenReturn(sourceBytes); + when(candidate.sourceResultDigest()).thenReturn("source-result-digest"); + var associationRequest = mock(StartSessionTemplateAssociationReadEvidence.Request.class); + when(associationRequest.selection()) + .thenReturn( + new StartSessionTemplateAssociationReadEvidence.ExactReplay( + VERSION, commit, "publication", "sha256:" + "f".repeat(64))); + associationCodec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.fromRequest(any())) + .thenReturn(associationRequest); + associationCodec + .when(() -> StartSessionTemplateAssociationReadGrpcCodec.toRequest(any())) + .thenReturn(ReadStartSessionTemplateAssociationRequest.getDefaultInstance()); + var historical = + mock(HistoricalOriginalStartSessionOwnerEvidence.Result.class, RETURNS_DEEP_STUBS); + when(launches.readHistoricalOriginalStartSessionOwnerEvidence(any())) + .thenReturn(Optional.of(historical)); + when(historical.ownerAttemptId()).thenReturn(owner); + when(historical.ownerFence()).thenReturn(8L); + when(historical.originalTuple().canonicalBytes()).thenReturn(tuple); + when(historical.accountRedemptionProjection()).thenReturn(account); + when(historical.descriptorPin().associationRead().request()).thenReturn(associationRequest); + var selected = historical.descriptorPin().associationRead().association(); + when(selected.canonicalVersionId()).thenReturn(VERSION); + when(selected.canonicalTenantId()).thenReturn(TENANT); + when(selected.selectedCommitId()).thenReturn(commit); + when(selected.publishWorkflowId()).thenReturn("publication"); + when(selected.associationDigest()).thenReturn("association"); + when(selected.sourceOperationId()).thenReturn(sourceOperation); + when(selected.sourceEvidenceDigest()).thenReturn("source-digest"); + var original = historical.launchAssociation(); + when(original.targetNamespace()).thenReturn(NAMESPACE); + when(original.canonicalTenantId()).thenReturn(TENANT); + when(original.gameInstanceUuid()).thenReturn(INSTANCE); + when(original.worldSlug()).thenReturn("world"); + when(original.controlPlaneRequestId()).thenReturn("original-launch"); + when(original.launchDescriptorId()).thenReturn("original-descriptor"); + when(original.playableStateNamespaceId()).thenReturn(PLAYABLE); + when(original.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(original.publicProduction()).thenReturn(true); + when(original.launchBindingEvidence()).thenReturn(launchBinding); + when(authored.request()).thenReturn(associationRequest); + when(authored.canonicalBytes()).thenReturn(sourceBytes); + when(authored.digest()).thenReturn("source-result-digest"); + when(authored.descriptor()).thenReturn(launchDescriptor); + when(projection.policy().canonicalJson()).thenReturn("controlled-policy"); + when(projection.canonicalTenantId()).thenReturn(TENANT); + when(projection.canonicalVersionId()).thenReturn(VERSION); + when(projection.worldSourceOperationId()).thenReturn(sourceOperation); + when(projection.worldSourceEvidenceDigest()).thenReturn("source-digest"); + when(projection.selectedCommitId()).thenReturn(commit); + when(projection.publicationWorkflowId()).thenReturn("publication"); + when(authored.projections()).thenReturn(List.of(projection)); + policyCodec.when(() -> RealmEntryPolicy.parseCanonical(any(), any())).thenReturn(policy); + when(policy.entryPolicy()).thenReturn(RealmEntryPolicy.EntryPolicy.PLAYER_CREATED); + when(policy.visible()).thenReturn(true); + when(policy.publicProduction()).thenReturn(true); + when(policy.stateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); + when(policy.worldSlug()).thenReturn("world"); + when(policy.realmSlug()).thenReturn("realm"); + when(policy.worldDisplayName()).thenReturn("Published world"); + when(policy.realmDisplayName()).thenReturn("Published realm"); + when(policy.schemaVersion()) + .thenReturn(RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION); + when(policy.canonicalJson()).thenReturn("controlled-policy"); + var policyRevision = UUID.randomUUID(); + when(projection.policy().commitId()).thenReturn(commit); + when(projection.policy().revisionId()).thenReturn(policyRevision); + when(projection.policy().logicalRevisionId()).thenReturn("policy-logical"); + when(projection.selectedCommitDigest()).thenReturn("sha256:" + "2".repeat(64)); + var originalAssociationRead = historical.descriptorPin().associationRead(); + when(authored.associationRead()).thenReturn(originalAssociationRead); + when(authored.associationRead().releaseBundle()) + .thenReturn( + PublishedReleaseBundle.newBuilder() + .setId(1L) + .setVersionId(1L) + .setCanonicalTenantId(TENANT.toString()) + .setCanonicalVersionId(VERSION.toString()) + .setPublishWorkflowId("publication") + .setPublishedReleaseBundleRef("original-release") + .setVersionNumber(1) + .setAttestationSchemaVersion("v2") + .setManifestHash("sha256:" + "3".repeat(64)) + .setManifestSchemaVersion(1) + .build()); + when(launchBinding.releaseAttestation().publishedReleaseBundleRef()) + .thenReturn("original-release"); + when(launchBinding.releaseAttestation().publishWorkflowId()).thenReturn("publication"); + when(launchBinding.releaseAttestation().commitId()).thenReturn(commit.toString()); + when(launchBinding.releaseAttestation().manifestHash()) + .thenReturn("sha256:" + "3".repeat(64)); + when(policySet.requireValidDigest()).thenReturn(policySet); + when(policySet.target().canonicalTenantId()).thenReturn(TENANT); + when(policySet.target().canonicalVersionId()).thenReturn(VERSION); + when(policySet.sourceCommitId()).thenReturn(commit); + when(policySet.publishWorkflowId()).thenReturn("publication"); + when(policySet.publishedReleaseBundleRef()).thenReturn("original-release"); + when(policySet.publishedReleaseBundleDigest()).thenReturn("sha256:" + "1".repeat(64)); + when(policySet.manifestHash()).thenReturn("sha256:" + "3".repeat(64)); + when(policySet.versionNumber()).thenReturn(1); + when(policySet.canonicalBytes()) + .thenReturn("controlled-sealed-set".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(policySet.operationBytes()).thenReturn(new byte[] {6}); + when(policySet.terminalEvidenceBytes()).thenReturn(new byte[] {7}); + when(policySet.policies()).thenReturn(List.of(policyEvidence)); + when(policyEvidence.policy()).thenReturn(policy); + when(policyEvidence.requireValidDigest(policySet)).thenReturn(policyEvidence); + when(policyEvidence.sourceCommitId()).thenReturn(commit); + when(policyEvidence.sourceRevisionId()).thenReturn(policyRevision); + when(policyEvidence.logicalRevisionId()).thenReturn("policy-logical"); + publicationOperationCodec + .when(() -> GameDesignPublicationOperationBinding.fromStored(any())) + .thenReturn(publicationOperation); + publicationTerminalCodec + .when(() -> GameDesignPublicationTerminalEvidence.fromStored(any())) + .thenReturn(publicationTerminal); + when(publicationOperation.world().request().targetNamespace()).thenReturn(NAMESPACE); + when(publicationOperation.account().input().selection().selectedCommit().digest()) + .thenReturn("sha256:" + "2".repeat(64)); + when(publicationTerminal.publishedReleaseBundleDigest()) + .thenReturn("sha256:" + "1".repeat(64)); + when(publicationTerminal.releaseContent().canonicalBytes()).thenReturn(new byte[] {8}); + when(publishedPolicies.listPublishedRealmEntryPolicies(TENANT, VERSION)) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return policySet; + }); + when(gameDesign.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return authored; + }); + sourceCodec + .when(() -> AuthoredInitialActorCoreReadGrpcCodec.toResponse(authored)) + .thenReturn( + ReadAuthoredInitialActorCoreResponse.newBuilder() + .setSchemaVersion(1) + .setCanonicalResultBytes(ByteString.copyFrom(sourceBytes)) + .build()); + when(world.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + when(lifecycle.request()).thenReturn(invocation.getArgument(0)); + return lifecycle; + }); + when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycle.lifecycleEpoch()).thenReturn(7L); + when(lifecycle.launchBinding()).thenReturn(launchBinding); + when(lifecycle.canonicalBytes()) + .thenReturn("world-original".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + service = + new GameSessionCharacterCreatePublicSourceService( + NAMESPACE, + routes, + catalogs, + admissions, + launches, + retention, + gameDesign, + world, + publishedPolicies); + } catch (RuntimeException | Error failure) { + close(); + throw failure; + } + } + + @Override + public void close() { + if (releaseContentCodec != null && !releaseContentCodec.isClosed()) + releaseContentCodec.close(); + if (publicationTerminalCodec != null && !publicationTerminalCodec.isClosed()) + publicationTerminalCodec.close(); + if (publicationOperationCodec != null && !publicationOperationCodec.isClosed()) + publicationOperationCodec.close(); + if (policyCodec != null && !policyCodec.isClosed()) policyCodec.close(); + if (sourceCodec != null && !sourceCodec.isClosed()) sourceCodec.close(); + if (associationCodec != null && !associationCodec.isClosed()) associationCodec.close(); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java new file mode 100644 index 0000000000..340bc79c00 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java @@ -0,0 +1,156 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyReadGrpcCodec; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesRequest; +import net.firedevops.firemud.gamedesign.v1.ListPublishedRealmEntryPoliciesResponse; +import net.firedevops.firemud.gamedesign.v1.PublishedRealmEntryPolicyServiceGrpc; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture; + +/** Physical client transport proof over controlled PKI and stipulated complete owner evidence. */ +@Timeout(60) +class GameDesignPublishedRealmPolicyClientMtlsTest { + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Published policy client test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", "spiffe://firemud/ns/test/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "server", "spiffe://firemud/ns/test/sa/game-design-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-service", "spiffe://firemud/ns/test/sa/world-management-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong-namespace", "spiffe://firemud/ns/other/sa/game-design-service", true)); + } + + @Test + void initializedClientReadsCompleteSetOnlyFromExactGameDesignPeer() throws Exception { + exercise("server", true); + } + + @Test + void sameCaWrongServiceAndNamespaceReceiveNoRpc() throws Exception { + for (String identity : List.of("wrong-service", "wrong-namespace")) { + exercise(identity, false); + } + } + + private static void exercise(String identity, boolean accepted) throws Exception { + var evidence = + PublishedRealmPolicyEvidenceFixture.fixture( + PublishedRealmPolicyEvidenceFixture.policy("main", true, true, "SHARED")) + .set(); + var rpcStarts = new AtomicInteger(); + var observedRequest = new AtomicReference(); + var observedPeer = new AtomicReference(); + var service = + new PublishedRealmEntryPolicyServiceGrpc.PublishedRealmEntryPolicyServiceImplBase() { + @Override + public void listPublishedRealmEntryPolicies( + ListPublishedRealmEntryPoliciesRequest request, + StreamObserver observer) { + observedRequest.set(request); + observedPeer.set(GrpcPeerIdentity.current().uri()); + var exact = PublishedRealmEntryPolicyReadGrpcCodec.fromRequest(request); + observer.onNext(PublishedRealmEntryPolicyReadGrpcCodec.toResponse(exact, evidence)); + observer.onCompleted(); + } + }; + var count = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + rpcStarts.incrementAndGet(); + return next.startCall(call, headers); + } + }; + var serverIdentity = pki.identity(identity); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor(), count)) + .build() + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("localhost:" + server.getPort()); + try (var client = + new GameDesignPublishedRealmPolicyClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + "test")) { + client.init(); + if (accepted) { + var result = + client.listPublishedRealmEntryPolicies( + evidence.target().canonicalTenantId(), evidence.target().canonicalVersionId()); + assertThat(result.canonicalBytes()).containsExactly(evidence.canonicalBytes()); + assertThat(rpcStarts).hasValue(1); + assertThat(observedPeer.get()) + .isEqualTo("spiffe://firemud/ns/test/sa/game-session-service"); + assertThat(observedRequest.get().getTargetNamespace()).isEqualTo("test"); + } else { + assertThatThrownBy( + () -> + client.listPublishedRealmEntryPolicies( + evidence.target().canonicalTenantId(), + evidence.target().canonicalVersionId())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(rpcStarts).hasValue(0); + assertThat(observedRequest.get()).isNull(); + assertThat(observedPeer.get()).isNull(); + } + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } +} From b97b2207e3d4c702f23ec737aad0aee4b7716c49 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:44:15 +1300 Subject: [PATCH 02/14] docs: record independent character creation source proof --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 d67e1db6e5..9ce8b04640 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 local candidate prepares the unregistered Game Session public-target discovery and full creation-source reads, plus the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). -This candidate has been materialized against the actual published roster-retention parent, but its independent candidate validation has not run. Earlier mixed-source proof retains its original attribution and does not qualify this comparison. The test publication/owner facts remain controlled; no genuine production source custody, created-actor roster/selection, runtime registration, protected activation or playable journey is established. The broader UUID runtime and CHARACTER_CREATE owners remain separate unfinished receiving work. +At local source `a18dab712f`, independent qualification against the published roster-retention parent passes in 3m53s: 32 Common cases, seven Entity source-client socket cases, 35 Game Session source/policy-client cases and one actual-pointer PostgreSQL case, with zero failures, errors or skips. Affected Main, Test, Integration Test and Common test-fixture static analysis, formatting and documentation checks pass. The pointer case uses real current readers, row locks and the stored timestamp over controlled retained pre1006 history. The source and socket fixtures control upstream publication, lifecycle and owner facts; they do not prove genuine production source custody, created-actor roster/selection, runtime registration, protected activation or a playable journey. Earlier mixed-source proof retains its original attribution. The broader UUID runtime and CHARACTER_CREATE owners remain separate unfinished receiving work. ### Retained Draft authorization fence migrations From 5d2b40903c25a267329e47d4f3437bbe9f97639f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:43:03 +1300 Subject: [PATCH 03/14] Record current published-parent qualification of created-roster source reads --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 9ce8b04640..233fe017df 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 local candidate prepares the unregistered Game Session public-target discove At local source `a18dab712f`, independent qualification against the published roster-retention parent passes in 3m53s: 32 Common cases, seven Entity source-client socket cases, 35 Game Session source/policy-client cases and one actual-pointer PostgreSQL case, with zero failures, errors or skips. Affected Main, Test, Integration Test and Common test-fixture static analysis, formatting and documentation checks pass. The pointer case uses real current readers, row locks and the stored timestamp over controlled retained pre1006 history. The source and socket fixtures control upstream publication, lifecycle and owner facts; they do not prove genuine production source custody, created-actor roster/selection, runtime registration, protected activation or a playable journey. Earlier mixed-source proof retains its original attribution. The broader UUID runtime and CHARACTER_CREATE owners remain separate unfinished receiving work. +After carrying the published roster-retention correction `2c266493a1aa7c048abe9e72f296941d443e0e00`, source checkpoint `0ad0a0beaf6218a0f5bd7d49266e341d9210194c` keeps the same 22-path prerequisite boundary. R4 passes in 5m01s: 32 Common, 354 Entity and 2,505 Game Session unit cases plus 22 selected Entity and 20 selected Game Session PostgreSQL cases, all with zero failures, errors or skips. Affected service static analysis, formatting and documentation checks pass. The existing Common test-fixture static proof retains its earlier attribution. These are source and controlled composition results, preserving the genuine custody, created-roster consumer, admission and activation limits above. + ### Retained Draft authorization fence migrations The [Account fence history fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java) executes the owning filesystem migrations from V75 through V76 and then the current default migration set. Its Account UUID and provenance come from PostgreSQL defaults; it retains the original v1 binding, commit order, stipulated World committed readback, missing Game Design outcome, pending source change and 512-byte source key. Every original column and row version in all six authorization ledger tables, and every prior complete Flyway history row, survives both upgrades. The expected V87 addition of one Global Roles serialization lock is checked separately; it supplies no authority evidence. Exact replay, current pending-mutation refusal and denied binding/readback rewrites leave the retained rows unchanged. From b11470f72795f3f7168c0291275a4abb5cdc54fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:29:30 +1300 Subject: [PATCH 04/14] docs: record created roster source composition proof --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 233fe017df..914a4b0f98 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### Public character-creation and created-roster source preparation +Current qualification at `d84249ff6ac7d18212c98de3f3bd35e522e1ad83` includes the actual published #3294 parent `a277d3758ad2eb113b69479e68ae6a1945d503c5`. R65 freshly passed 1,001 Common and 377 Entity unit cases plus 32 selected Entity PostgreSQL cases; those unchanged-source results retain their original attribution. After the final parent correction, R69 freshly passes 2,524 Game Session unit cases, 49 selected PostgreSQL cases, affected formatting and static analysis, links and Markdown. Fourteen cross-service cases pass in R69; all 22 Communication cases initially fail with the same refused PostgreSQL endpoint, then freshly pass in R70 without code changes. The transient refusal cause remains unproven. R57 rebuilds fresh service images at this reconciled checkpoint 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. These are controlled source/storage and isolated backend proofs; the genuine custody, created-roster consumer, registration, public admission and activation gaps below remain open. + The local candidate prepares the unregistered Game Session public-target discovery and full creation-source reads, plus the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). At local source `a18dab712f`, independent qualification against the published roster-retention parent passes in 3m53s: 32 Common cases, seven Entity source-client socket cases, 35 Game Session source/policy-client cases and one actual-pointer PostgreSQL case, with zero failures, errors or skips. Affected Main, Test, Integration Test and Common test-fixture static analysis, formatting and documentation checks pass. The pointer case uses real current readers, row locks and the stored timestamp over controlled retained pre1006 history. The source and socket fixtures control upstream publication, lifecycle and owner facts; they do not prove genuine production source custody, created-actor roster/selection, runtime registration, protected activation or a playable journey. Earlier mixed-source proof retains its original attribution. The broader UUID runtime and CHARACTER_CREATE owners remain separate unfinished receiving work. From e6682785db8c4aa678ce730b1361f02525fff639 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:36:30 +1300 Subject: [PATCH 05/14] Classify public creation source dependency and owner failures --- .../player-access-and-session.md | 2 + ...haracterCreatePublicSourceGrpcService.java | 23 +- ...ionCharacterCreatePublicSourceService.java | 34 ++- ...cterCreatePublicSourceGrpcServiceTest.java | 55 +++++ ...haracterCreatePublicSourceServiceTest.java | 196 +++++++++++++++++- 5 files changed, 298 insertions(+), 12 deletions(-) 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 914a4b0f98..b5a46e5d5f 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 @@ Current qualification at `d84249ff6ac7d18212c98de3f3bd35e522e1ad83` includes the The local candidate prepares the unregistered Game Session public-target discovery and full creation-source reads, plus the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). +Historical qualification follows for the earlier `a18dab712f` and `0ad0a0be` checkpoints; it does not replace the current qualification above. + At local source `a18dab712f`, independent qualification against the published roster-retention parent passes in 3m53s: 32 Common cases, seven Entity source-client socket cases, 35 Game Session source/policy-client cases and one actual-pointer PostgreSQL case, with zero failures, errors or skips. Affected Main, Test, Integration Test and Common test-fixture static analysis, formatting and documentation checks pass. The pointer case uses real current readers, row locks and the stored timestamp over controlled retained pre1006 history. The source and socket fixtures control upstream publication, lifecycle and owner facts; they do not prove genuine production source custody, created-actor roster/selection, runtime registration, protected activation or a playable journey. Earlier mixed-source proof retains its original attribution. The broader UUID runtime and CHARACTER_CREATE owners remain separate unfinished receiving work. After carrying the published roster-retention correction `2c266493a1aa7c048abe9e72f296941d443e0e00`, source checkpoint `0ad0a0beaf6218a0f5bd7d49266e341d9210194c` keeps the same 22-path prerequisite boundary. R4 passes in 5m01s: 32 Common, 354 Entity and 2,505 Game Session unit cases plus 22 selected Entity and 20 selected Game Session PostgreSQL cases, all with zero failures, errors or skips. Affected service static analysis, formatting and documentation checks pass. The existing Common test-fixture static proof retains its earlier attribution. These are source and controlled composition results, preserving the genuine custody, created-roster consumer, admission and activation limits above. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java index 075253682f..ca54ed9580 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcService.java @@ -52,8 +52,7 @@ public void resolveCharacterCreatePublicTarget( observer.onCompleted(); } catch (StatusRuntimeException status) { observer.onError(status); - } catch (IllegalArgumentException invalid) { - observer.onError(GameSessionCharacterCreatePublicSourceService.invalid()); + } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException storage) { observer.onError( @@ -87,10 +86,16 @@ public void readCharacterCreatePublicSource( } observer.onNext(result); observer.onCompleted(); + } catch ( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + dependency) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Creation source dependency unavailable") + .asRuntimeException()); } catch (StatusRuntimeException status) { observer.onError(status); - } catch (IllegalArgumentException invalid) { - observer.onError(GameSessionCharacterCreatePublicSourceService.invalid()); + } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException storage) { observer.onError( @@ -125,10 +130,16 @@ public void readPlayerCreatedRosterSource( } observer.onNext(result); observer.onCompleted(); + } catch ( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + dependency) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Creation source dependency unavailable") + .asRuntimeException()); } catch (StatusRuntimeException status) { observer.onError(status); - } catch (IllegalArgumentException invalid) { - observer.onError(GameSessionCharacterCreatePublicSourceService.invalid()); + } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException storage) { observer.onError( 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 ff02b13548..f6c73b303b 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 @@ -3,6 +3,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.time.Instant; import java.util.Arrays; import java.util.Objects; @@ -235,7 +236,12 @@ private SourceFacts readSource( requireOriginal(retained, launch, historical, sourceRequest); outsideSql(); - var authored = gameDesign.read(sourceRequest); + AuthoredInitialActorCoreReadEvidence.ReadResult authored; + try { + authored = gameDesign.read(sourceRequest); + } catch (StatusRuntimeException dependency) { + throw new SourceDependencyUnavailableException(dependency); + } if (!Arrays.equals(authored.canonicalBytes(), retained.canonicalSourceResultBytes()) || !authored.digest().equals(retained.sourceResultDigest()) || !sourceRequest.associationRequest().equals(authored.request()) @@ -260,7 +266,12 @@ private SourceFacts readSource( descriptor.resultDigest(), launch.launchBindingEvidence().releaseAttestation().evidenceDigest()); outsideSql(); - var lifecycle = world.read(lifecycleRequest); + WorldCanonicalInstanceLifecycleEvidence lifecycle; + try { + lifecycle = world.read(lifecycleRequest); + } catch (StatusRuntimeException dependency) { + throw new SourceDependencyUnavailableException(dependency); + } if (!lifecycleRequest.equals(lifecycle.request()) || !"ACTIVE".equals(lifecycle.lifecycleStatus()) || lifecycle.lifecycleEpoch() != before.activeWorldEpoch() @@ -303,9 +314,15 @@ private PublishedRealmEntryPolicySetEvidence readPublishedPolicies( AuthoredInitialActorCoreReadEvidence.ReadResult authored, WorldCanonicalInstanceLifecycleEvidence lifecycle) { outsideSql(); - var set = - publishedPolicies.listPublishedRealmEntryPolicies( - route.canonicalTenantId(), route.canonicalVersionId()); + PublishedRealmEntryPolicySetEvidence set; + try { + set = + publishedPolicies.listPublishedRealmEntryPolicies( + route.canonicalTenantId(), route.canonicalVersionId()); + } catch (StatusRuntimeException + | GameDesignPublishedRealmPolicyClient.UninitializedClientException dependency) { + throw new SourceDependencyUnavailableException(dependency); + } if (set == null) throw missing(); set.requireValidDigest(); var operation = GameDesignPublicationOperationBinding.fromStored(set.operationBytes()); @@ -689,6 +706,13 @@ static void outsideSql() { throw new IllegalStateException("Creation source reads must not join an ambient transaction"); } + /** An outbound source owner could not provide evidence; this is not a caller rejection. */ + public static final class SourceDependencyUnavailableException extends RuntimeException { + private SourceDependencyUnavailableException(RuntimeException cause) { + super("Creation source dependency unavailable", cause); + } + } + static RuntimeException invalid() { return Status.INVALID_ARGUMENT .withDescription("Exact bounded public CHARACTER_CREATE selectors required") diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java index 901f889ffa..54f45f9399 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceGrpcServiceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -232,6 +233,60 @@ void rejectsBearerCallerContextAndMalformedFieldsBeforeSourceAccess() { verifyNoInteractions(source); } + @Test + void ownerEvidenceArgumentFailuresArePreconditionsWhileMalformedCallerRequestsRemainInvalid() { + var source = mock(GameSessionCharacterCreatePublicSourceService.class); + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, "firemud"); + var request = request(); + var rosterRequest = GameSessionCharacterCreatePublicSourceServiceTest.rosterRequest(); + var resolveRequest = GameSessionCharacterCreatePublicSourceServiceTest.resolveRequest(); + when(source.read(request)) + .thenThrow(new IllegalArgumentException("invalid retained source evidence")); + when(source.readPlayerCreatedRosterSource(rosterRequest)) + .thenThrow(new IllegalArgumentException("invalid persisted policy evidence")); + when(source.resolve(resolveRequest)) + .thenThrow(new IllegalArgumentException("invalid current owner evidence")); + + var account = call(adapter, "account-service", "firemud", request); + assertThat(account.code).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(account.value).isNull(); + assertThat( + call( + adapter, + "account-service", + "firemud", + request.toBuilder().setSchemaVersion(2).build()) + .code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + var entity = roster(adapter, "entity-management-service", "firemud", rosterRequest); + assertThat(entity.code).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(entity.value).isNull(); + assertThat( + roster( + adapter, + "entity-management-service", + "firemud", + rosterRequest.toBuilder().setSchemaVersion(2).build()) + .code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + var target = resolve(adapter, "account-service", "firemud", resolveRequest); + assertThat(target.code).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(target.value).isNull(); + assertThat( + resolve( + adapter, + "account-service", + "firemud", + resolveRequest.toBuilder().setSchemaVersion(2).build()) + .code) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verify(source).read(request); + verify(source).readPlayerCreatedRosterSource(rosterRequest); + verify(source).resolve(resolveRequest); + } + @Test void echoesExactSelectorsAndPreservesOwnerUnavailableWithoutSubstitution() { var source = mock(GameSessionCharacterCreatePublicSourceService.class); 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 eca7c2edc3..fda3727841 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 @@ -5,6 +5,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.verify; @@ -12,11 +13,15 @@ import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Status; import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; @@ -25,6 +30,9 @@ import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; import net.firedevops.firemud.common.gamesession.HistoricalOriginalStartSessionOwnerEvidence; +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.publication.GameDesignPublicationOperationBinding; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence; import net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence; @@ -64,6 +72,192 @@ class GameSessionCharacterCreatePublicSourceServiceTest { private static final UUID PLAYABLE = UUID.randomUUID(); private static final UUID VERSION = UUID.randomUUID(); + @Test + void actualSourceCompositionClassifiesOutboundStatusesAsDependencyUnavailable() { + for (String boundary : List.of("authored", "world", "policy")) { + for (var status : + List.of( + Status.PERMISSION_DENIED, + Status.UNAUTHENTICATED, + Status.INVALID_ARGUMENT, + Status.DEADLINE_EXCEEDED, + Status.UNAVAILABLE, + Status.FAILED_PRECONDITION)) { + for (boolean rosterRead : List.of(false, true)) { + if (boundary.equals("policy") && !rosterRead) continue; + try (var fixture = new Fixture()) { + var failure = + status.withDescription("private downstream failure details").asRuntimeException(); + if (boundary.equals("authored")) doThrow(failure).when(fixture.gameDesign).read(any()); + else if (boundary.equals("world")) doThrow(failure).when(fixture.world).read(any()); + else + doThrow(failure) + .when(fixture.publishedPolicies) + .listPublishedRealmEntryPolicies(TENANT, VERSION); + var observed = readThroughAdapter(fixture.service, rosterRead); + assertThat(observed.status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observed.status.getDescription()) + .isEqualTo("Creation source dependency unavailable"); + assertThat(observed.value).isNull(); + assertThat(observed.completed).isFalse(); + } + } + } + } + } + + @Test + void actualUninitializedPolicyClientIsUnavailableAndKeepsItsCauseInsideTheService() + throws Exception { + try (var fixture = new Fixture()) { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain("controlled-gs.crt"); + tls.setPrivateKey("controlled-gs.key"); + tls.setCaCert("controlled-ca.crt"); + var channels = mock(GrpcChannelFactory.class); + try (var policy = + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), tls, channels, NAMESPACE)) { + var actual = + new GameSessionCharacterCreatePublicSourceService( + NAMESPACE, + fixture.routes, + fixture.catalogs, + fixture.admissions, + fixture.launches, + fixture.retention, + fixture.gameDesign, + fixture.world, + policy); + assertThatThrownBy(() -> actual.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + .class) + .hasCauseInstanceOf( + GameDesignPublishedRealmPolicyClient.UninitializedClientException.class); + var observed = readThroughAdapter(actual, true); + assertThat(observed.status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observed.status.getDescription()) + .isEqualTo("Creation source dependency unavailable"); + assertThat(observed.value).isNull(); + assertThat(observed.completed).isFalse(); + verifyNoInteractions(channels); + } + } + try (var fixture = new Fixture()) { + var transport = + Status.PERMISSION_DENIED.withDescription("private peer reason").asRuntimeException(); + doThrow(transport).when(fixture.gameDesign).read(any()); + assertThatThrownBy(() -> fixture.service.read(request())) + .isInstanceOf( + GameSessionCharacterCreatePublicSourceService.SourceDependencyUnavailableException + .class) + .hasCause(transport) + .hasMessage("Creation source dependency unavailable"); + } + } + + @Test + void localCallerRequestMissingSourceAndUndifferentiatedEvidenceErrorsKeepTheirClassifications() { + try (var fixture = new Fixture()) { + var adapter = + new GameSessionCharacterCreatePublicSourceGrpcService(fixture.service, NAMESPACE); + var invalid = + new SourceObserver< + net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse>(); + runAsSourcePeer( + "entity-management-service", + () -> + adapter.readPlayerCreatedRosterSource( + rosterRequest().toBuilder().setSchemaVersion(2).build(), invalid)); + assertThat(invalid.status.getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + var denied = + new SourceObserver< + net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse>(); + runAsSourcePeer( + "account-service", () -> adapter.readPlayerCreatedRosterSource(rosterRequest(), denied)); + assertThat(denied.status.getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(fixture.gameDesign, fixture.world, fixture.publishedPolicies); + } + try (var fixture = new Fixture()) { + when(fixture.retention.readByOriginalOperation(anyString(), anyString())) + .thenReturn(Optional.empty()); + assertThat(readThroughAdapter(fixture.service, true).status.getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + verifyNoInteractions(fixture.gameDesign, fixture.world, fixture.publishedPolicies); + } + // Common authored-core/World clients use plain IllegalStateException both for missing init + // and invalid evidence. Without a typed discriminator their existing classification stays. + for (boolean world : List.of(false, true)) { + try (var fixture = new Fixture()) { + var invalid = new IllegalStateException("undifferentiated client state or evidence error"); + if (world) doThrow(invalid).when(fixture.world).read(any()); + else doThrow(invalid).when(fixture.gameDesign).read(any()); + assertThat(readThroughAdapter(fixture.service, true).status.getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + } + try (var fixture = new Fixture()) { + doThrow( + new GameDesignPublishedRealmPolicyClient.InvalidResponseException( + "invalid policy evidence", null)) + .when(fixture.publishedPolicies) + .listPublishedRealmEntryPolicies(TENANT, VERSION); + assertThat(readThroughAdapter(fixture.service, true).status.getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + } + + private static SourceObserver readThroughAdapter( + GameSessionCharacterCreatePublicSourceService source, boolean rosterRead) { + var adapter = new GameSessionCharacterCreatePublicSourceGrpcService(source, NAMESPACE); + if (rosterRead) { + var observer = + new SourceObserver< + net.firedevops.firemud.gamesession.v1.ReadPlayerCreatedRosterSourceResponse>(); + runAsSourcePeer( + "entity-management-service", + () -> adapter.readPlayerCreatedRosterSource(rosterRequest(), observer)); + return observer; + } + var observer = + new SourceObserver< + net.firedevops.firemud.gamesession.v1.ReadCharacterCreatePublicSourceResponse>(); + runAsSourcePeer( + "account-service", () -> adapter.readCharacterCreatePublicSource(request(), observer)); + return observer; + } + + private static void runAsSourcePeer(String service, Runnable operation) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/" + service, NAMESPACE, service)) + .run(operation); + } + + private static final class SourceObserver implements StreamObserver { + private T value; + private Status status = Status.OK; + private boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable failure) { + status = Status.fromThrowable(failure); + } + + @Override + public void onCompleted() { + completed = true; + } + } + @Test void accountReadsDoNotCallTheRosterPublishedPolicyOwner() { try (var fixture = new Fixture()) { @@ -135,7 +329,7 @@ void entityRosterRejectsMissingOrChangedSealedPolicyAndOriginalSourceIdentity() try (var fixture = new Fixture()) { invalidate.accept(fixture); assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) - .isInstanceOf(RuntimeException.class); + .isInstanceOfAny(StatusRuntimeException.class, IllegalArgumentException.class); } } } From 79c78c5aeb363b320ec98d8d6f35eb0c09b3df3c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:46:13 +1300 Subject: [PATCH 06/14] Record qualified public creation source review corrections --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 b5a46e5d5f..9226bb136d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### 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. + Current qualification at `d84249ff6ac7d18212c98de3f3bd35e522e1ad83` includes the actual published #3294 parent `a277d3758ad2eb113b69479e68ae6a1945d503c5`. R65 freshly passed 1,001 Common and 377 Entity unit cases plus 32 selected Entity PostgreSQL cases; those unchanged-source results retain their original attribution. After the final parent correction, R69 freshly passes 2,524 Game Session unit cases, 49 selected PostgreSQL cases, affected formatting and static analysis, links and Markdown. Fourteen cross-service cases pass in R69; all 22 Communication cases initially fail with the same refused PostgreSQL endpoint, then freshly pass in R70 without code changes. The transient refusal cause remains unproven. R57 rebuilds fresh service images at this reconciled checkpoint 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. These are controlled source/storage and isolated backend proofs; the genuine custody, created-roster consumer, registration, public admission and activation gaps below remain open. The local candidate prepares the unregistered Game Session public-target discovery and full creation-source reads, plus the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). From 8f80c324745a7f2fa9a0f3025fd796dac3a64710 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:19:19 +1300 Subject: [PATCH 07/14] Separate invalid created-roster source evidence from caller faults --- ...EntityPlayerCreatedRosterSourceClient.java | 19 +++++ ...ayerCreatedRosterSourceClientMtlsTest.java | 77 ++++++++++++++++++- 2 files changed, 93 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 d46f84d686..e682b72331 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 @@ -7,6 +7,7 @@ import com.google.protobuf.UnknownFieldSet; 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.NettyServerBuilder; @@ -66,6 +67,7 @@ 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.InvalidOwnerEvidenceException; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; @@ -183,7 +185,10 @@ endpoints, new CommonGrpcClientProperties(), channels, NAMESPACE)) pki.clientProperties(directory, pki.identity("entity")), channels, "Other")) - .isInstanceOf(RuntimeException.class); + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT)); } @Test @@ -244,7 +249,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.received).isEmpty(); } @@ -486,7 +496,9 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws good.toBuilder().setUnknownFields(unknown()).build())) { owner.response.set(changed); assertThatThrownBy(() -> client.read(fixture.request())) - .isInstanceOf(RuntimeException.class); + .isInstanceOfSatisfying( + InvalidOwnerEvidenceException.class, + failure -> assertThat(failure.getCause()).isNotNull()); } assertThat(owner.received).isNotEmpty().allMatch(fixture.request()::equals); owner.response.set(good); @@ -494,6 +506,57 @@ void changedEchoTargetsProvenanceClosedBodiesAndInactiveWorldFailClosed() throws } } + @Test + void authenticatedMalformedOwnerResponseKeepsGuardAndCodecCausesDistinctFromCallerInput() + throws Exception { + try (var owner = owner("server"); + var client = client(owner)) { + client.init(); + owner.response.set(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.response.set( + fixture.response().toBuilder() + .setWorldLifecycleEvidence(ByteString.copyFromUtf8("not-json-world-evidence")) + .build()); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOf(InvalidOwnerEvidenceException.class) + .hasCauseInstanceOf(IllegalArgumentException.class); + assertThat(owner.received).containsExactly(fixture.request(), fixture.request()); + owner.response.set(fixture.response()); + assertThat(client.read(fixture.request()).response()).isEqualTo(fixture.response()); + } + } + + @Test + void authenticatedOutboundFailuresKeepTheirExactTransportStatus() throws Exception { + for (var status : + List.of(Status.UNAVAILABLE, Status.FAILED_PRECONDITION, Status.INVALID_ARGUMENT)) { + var outbound = status.withDescription("controlled source owner transport failure"); + try (var owner = owner("server", outbound.asRuntimeException()); + var client = client(owner)) { + client.init(); + assertThatThrownBy(() -> client.read(fixture.request())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()).isEqualTo(outbound.getCode()); + assertThat(failure.getStatus().getDescription()) + .isEqualTo(outbound.getDescription()); + }); + assertThat(owner.received).containsExactly(fixture.request()); + } + } + } + @Test void inboundTransportRejectsResponseBeyond32MiBBeforeSourceDecoding() throws Exception { try (var owner = owner("server"); @@ -532,6 +595,10 @@ private static EntityPlayerCreatedRosterSourceClient client(Owner owner) throws } private static Owner owner(String name) throws Exception { + return owner(name, null); + } + + private static Owner owner(String name, StatusRuntimeException outboundFailure) throws Exception { var response = new AtomicReference<>(fixture.response()); var received = new CopyOnWriteArrayList(); var observedPeer = new AtomicReference(); @@ -554,6 +621,10 @@ public void readPlayerCreatedRosterSource( StreamObserver observer) { observedPeer.set(GrpcPeerIdentity.current().uri()); received.add(request); + if (outboundFailure != null) { + observer.onError(outboundFailure); + return; + } observer.onNext(response.get()); observer.onCompleted(); } From 5cdb2224f95cfc248a26b6c77de3d8425ede5bf2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:32:18 +1300 Subject: [PATCH 08/14] Align creation protection bounds and canonical source slugs --- .../player-access-and-session.md | 6 +- .../EntityCharacterCreateBindings.java | 7 +- ...tyCharacterCreateProtectionBoundsTest.java | 124 ++++++++++++++++++ ...ionCharacterCreatePublicSourceService.java | 4 +- ...haracterCreatePublicSourceServiceTest.java | 37 ++++++ 5 files changed, 172 insertions(+), 6 deletions(-) create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java 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..332bbc6d96 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,9 +8,11 @@ This is a non-normative implementation tracker for player access and session. Ca ### 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. +The latest source-client correction at `8f80c324745a7f2fa9a0f3025fd796dac3a64710` separates malformed authenticated owner evidence from caller input and outbound transport failures, retaining the original validation cause. R89 freshly passes all 379 Entity unit cases and 70 PostgreSQL cases with affected static analysis, formatting and documentation checks. Actual loopback mTLS covers malformed owner guards and codecs, caller rejection before RPC, unchanged owner transport statuses and recovery to a valid response. R91 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These controlled results do not establish genuine source custody, a created-roster consumer, runtime registration, public admission or activation. -Current qualification at `d84249ff6ac7d18212c98de3f3bd35e522e1ad83` includes the actual published #3294 parent `a277d3758ad2eb113b69479e68ae6a1945d503c5`. R65 freshly passed 1,001 Common and 377 Entity unit cases plus 32 selected Entity PostgreSQL cases; those unchanged-source results retain their original attribution. After the final parent correction, R69 freshly passes 2,524 Game Session unit cases, 49 selected PostgreSQL cases, affected formatting and static analysis, links and Markdown. Fourteen cross-service cases pass in R69; all 22 Communication cases initially fail with the same refused PostgreSQL endpoint, then freshly pass in R70 without code changes. The transient refusal cause remains unproven. R57 rebuilds fresh service images at this reconciled checkpoint 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. These are controlled source/storage and isolated backend proofs; the genuine custody, created-roster consumer, registration, public admission and activation gaps below remain open. +The preceding 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. + +The underlying source qualification at `d84249ff6ac7d18212c98de3f3bd35e522e1ad83` includes the actual published #3294 parent `a277d3758ad2eb113b69479e68ae6a1945d503c5`. R65 freshly passed 1,001 Common and 377 Entity unit cases plus 32 selected Entity PostgreSQL cases; those unchanged-source results retain their original attribution. After the final parent correction, R69 freshly passes 2,524 Game Session unit cases, 49 selected PostgreSQL cases, affected formatting and static analysis, links and Markdown. Fourteen cross-service cases pass in R69; all 22 Communication cases initially fail with the same refused PostgreSQL endpoint, then freshly pass in R70 without code changes. The transient refusal cause remains unproven. R57 rebuilds fresh service images at this reconciled checkpoint 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. These are controlled source/storage and isolated backend proofs; the genuine custody, created-roster consumer, registration, public admission and activation gaps below remain open. The local candidate prepares the unregistered Game Session public-target discovery and full creation-source reads, plus the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindings.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindings.java index f91c6c712d..fdb51d0b93 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindings.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindings.java @@ -85,7 +85,8 @@ public static void requireAccountProtection( ReadOriginalCharacterCreateResponse original, ReadOriginalCharacterCreateProtectionResponse protection) { requireBound(protection, MAX_ACCOUNT_RESPONSE_BYTES); - if (!protection.hasOriginal() + if (original == null + || !protection.hasOriginal() || !original.equals(protection.getOriginal()) || !request .getAccountProtection() @@ -94,7 +95,9 @@ public static void requireAccountProtection( || request.getAccountProtection().getProtectionFence() != protection.getAccountProtectionFence() || protection.getOriginalMembershipSnapshot().isEmpty() - || protection.getOriginalEntitlementSnapshot().isEmpty()) throw invalid(); + || protection.getOriginalMembershipSnapshot().size() > 1024 * 1024 + || protection.getOriginalEntitlementSnapshot().isEmpty() + || protection.getOriginalEntitlementSnapshot().size() > 1024 * 1024) throw invalid(); instant(protection.getAcquiredAt()); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java new file mode 100644 index 0000000000..58ae5c4303 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java @@ -0,0 +1,124 @@ +package net.firedevops.firemud.entitymanagement.charactercreate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.List; +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.entitymanagement.v1.CharacterCreateProtectionReference; +import net.firedevops.firemud.entitymanagement.v1.CommitProtectedCharacterCreateRequest; +import org.junit.jupiter.api.Test; + +/** + * Controlled value checks for the Account protection receiver only. The original is a stipulated + * comparison value, not authenticated Account authority or independently validated creation intent. + */ +class EntityCharacterCreateProtectionBoundsTest { + private static final ByteString ONE_MEBIBYTE = ByteString.copyFrom(new byte[1024 * 1024]); + private static final ReadOriginalCharacterCreateResponse ORIGINAL = + ReadOriginalCharacterCreateResponse.newBuilder() + .setTargetNamespace("test") + .setOperationId(uuid(1)) + .setMutationDigest("a".repeat(64)) + .build(); + private static final CommitProtectedCharacterCreateRequest REQUEST = + CommitProtectedCharacterCreateRequest.newBuilder() + .setOriginal( + ReadOriginalCharacterCreateRequest.newBuilder() + .setTargetNamespace("test") + .setOperationId(uuid(1)) + .setMutationDigest("a".repeat(64))) + .setAccountProtection(reference(2)) + .setGameSessionProtection(reference(3)) + .setWorldProtection(reference(4)) + .build(); + + @Test + void eachExactOneMebibyteSnapshotIsAccepted() { + assertThatCode( + () -> + EntityCharacterCreateBindings.requireAccountProtection( + REQUEST, ORIGINAL, protection())) + .doesNotThrowAnyException(); + } + + @Test + void eachSnapshotIndependentlyRejectsOneByteBeyondOneMebibyte() { + var oversized = ONE_MEBIBYTE.concat(ByteString.copyFrom(new byte[] {1})); + for (var changed : + List.of( + protection().toBuilder().setOriginalMembershipSnapshot(oversized).build(), + protection().toBuilder().setOriginalEntitlementSnapshot(oversized).build())) { + assertInvalid( + () -> EntityCharacterCreateBindings.requireAccountProtection(REQUEST, ORIGINAL, changed)); + } + } + + @Test + void nullOriginalIsInvalidArgumentRatherThanANullDereference() { + assertInvalid( + () -> EntityCharacterCreateBindings.requireAccountProtection(REQUEST, null, protection())); + } + + @Test + void exactOriginalProtectionEmptySnapshotsAndAcquisitionGuardsRemainRequired() { + for (var changed : + List.of( + protection().toBuilder().clearOriginal().build(), + protection().toBuilder() + .setOriginal(ORIGINAL.toBuilder().setOperationId(uuid(9))) + .build(), + protection().toBuilder().setAccountProtectionId(uuid(9)).build(), + protection().toBuilder().setAccountProtectionFence(8).build(), + protection().toBuilder().clearOriginalMembershipSnapshot().build(), + protection().toBuilder().clearOriginalEntitlementSnapshot().build(), + protection().toBuilder().setAcquiredAt("not-an-instant").build(), + protection().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertInvalid( + () -> EntityCharacterCreateBindings.requireAccountProtection(REQUEST, ORIGINAL, changed)); + } + } + + private static ReadOriginalCharacterCreateProtectionResponse protection() { + return ReadOriginalCharacterCreateProtectionResponse.newBuilder() + .setOriginal(ORIGINAL) + .setAccountProtectionId(REQUEST.getAccountProtection().getProtectionId()) + .setAccountProtectionFence(REQUEST.getAccountProtection().getProtectionFence()) + .setAcquiredAt("2026-10-24T00:00:00Z") + .setOriginalMembershipSnapshot(ONE_MEBIBYTE) + .setOriginalEntitlementSnapshot(ONE_MEBIBYTE) + .build(); + } + + private static CharacterCreateProtectionReference reference(int value) { + return CharacterCreateProtectionReference.newBuilder() + .setProtectionId(uuid(value)) + .setProtectionFence(7) + .build(); + } + + private static String uuid(int value) { + return new UUID(0L, value).toString(); + } + + private static void assertInvalid(Runnable validation) { + assertThatThrownBy(validation::run) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT)); + } +} 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..4c4c91065d 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 @@ -620,8 +620,8 @@ static void requireRequest(ReadCharacterCreatePublicSourceRequest request, Strin || request.getSchemaVersion() != 1 || !namespace.equals(request.getTargetNamespace()) || !"SHARED".equals(request.getPlayableStateScope()) - || !request.getWorldSlug().matches("[a-z0-9]+(?:-[a-z0-9]+)*") - || !request.getRealmSlug().matches("[a-z0-9]+(?:-[a-z0-9]+)*") + || !RealmEntryPolicy.isCanonicalSlug(request.getWorldSlug()) + || !RealmEntryPolicy.isCanonicalSlug(request.getRealmSlug()) || request.getCatalogRevision() <= 0 || request.getPointerVersion() <= 0) throw invalid(); for (String id : 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..14ff32998b 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 @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.charactercreate; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -706,6 +707,42 @@ void rejectsWorldNonActiveAndChangedCurrentTargetAfterRemoteReads() { } } + @Test + void accountSourceRejectsOverlengthSlugsBeforeReadingAnyOwner() { + String overlength = "a".repeat(RealmEntryPolicy.MAX_SLUG_LENGTH + 1); + for (var invalid : + List.of( + request().toBuilder().setWorldSlug(overlength).build(), + request().toBuilder().setRealmSlug(overlength).build())) { + try (var fixture = new Fixture()) { + assertThatThrownBy(() -> fixture.service.read(invalid)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); + verifyNoInteractions( + fixture.routes, + fixture.catalogs, + fixture.admissions, + fixture.launches, + fixture.retention, + fixture.gameDesign, + fixture.world, + fixture.publishedPolicies); + } + } + } + + @Test + void accountSourceRequestValidationAcceptsMaximumCanonicalSlugs() { + String maximum = "a".repeat(RealmEntryPolicy.MAX_SLUG_LENGTH); + var bounded = request().toBuilder().setWorldSlug(maximum).setRealmSlug(maximum).build(); + assertThatCode( + () -> GameSessionCharacterCreatePublicSourceService.requireRequest(bounded, NAMESPACE)) + .doesNotThrowAnyException(); + } + @Test void rejectsAmbientTransactionBeforeReadingAnyOwner() { try (var fixture = new Fixture()) { From 5297c88ffcf9126454029b7749d5943c7df954b1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:36:59 +1300 Subject: [PATCH 09/14] Record qualified combined creation source review fixes --- .../implementation-tracking/player-access-and-session.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 332bbc6d96..d949146b32 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Public character-creation and created-roster source preparation -The latest source-client correction at `8f80c324745a7f2fa9a0f3025fd796dac3a64710` separates malformed authenticated owner evidence from caller input and outbound transport failures, retaining the original validation cause. R89 freshly passes all 379 Entity unit cases and 70 PostgreSQL cases with affected static analysis, formatting and documentation checks. Actual loopback mTLS covers malformed owner guards and codecs, caller rejection before RPC, unchanged owner transport statuses and recovery to a valid response. R91 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These controlled results do not establish genuine source custody, a created-roster consumer, runtime registration, public admission or activation. +The latest combined review correction at `5cdb2224f95cfc248a26b6c77de3d8425ede5bf2` retains the typed source-client classification below, rejects null Account originals and oversized individual membership or entitlement snapshots, and applies the canonical slug grammar before Account-source owner reads. R92 freshly passes 383 Entity unit cases, 70 Entity PostgreSQL cases and 2,530 Game Session unit cases with affected static analysis, formatting and documentation checks. The new cases cover each exact 1 MiB snapshot limit, each one-byte overflow, null-original classification, 65-character slug rejection before any owner read and exact-64 request acceptance. R94 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. Earlier Common, Game Session PostgreSQL and cross-service results retain their independently attributed executions. These are controlled component and isolated runtime proofs, without genuine source custody, created-roster consumption, runtime registration, successful public admission or activation. + +The preceding source-client correction at `8f80c324745a7f2fa9a0f3025fd796dac3a64710` separates malformed authenticated owner evidence from caller input and outbound transport failures, retaining the original validation cause. R89 freshly passes all 379 Entity unit cases and 70 PostgreSQL cases with affected static analysis, formatting and documentation checks. Actual loopback mTLS covers malformed owner guards and codecs, caller rejection before RPC, unchanged owner transport statuses and recovery to a valid response. R91 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These controlled results do not establish genuine source custody, a created-roster consumer, runtime registration, public admission or activation. The preceding 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. From 2aa25d9327bd9c15698c69168f2c96254f0fa732 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:48:31 +1300 Subject: [PATCH 10/14] Clarify creation source API and current qualification --- .../game-session-service/api-contracts.md | 8 ++++---- .../player-access-and-session.md | 16 +++------------- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index f1ec218201..512a9c5e54 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -76,13 +76,13 @@ The fresh canonical Human admission path also refuses preparation, commit and ab ### Public character-creation source read -The Entity-only roster response additionally carries the complete canonical sealed policy set from Game Design's [published realm-entry policy owner read](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read). Game Session independently reads and validates that set against the original authored association, full immutable release content and World launch, then requires exactly one matching schema-three `PLAYER_CREATED` policy with the same canonical policy, descriptor and source revision as the authored projection. Its owner-issued policy identity and `policyDigest` remain distinct from projection binding identities and content digests. The policy read occurs before final local and historical source revalidation; Account's two methods do not perform this additional RPC or carry the set. +The unregistered `CharacterCreatePublicSourceService.ReadCharacterCreatePublicSource` is a pre-intent source read for the exact same-namespace Account mTLS workload, without bearer or end-user-context substitutes. Its [closed protobuf contract](../../../../protos/game-session/v1/character_create_public_source_service.proto) accepts only expected canonical discovery selectors and echoes them exactly; those selectors establish no Account authentication or issued-scope authority. The initial supported source is visible public-production `SHARED` with `PLAYER_CREATED`, a current canonical `OPEN` pointer, an existing retained original authored-core source, and an independently read matching World `ACTIVE` lifecycle. The composition rereads the original Game Design source through the existing exact-replay codec and compares the complete retained bytes and digest, verifies the immutable historical StartSession association without renewing or reacquiring its claim, then rechecks the full local route, catalog, pointer, launch and retained source after remote reads. Its complete pointer source includes the actual pointer row's `updatedAt`, never a substituted terminal timestamp. Missing, conflicting, replaced, fixture-only or unsupported owner evidence fails closed. The request is bounded to 16 KiB and the complete response to 32 MiB, retaining the existing authored-source codec's 16 MiB wire and 8 MiB canonical-result bounds; downstream Account persistence and terminal budgets require separate qualification and must not truncate this source to fit. Registration remains absent; the adapter checks the closed request bound before owner work. This API constructs no Account action, acquires no protection, allocates no actor and establishes no admission or activation authority. -The same unregistered service exposes a distinct `ReadPlayerCreatedRosterSource` read to the exact same-namespace Entity Management workload certificate, rejecting Account callers, foreign namespaces and authenticated caller context; bearer credentials cannot substitute for the required certificate. Its closed selectors pin canonical tenant, realm, shared playable namespace, runtime instance, catalog and pointer revisions, expected canonical content version and active World epoch, without Account scope or evaluation/expiry timestamps. It preserves the existing original authored-source, historical launch and independent World `ACTIVE` readback composition, including full owner bytes and rereads of current local and historical source facts; expected version and epoch must still match after remote reads. The request is bounded to 16 KiB and the response to 32 MiB. Account's discovery and creation-source methods remain Account-only. This supplies current published `PLAYER_CREATED` policy and descriptor input for Entity's [actor-entry boundary](../entity-management-service/api-contracts.md#character-creation-owner-protection) under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md); it grants no roster assignment, Account authority, protection, activation or admission and does not widen the separate `PRESEEDED_ONLY` owner-read or assignment authority. +The unregistered Entity-only `ReadPlayerCreatedRosterSource` read is exposed to the exact same-namespace Entity Management workload certificate, rejecting Account callers, foreign namespaces and authenticated caller context; bearer credentials cannot substitute for the required certificate. Its closed selectors pin canonical tenant, realm, shared playable namespace, runtime instance, catalog and pointer revisions, expected canonical content version and active World epoch, without Account scope or evaluation/expiry timestamps. It preserves the existing original authored-source, historical launch and independent World `ACTIVE` readback composition, including full owner bytes and rereads of current local and historical source facts; expected version and epoch must still match after remote reads. The request is bounded to 16 KiB and the response to 32 MiB. Account's discovery and creation-source methods remain Account-only. This supplies current published `PLAYER_CREATED` policy and descriptor input for Entity's [actor-entry boundary](../entity-management-service/api-contracts.md#character-creation-owner-protection) under [ADR 0140](../../decisions/adr-0140-realm-authored-controllable-actor-entry.md); it grants no roster assignment, Account authority, protection, activation or admission and does not widen the separate `PRESEEDED_ONLY` owner-read or assignment authority. -The same unregistered Account-only workload family exposes `ResolveCharacterCreatePublicTarget` before scope issuance. Its closed request contains only schema version, read-request UUID, workload namespace and friendly world/realm slugs. Game Session resolves exactly one match through its actual canonical visible public-production route owner, requires `SHARED` and `PLAYER_CREATED`, and rereads the complete current route, catalog and `OPEN` pointer before returning their typed canonical identifiers, metadata, revisions, canonical content version, active epoch and actual pointer timestamp. Unknown, ambiguous, unsupported or changed targets fail closed. The response is bounded to 64 KiB, echoes the original request and contains no Account-issued scope, evaluation time, expiry, creation intent or membership authority. Account must independently authenticate bootstrap identity and issue its own canonical scope; friendly selectors and target discovery do not supply that authority. The request has the same 16 KiB bound and exact peer requirement as the source read below. +The Entity-only roster response additionally carries the complete canonical sealed policy set from Game Design's [published realm-entry policy owner read](../game-design-service/api-contracts.md#published-realm-entry-policy-owner-read). Game Session independently reads and validates that set against the original authored association, full immutable release content and World launch, then requires exactly one matching schema-three `PLAYER_CREATED` policy with the same canonical policy, descriptor and source revision as the authored projection. Its owner-issued policy identity and `policyDigest` remain distinct from projection binding identities and content digests. The policy read occurs before final local and historical source revalidation; Account's two methods do not perform this additional RPC or carry the set. -The unregistered `CharacterCreatePublicSourceService.ReadCharacterCreatePublicSource` is a pre-intent source read for the exact same-namespace Account mTLS workload, without bearer or end-user-context substitutes. Its [closed protobuf contract](../../../../protos/game-session/v1/character_create_public_source_service.proto) accepts only expected canonical discovery selectors and echoes them exactly; those selectors establish no Account authentication or issued-scope authority. The initial supported source is visible public-production `SHARED` with `PLAYER_CREATED`, a current canonical `OPEN` pointer, an existing retained original authored-core source, and an independently read matching World `ACTIVE` lifecycle. The composition rereads the original Game Design source through the existing exact-replay codec and compares the complete retained bytes and digest, verifies the immutable historical StartSession association without renewing or reacquiring its claim, then rechecks the full local route, catalog, pointer, launch and retained source after remote reads. Its complete pointer source includes the actual pointer row's `updatedAt`, never a substituted terminal timestamp. Missing, conflicting, replaced, fixture-only or unsupported owner evidence fails closed. The request is bounded to 16 KiB and the complete response to 32 MiB, retaining the existing authored-source codec's 16 MiB wire and 8 MiB canonical-result bounds; downstream Account persistence and terminal budgets require separate qualification and must not truncate this source to fit. Registration remains absent; the adapter checks the closed request bound before owner work. This API constructs no Account action, acquires no protection, allocates no actor and establishes no admission or activation authority. +The same unregistered Account-only workload family exposes `ResolveCharacterCreatePublicTarget` before scope issuance. Its closed request contains only schema version, read-request UUID, workload namespace and friendly world/realm slugs. Game Session resolves exactly one match through its actual canonical visible public-production route owner, requires `SHARED` and `PLAYER_CREATED`, and rereads the complete current route, catalog and `OPEN` pointer before returning their typed canonical identifiers, metadata, revisions, canonical content version, active epoch and actual pointer timestamp. Unknown, ambiguous, unsupported or changed targets fail closed. The response is bounded to 64 KiB, echoes the original request and contains no Account-issued scope, evaluation time, expiry, creation intent or membership authority. Account must independently authenticate bootstrap identity and issue its own canonical scope; friendly selectors and target discovery do not supply that authority. The request has the same 16 KiB bound and exact peer requirement as the Account source read above. ### Canonical gameplay roster owner reads 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 d949146b32..93b46e76ea 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,21 +8,11 @@ This is a non-normative implementation tracker for player access and session. Ca ### Public character-creation and created-roster source preparation -The latest combined review correction at `5cdb2224f95cfc248a26b6c77de3d8425ede5bf2` retains the typed source-client classification below, rejects null Account originals and oversized individual membership or entitlement snapshots, and applies the canonical slug grammar before Account-source owner reads. R92 freshly passes 383 Entity unit cases, 70 Entity PostgreSQL cases and 2,530 Game Session unit cases with affected static analysis, formatting and documentation checks. The new cases cover each exact 1 MiB snapshot limit, each one-byte overflow, null-original classification, 65-character slug rejection before any owner read and exact-64 request acceptance. R94 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. Earlier Common, Game Session PostgreSQL and cross-service results retain their independently attributed executions. These are controlled component and isolated runtime proofs, without genuine source custody, created-roster consumption, runtime registration, successful public admission or activation. +The latest combined review correction at `5cdb2224f95cfc248a26b6c77de3d8425ede5bf2` preserves distinct source-client classifications for malformed caller input, invalid authenticated owner evidence and outbound transport failures, retaining the original validation cause. It rejects null Account originals and oversized individual membership or entitlement snapshots, and applies the canonical slug grammar before Account-source owner reads. R92 freshly passes 383 Entity unit cases, 70 Entity PostgreSQL cases and 2,530 Game Session unit cases with affected static analysis, formatting and documentation checks. The new cases cover each exact 1 MiB snapshot limit, each one-byte overflow, null-original classification, 65-character slug rejection before any owner read and exact-64 request acceptance. R94 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These are controlled component and isolated runtime proofs, without genuine source custody, created-roster consumption, runtime registration, successful public admission or activation. -The preceding source-client correction at `8f80c324745a7f2fa9a0f3025fd796dac3a64710` separates malformed authenticated owner evidence from caller input and outbound transport failures, retaining the original validation cause. R89 freshly passes all 379 Entity unit cases and 70 PostgreSQL cases with affected static analysis, formatting and documentation checks. Actual loopback mTLS covers malformed owner guards and codecs, caller rejection before RPC, unchanged owner transport statuses and recovery to a valid response. R91 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These controlled results do not establish genuine source custody, a created-roster consumer, runtime registration, public admission or activation. +Unchanged Common proof remains 1,001 cases from R65; R69 passed 49 Game Session PostgreSQL and 14 cross-service cases, while all 22 Communication cases first failed on the same PostgreSQL connection refusal in R69 and passed unchanged in R70 (cause unproven). None of these earlier results was freshly rerun in R92. -The preceding 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. - -The underlying source qualification at `d84249ff6ac7d18212c98de3f3bd35e522e1ad83` includes the actual published #3294 parent `a277d3758ad2eb113b69479e68ae6a1945d503c5`. R65 freshly passed 1,001 Common and 377 Entity unit cases plus 32 selected Entity PostgreSQL cases; those unchanged-source results retain their original attribution. After the final parent correction, R69 freshly passes 2,524 Game Session unit cases, 49 selected PostgreSQL cases, affected formatting and static analysis, links and Markdown. Fourteen cross-service cases pass in R69; all 22 Communication cases initially fail with the same refused PostgreSQL endpoint, then freshly pass in R70 without code changes. The transient refusal cause remains unproven. R57 rebuilds fresh service images at this reconciled checkpoint 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. These are controlled source/storage and isolated backend proofs; the genuine custody, created-roster consumer, registration, public admission and activation gaps below remain open. - -The local candidate prepares the unregistered Game Session public-target discovery and full creation-source reads, plus the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). - -Historical qualification follows for the earlier `a18dab712f` and `0ad0a0be` checkpoints; it does not replace the current qualification above. - -At local source `a18dab712f`, independent qualification against the published roster-retention parent passes in 3m53s: 32 Common cases, seven Entity source-client socket cases, 35 Game Session source/policy-client cases and one actual-pointer PostgreSQL case, with zero failures, errors or skips. Affected Main, Test, Integration Test and Common test-fixture static analysis, formatting and documentation checks pass. The pointer case uses real current readers, row locks and the stored timestamp over controlled retained pre1006 history. The source and socket fixtures control upstream publication, lifecycle and owner facts; they do not prove genuine production source custody, created-actor roster/selection, runtime registration, protected activation or a playable journey. Earlier mixed-source proof retains its original attribution. The broader UUID runtime and CHARACTER_CREATE owners remain separate unfinished receiving work. - -After carrying the published roster-retention correction `2c266493a1aa7c048abe9e72f296941d443e0e00`, source checkpoint `0ad0a0beaf6218a0f5bd7d49266e341d9210194c` keeps the same 22-path prerequisite boundary. R4 passes in 5m01s: 32 Common, 354 Entity and 2,505 Game Session unit cases plus 22 selected Entity and 20 selected Game Session PostgreSQL cases, all with zero failures, errors or skips. Affected service static analysis, formatting and documentation checks pass. The existing Common test-fixture static proof retains its earlier attribution. These are source and controlled composition results, preserving the genuine custody, created-roster consumer, admission and activation limits above. +Game Session prepares the unregistered public-target discovery and full creation-source reads, alongside the distinct Entity-only created-roster source read and its authenticated Entity client. The source preserves the complete original authored evidence and independently read World lifecycle; the Entity branch additionally validates Game Design’s complete sealed policy set and exact schema-three creation descriptor before final source revalidation. The current pointer source uses its actual stored timestamp. These readers acquire no owner protection, allocate no actor and grant no admission. Canonical contracts remain in the [Game Session API](../../architecture/microservices/game-session-service/api-contracts.md#public-character-creation-source-read) and [Entity API](../../architecture/microservices/entity-management-service/api-contracts.md#implementation-status). Genuine source custody, created-roster consumption, runtime registration, successful public admission and activation remain future gaps, as do the broader UUID runtime and CHARACTER_CREATE owners. ### Retained Draft authorization fence migrations From ee9482ca8debfa7c5cf881b3aced2213bcb6504e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:05:03 +1300 Subject: [PATCH 11/14] Align Game Session immutable release evidence with Entity validation --- ...ionCharacterCreatePublicSourceService.java | 32 ++++- ...haracterCreatePublicSourceServiceTest.java | 118 ++++++++++++++++++ 2 files changed, 149 insertions(+), 1 deletion(-) 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 4c4c91065d..f5b30557b3 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 @@ -12,6 +12,7 @@ import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; import net.firedevops.firemud.common.gamesession.CanonicalGameInstanceLaunchAssociationReadEvidence; @@ -329,10 +330,11 @@ private PublishedRealmEntryPolicySetEvidence readPublishedPolicies( var terminal = GameDesignPublicationTerminalEvidence.fromStored(set.terminalEvidenceBytes()); var association = authored.associationRead().association(); var bundle = authored.associationRead().releaseBundle(); + var associationWorld = authored.associationRead().worldPublishedStartLocationEvidence(); var worldRelease = lifecycle.launchBinding().releaseAttestation(); var sourceRelease = net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence - .releaseContent(bundle, worldRelease.worldStartLocationEvidence()); + .releaseContent(bundle, associationWorld); if (!namespace.equals(operation.world().request().targetNamespace()) || !route.canonicalTenantId().equals(set.target().canonicalTenantId()) || !route.canonicalVersionId().equals(set.target().canonicalVersionId()) @@ -348,6 +350,34 @@ private PublishedRealmEntryPolicySetEvidence readPublishedPolicies( sourceRelease.canonicalBytes(), terminal.releaseContent().canonicalBytes()) || !set.manifestHash().equals(bundle.getManifestHash()) || !set.manifestHash().equals(worldRelease.manifestHash()) + || sourceRelease.manifestSchemaVersion() != worldRelease.manifestSchemaVersion() + || !sourceRelease.artifactDigests().equals(worldRelease.artifactDigests()) + || !sourceRelease + .requiredManifestAssetKeys() + .equals(worldRelease.requiredManifestAssetKeys()) + || !sourceRelease.commandDefinitions().equals(worldRelease.commandDefinitions()) + || !sourceRelease.generationConfigRevision().equals(worldRelease.generationConfigRevision()) + || !sourceRelease.participantDigests().stream() + .map( + value -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId() != null, + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + value.digestSchemaVersion(), + value.abilitySchemaDigest() != null, + value.abilitySchemaDigest())) + .toList() + .equals(worldRelease.participantDigests()) + || !Arrays.equals( + associationWorld.canonicalBytes(), + worldRelease.worldStartLocationEvidence().canonicalBytes()) + || !Arrays.equals( + worldRelease.worldStartLocationEvidence().canonicalBytes(), + operation.world().canonicalBytes()) || set.versionNumber() != bundle.getVersionNumber()) throw missing(); var projections = authored.projections().stream() 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 14ff32998b..714b1e2de5 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 @@ -27,6 +27,7 @@ import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadGrpcCodec; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence; import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadGrpcCodec; @@ -40,6 +41,9 @@ import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.ReadAuthoredInitialActorCoreResponse; import net.firedevops.firemud.gamedesign.v1.ReadStartSessionTemplateAssociationRequest; @@ -335,6 +339,35 @@ void entityRosterRejectsMissingOrChangedSealedPolicyAndOriginalSourceIdentity() } } + @Test + void entityRosterRejectsIndependentlyChangedWorldSelectorsAndImmutableReleaseFields() { + List> invalidations = + List.of( + fixture -> when(fixture.associationWorld.canonicalBytes()).thenReturn(new byte[] {10}), + fixture -> when(fixture.releaseWorld.canonicalBytes()).thenReturn(new byte[] {11}), + fixture -> + when(fixture.publicationOperation.world().canonicalBytes()) + .thenReturn(new byte[] {12}), + fixture -> when(fixture.worldRelease.manifestSchemaVersion()).thenReturn(2), + fixture -> when(fixture.worldRelease.artifactDigests()).thenReturn(List.of()), + fixture -> when(fixture.worldRelease.requiredManifestAssetKeys()).thenReturn(List.of()), + fixture -> + when(fixture.worldRelease.commandDefinitions()).thenReturn(List.of("changed")), + fixture -> when(fixture.worldRelease.generationConfigRevision()).thenReturn("changed"), + fixture -> when(fixture.worldRelease.participantDigests()).thenReturn(List.of())); + for (var invalidate : invalidations) { + try (var fixture = new Fixture()) { + invalidate.accept(fixture); + assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + } + } + } + @Test void finalTargetRereadOccursAfterTheAdditionalPublishedPolicyOwnerCall() { try (var fixture = new Fixture()) { @@ -818,6 +851,12 @@ private static final class Fixture implements AutoCloseable { mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); final WorldCanonicalInstanceLifecycleEvidence lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); + final AuthoredWorldReleaseAttestationEvidence worldRelease = + mock(AuthoredWorldReleaseAttestationEvidence.class); + final WorldPublishedStartLocationEvidence associationWorld = + mock(WorldPublishedStartLocationEvidence.class); + final WorldPublishedStartLocationEvidence releaseWorld = + mock(WorldPublishedStartLocationEvidence.class); private org.mockito.MockedStatic associationCodec; private org.mockito.MockedStatic sourceCodec; private org.mockito.MockedStatic policyCodec; @@ -842,6 +881,34 @@ private static final class Fixture implements AutoCloseable { (value, context) -> { when(value.contentDigest()).thenReturn("sha256:" + "1".repeat(64)); when(value.canonicalBytes()).thenReturn(new byte[] {8}); + when(value.manifestSchemaVersion()) + .thenReturn((Integer) context.arguments().get(7)); + when(value.artifactDigests()) + .thenReturn( + ((List) context.arguments().get(8)) + .stream() + .map(AuthoredWorldReleaseAttestationEvidence.Artifact.class::cast) + .toList()); + when(value.requiredManifestAssetKeys()) + .thenReturn( + ((List) context.arguments().get(9)) + .stream().map(String.class::cast).toList()); + when(value.participantDigests()) + .thenReturn( + ((List) context.arguments().get(10)) + .stream() + .map( + GameDesignPublicationTerminalEvidence.Participant.class::cast) + .toList()); + when(value.commandDefinitions()) + .thenReturn( + ((List) context.arguments().get(11)) + .stream().map(String.class::cast).toList()); + when(value.generationConfigRevision()) + .thenReturn((String) context.arguments().get(12)); + when(value.worldStartLocationEvidence()) + .thenReturn( + (WorldPublishedStartLocationEvidence) context.arguments().get(13)); }); policyCodec.when(() -> RealmEntryPolicy.isCanonicalSlug(anyString())).thenCallRealMethod(); UUID sourceOperation = UUID.randomUUID(); @@ -851,6 +918,7 @@ private static final class Fixture implements AutoCloseable { byte[] account = new byte[] {2}; byte[] sourceBytes = "retained".getBytes(java.nio.charset.StandardCharsets.UTF_8); var launch = mock(CanonicalGameInstanceLaunchAssociation.class, RETURNS_DEEP_STUBS); + when(launch.launchBindingEvidence().releaseAttestation()).thenReturn(worldRelease); var proof = mock(CanonicalInitialAdmissionOwnerProof.class); when(proof.provesCommit()).thenReturn(true); when(proof.proofDigest()).thenReturn("sha256:" + "a".repeat(64)); @@ -1036,6 +1104,30 @@ private static final class Fixture implements AutoCloseable { when(projection.selectedCommitDigest()).thenReturn("sha256:" + "2".repeat(64)); var originalAssociationRead = historical.descriptorPin().associationRead(); when(authored.associationRead()).thenReturn(originalAssociationRead); + when(originalAssociationRead.worldPublishedStartLocationEvidence()) + .thenReturn(associationWorld); + when(associationWorld.canonicalBytes()).thenReturn(new byte[] {9}); + when(releaseWorld.canonicalBytes()).thenReturn(new byte[] {9}); + when(worldRelease.worldStartLocationEvidence()).thenReturn(releaseWorld); + var artifact = + new AuthoredWorldReleaseAttestationEvidence.Artifact( + "world", + "WORLD_MANIFEST", + "artifacts/sha256/" + "6".repeat(64), + "sha256:" + "6".repeat(64), + "application/json", + 1); + var participant = + new AuthoredWorldReleaseAttestationEvidence.Participant( + "world", + "PUBLIC", + false, + null, + commit.toString(), + "7".repeat(64), + 1, + true, + "sha256:" + "8".repeat(64)); when(authored.associationRead().releaseBundle()) .thenReturn( PublishedReleaseBundle.newBuilder() @@ -1049,7 +1141,32 @@ private static final class Fixture implements AutoCloseable { .setAttestationSchemaVersion("v2") .setManifestHash("sha256:" + "3".repeat(64)) .setManifestSchemaVersion(1) + .addRequiredManifestAssetKeys("world") + .addArtifactDigests( + PublishedArtifactDigest.newBuilder() + .setUsageKey(artifact.usageKey()) + .setArtifactKind(artifact.artifactKind()) + .setImmutableObjectKey(artifact.immutableObjectKey()) + .setContentDigest(artifact.contentDigest()) + .setContentType(artifact.contentType()) + .setArtifactSchemaVersion(artifact.artifactSchemaVersion())) + .addParticipantDigests( + ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()) + .setAbilitySchemaDigest(participant.abilitySchemaDigest())) + .addCommandDefinitions("look") + .setGenerationConfigRevision("generation-1") .build()); + when(worldRelease.manifestSchemaVersion()).thenReturn(1); + when(worldRelease.artifactDigests()).thenReturn(List.of(artifact)); + when(worldRelease.requiredManifestAssetKeys()).thenReturn(List.of("world")); + when(worldRelease.commandDefinitions()).thenReturn(List.of("look")); + when(worldRelease.generationConfigRevision()).thenReturn("generation-1"); + when(worldRelease.participantDigests()).thenReturn(List.of(participant)); when(launchBinding.releaseAttestation().publishedReleaseBundleRef()) .thenReturn("original-release"); when(launchBinding.releaseAttestation().publishWorkflowId()).thenReturn("publication"); @@ -1082,6 +1199,7 @@ private static final class Fixture implements AutoCloseable { .when(() -> GameDesignPublicationTerminalEvidence.fromStored(any())) .thenReturn(publicationTerminal); when(publicationOperation.world().request().targetNamespace()).thenReturn(NAMESPACE); + when(publicationOperation.world().canonicalBytes()).thenReturn(new byte[] {9}); when(publicationOperation.account().input().selection().selectedCommit().digest()) .thenReturn("sha256:" + "2".repeat(64)); when(publicationTerminal.publishedReleaseBundleDigest()) From cc33169ca1354872e101c4ef42777b0e79032473 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:10:25 +1300 Subject: [PATCH 12/14] Record complete release-evidence correction proof --- .../implementation-tracking/player-access-and-session.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 93b46e76ea..9ee4f8e282 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### Public character-creation and created-roster source preparation -The latest combined review correction at `5cdb2224f95cfc248a26b6c77de3d8425ede5bf2` preserves distinct source-client classifications for malformed caller input, invalid authenticated owner evidence and outbound transport failures, retaining the original validation cause. It rejects null Account originals and oversized individual membership or entitlement snapshots, and applies the canonical slug grammar before Account-source owner reads. R92 freshly passes 383 Entity unit cases, 70 Entity PostgreSQL cases and 2,530 Game Session unit cases with affected static analysis, formatting and documentation checks. The new cases cover each exact 1 MiB snapshot limit, each one-byte overflow, null-original classification, 65-character slug rejection before any owner read and exact-64 request acceptance. R94 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These are controlled component and isolated runtime proofs, without genuine source custody, created-roster consumption, runtime registration, successful public admission or activation. +The release-evidence correction at `ee9482ca8debfa7c5cf881b3aced2213bcb6504e` aligns Game Session with Entity’s existing full immutable-release validation and binds the association, World release and publication operation to byte-identical World evidence. R114 passes the complete Game Session check, formatting and static analysis with 2,531 unit cases, 357 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. The added unit case exercises nine independently mismatched release/World fields. R115 freshly rebuilds that code and passes held Gateway/Telnet denial and the isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline; authenticated teardown and independent exact-project inspection confirm no remaining containers, networks or volumes. These results qualify the source correction and packaging, without registering this source or establishing successful public admission. + +The preceding combined review correction at `5cdb2224f95cfc248a26b6c77de3d8425ede5bf2` preserves distinct source-client classifications for malformed caller input, invalid authenticated owner evidence and outbound transport failures, retaining the original validation cause. It rejects null Account originals and oversized individual membership or entitlement snapshots, and applies the canonical slug grammar before Account-source owner reads. R92 freshly passes 383 Entity unit cases, 70 Entity PostgreSQL cases and 2,530 Game Session unit cases with affected static analysis, formatting and documentation checks. The new cases cover each exact 1 MiB snapshot limit, each one-byte overflow, null-original classification, 65-character slug rejection before any owner read and exact-64 request acceptance. R94 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These are controlled component and isolated runtime proofs, without genuine source custody, created-roster consumption, runtime registration, successful public admission or activation. Unchanged Common proof remains 1,001 cases from R65; R69 passed 49 Game Session PostgreSQL and 14 cross-service cases, while all 22 Communication cases first failed on the same PostgreSQL connection refusal in R69 and passed unchanged in R70 (cause unproven). None of these earlier results was freshly rerun in R92. From bd032b622d7696ebfeeab462d9c2907b9eed8765 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 05:05:31 +1300 Subject: [PATCH 13/14] docs: record created-source parent reconciliation proof --- .../implementation-tracking/player-access-and-session.md | 2 ++ 1 file changed, 2 insertions(+) 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 c4666cb495..fd007c80bc 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for player access and session. Ca ### 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. + The release-evidence correction at `ee9482ca8debfa7c5cf881b3aced2213bcb6504e` aligns Game Session with Entity’s existing full immutable-release validation and binds the association, World release and publication operation to byte-identical World evidence. R114 passes the complete Game Session check, formatting and static analysis with 2,531 unit cases, 357 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. The added unit case exercises nine independently mismatched release/World fields. R115 freshly rebuilds that code and passes held Gateway/Telnet denial and the isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline; authenticated teardown and independent exact-project inspection confirm no remaining containers, networks or volumes. These results qualify the source correction and packaging, without registering this source or establishing successful public admission. The preceding combined review correction at `5cdb2224f95cfc248a26b6c77de3d8425ede5bf2` preserves distinct source-client classifications for malformed caller input, invalid authenticated owner evidence and outbound transport failures, retaining the original validation cause. It rejects null Account originals and oversized individual membership or entitlement snapshots, and applies the canonical slug grammar before Account-source owner reads. R92 freshly passes 383 Entity unit cases, 70 Entity PostgreSQL cases and 2,530 Game Session unit cases with affected static analysis, formatting and documentation checks. The new cases cover each exact 1 MiB snapshot limit, each one-byte overflow, null-original classification, 65-character slug rejection before any owner read and exact-64 request acceptance. R94 rebuilds fresh images at that code checkpoint and passes held Gateway/Telnet denial plus isolated backend WebSocket `WORLDS` / `LOGIN` / `PLAY` / `LOOK`; authenticated teardown succeeds and independent exact-project inspection confirms no remaining containers, networks or volumes. These are controlled component and isolated runtime proofs, without genuine source custody, created-roster consumption, runtime registration, successful public admission or activation. From 947a02d859027bbef2a5f2eb595061c8c57bbbec Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:51:51 +1300 Subject: [PATCH 14/14] Record focused proof for created-source parent reconciliation --- .../implementation-tracking/player-access-and-session.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 15905fe60b..681b4c93cb 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,7 +8,9 @@ This is a non-normative implementation tracker for player access and session. Ca ### 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. +The latest parent carry receives the independently qualified roster retention and recovery corrections without changing this stage’s 23-file owned boundary. R368 freshly passes 13 Entity unit/mTLS cases, 36 Game Session unit/mTLS cases and 44 Game Session PostgreSQL cases, including current-pointer assertions and the inherited reference-owner recovery regressions, with zero failures, errors or skips. Root checks, enabled affected static analysis, formatting and documentation checks pass. The two shared-file merges preserve both this stage’s current-pointer/source assertions and the parent’s operation-UUID and proof-handoff corrections. Earlier runtime results retain their original source attribution; these focused results do not establish genuine authority, created-player admission or activation. + +The earlier 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. The release-evidence correction at `ee9482ca8debfa7c5cf881b3aced2213bcb6504e` aligns Game Session with Entity’s existing full immutable-release validation and binds the association, World release and publication operation to byte-identical World evidence. R114 passes the complete Game Session check, formatting and static analysis with 2,531 unit cases, 357 PostgreSQL cases and 36 cross-service cases, all with zero failures, errors or skips. The added unit case exercises nine independently mismatched release/World fields. R115 freshly rebuilds that code and passes held Gateway/Telnet denial and the isolated backend `WORLDS` / `LOGIN` / `PLAY` / `LOOK` baseline; authenticated teardown and independent exact-project inspection confirm no remaining containers, networks or volumes. These results qualify the source correction and packaging, without registering this source or establishing successful public admission.